C If ... Else
Condation and C If ... Else statement
conditional statements and the if...else statement are fundamental tools for making decisions and controlling the flow of your program.
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
C offers a range of conditional statements to control the flow of your program based on specific conditions.
C has the following conditional statements:The if Statement
Use the if statement to specify a block of code to be executed if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
In the example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some text:
Example
#include <stdbool.h>
int main() {
if (20 > 18) {
printf("20 is greater than 18");
}
return 0;
}
Output
20 is greater than 18
We can also test variables:
Example
#include <stdbool.h>
int main() {
int x = 20;
int y = 18;
if (x > y) {
printf("x is greater than y");
}
return 0;
}
Output
x is greater than y
Example explained
In the above example we use two variables, x and y, to test whether x is greater than y using the (>) operator. Since x is 20, and y is 18, and we know that 20 is greater than 18, we print on the screen "x is greater than y".