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:
- The program starts by including the necessary header file
stdio.h
, which provides input/output functions likeprintf
. - The
main
function is defined, which is the entry point of the program. - A variable
num
is declared and assigned a value of 10. - The first
if
statement checks ifnum
is greater than 0. If it is, the code inside the block is executed. - Inside the first
if
block, the program prints "The number is positive." to the console using theprintf
function. - The nested
if
statement checks ifnum
is divisible by 2 (i.e., even). If it is, the code inside the block is executed. - Inside the nested
if
block, the program prints "The number is even." to the console. - If the condition of the nested
if
statement is not true (i.e.,num
is not even), the code inside theelse
block is executed, and the program prints "The number is odd." to the console. - If the condition of the first
if
statement is not true (i.e.,num
is not greater than 0), the code inside theelse
block is executed, and the program prints "The number is negative." to the console. - The
main
function ends with areturn 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.