• The if statement evaluates the test
expression inside the .
• If the test expression is evaluated to
, statements inside the body of
.
• If the test expression is evaluated to
, statements inside the body
.
Output 1
// Program to display a number if it is
negative
#include <stdio.h>
int main() { The if statement is easy.
int number; When the user enters -2, the test expression number<0 is evaluated
printf("Enter an integer: "); to true. Hence, You entered -2 is displayed on the screen.
scanf("%d", &number);
// true if number is less than 0 Output 2
When the user enters 5, the test expression number<0 is evaluated
to false and the statement inside the body of if is not executed
printf("The if statement is easy.");
return 0;
}
If the test expression is evaluated to
true,
• statements inside the body of if are
executed.
• statements inside the body of else are
skipped from execution.
If the test expression is evaluated to
false,
• statements inside the body of else are
executed
• statements inside the body of if are
skipped from execution.
Output
When the user enters 7, the test expression
number%2==0 is evaluated to false. Hence, the
statement inside the body of else is executed.
The if...else statement executes two different codes depending
upon whether the test expression is true or false.
Sometimes, a choice has to be made from more than 2 possibilities.
The if...else ladder allows you to check between multiple test
expressions and execute different statements.
if (test expression1) {
// statement(s)
}
else if(test expression2) {
// statement(s)
}
else if (test expression3) {
// statement(s)
}
.
.
else {
// statement(s)
}
It is possible to include an if...else statement inside the
body of another if...else statement.