C If Statement
C If Statement
else Statement
In this tutorial, you will learn about if statement (including if...else and nested
if..else) in C programming with the help of examples.
C if Statement
The syntax of the if statement in C programming is:
1. if (test expression)
2. {
3. // statements to be executed if the test expression is true
4. }
To learn more about when test expression is evaluated to true (non-zero value) and
false (0), check relational and logical operators.
Example 1: if statement
1. // Program to display a number if it is negative
2.
3. #include <stdio.h>
4. int main()
5. {
6. int number;
7.
8. printf("Enter an integer: ");
9. scanf("%d", &number);
10.
11. // true if number is less than 0
12. if (number < 0)
13. {
14. printf("You entered %d.\n", number);
15. }
16.
17. printf("The if statement is easy.");
18.
19. return 0;
20. }
Output 1
Enter an integer: -2
You entered -2.
The if statement is easy.
When the user enters -2, the test expression number<0 is evaluated to true. Hence, You
entered -2 is displayed on the screen.
Output 2
Enter an integer: 5
The if statement is easy.
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
C if...else Statement
The if statement may have an optional else block. The syntax of
the if..else statement is:
1. if (test expression) {
2. // statements to be executed if the test expression is true
3. }
4. else {
5. // statements to be executed if the test expression is false
6. }
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.
C if...else Ladder
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.
Nested if...else
It is possible to include an if...else statement inside the body of
another if...else statement.
If the body of an if...else statement has only one statement, you do not need to use
brackets {}.
1. if (a > b) {
2. print("Hello");
3. }
4. print("Hi");
is equivalent to
1. if (a > b)
2. print("Hello");
3. print("Hi");