What is a if else statement in c

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. int number;
  5. printf("Enter an integer: ");
  6. scanf("%d", &number);
  7. // true if number is less than 0
  8. if (number < 0) {
  9. printf("You entered %d.\n", number);
  10. }
  11. printf("The if statement is easy.");
  12. return 0;
  13. }
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. }

How if...else statement works?

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.
How if...else statement works in C programming?

Example 2: if...else statement

  1. // Check whether an integer is odd or even
  2. #include <stdio.h>
  3. int main() {
  4. int number;
  5. printf("Enter an integer: ");
  6. scanf("%d", &number);
  7. // True if the remainder is 0
  8. if (number%2 == 0) {
  9. printf("%d is an even integer.",number);
  10. }
  11. else {
  12. printf("%d is an odd integer.",number);
  13. }
  14. return 0;
  15. }

Post a Comment

0 Comments