In C and C++, conditional statements are used to make decisions in your code based on certain conditions. These conditions are generally expressed using logical expressions that evaluate to either true or false. Here, I will explain various conditional statements in C and provide examples for each:
1. if statement:
- The if
statement is used to execute a block of code if a specified condition is true.
#include <stdio.h>
int main() {
int x = 5;
if (x > 0) {
printf("x is positive\n");
}
return 0;
}
In this example, the code inside the if
block will execute because the condition x > 0
is true.
2. if-else statement:
- The if-else
statement is used when you want to execute one block of code if a condition is true and another block of code if the condition is false.
#include <stdio.h>
int main() {
int x = -3;
if (x > 0) {
printf("x is positive\n");
} else {
printf("x is non-positive\n");
}
return 0;
}
In this example, because x
is negative, the code inside the else
block will execute.
3. if-else if statement:
- The if-else if
statement is used when you have multiple conditions to check, and you want to execute different code blocks based on the first condition that is true.
#include <stdio.h>
int main() {
int x = 0;
if (x > 0) {
printf("x is positive\n");
} else if (x < 0) {
printf("x is negative\n");
} else {
printf("x is zero\n");
}
return 0;
}
In this example, because x
is zero, the code inside the final else
block will execute.
4. Shorthand if-else (Ternary operator):
- The shorthand if-else is a compact way to write a simple conditional statement in a single line.
#include <stdio.h>
int main() {
int x = 7;
int result;
result = (x > 0) ? 1 : 0;
printf("The result is %d\n", result);
return 0;
}
In this example, the ternary operator assigns the value 1 to result
if x > 0
, and 0 if it's not true.
These are the basic conditional statements in C/C++. They allow you to control the flow of your program based on different conditions, making your code more flexible and capable of responding to various situations.