nested if example in c

Nested if example in C

Here is an example of a nested if statement in C:

#include <stdio.h>

int main() {
   int num = 10;

   if (num > 0) {
      printf("The number is positive.\n");

      if (num % 2 == 0) {
         printf("The number is even.\n");
      } else {
         printf("The number is odd.\n");
      }
   } else {
      printf("The number is negative.\n");
   }

   return 0;
}

Explanation of each step:

  1. The program starts by including the necessary header file stdio.h, which provides input/output functions like printf.
  2. The main function is defined, which is the entry point of the program.
  3. A variable num is declared and assigned a value of 10.
  4. The first if statement checks if num is greater than 0. If it is, the code inside the block is executed.
  5. Inside the first if block, the program prints "The number is positive." to the console using the printf function.
  6. The nested if statement checks if num is divisible by 2 (i.e., even). If it is, the code inside the block is executed.
  7. Inside the nested if block, the program prints "The number is even." to the console.
  8. If the condition of the nested if statement is not true (i.e., num is not even), the code inside the else block is executed, and the program prints "The number is odd." to the console.
  9. If the condition of the first if statement is not true (i.e., num is not greater than 0), the code inside the else block is executed, and the program prints "The number is negative." to the console.
  10. The main function ends with a return 0; statement, indicating successful program execution.

This example demonstrates how nested if statements can be used to perform conditional branching based on multiple conditions. The inner if statement is only executed if the outer if statement's condition is true.