C if...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. }

How if statement works?

The if statement evaluates the test expression inside the parenthesis ().
  • If the test expression is evaluated to true, statements inside the body of if are executed.
  • If the test expression is evaluated to false, statements inside the body of if are not executed.
How if statement works in C programming?
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. #include <stdio.h>
  3. int main()
  4. {
  5. int number;
  6. printf("Enter an integer: ");
  7. scanf("%d", &number);
  8. // true if number is less than 0
  9. if (number < 0)
  10. {
  11. printf("You entered %d.\n", number);
  12. }
  13. printf("The if statement is easy.");
  14. return 0;
  15. }
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.

Comments