Explain if Else Statement in c Programming
Explain if Else Statement in c Programming
It provides a
way to execute one block of code if a specified condition is true and another block of code if the
condition is false. This allows for two distinct paths of execution based on the evaluation of a
single condition.
Syntax:
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Explanation:
1. if keyword: Marks the beginning of the conditional statement.
2. condition: An expression enclosed in parentheses (). This condition is evaluated to
determine its truthiness (non-zero value) or falsity (zero value).
3. if block (True block): The code enclosed within the curly braces {} immediately following
the if condition is executed only if the condition evaluates to true.
4. else keyword: This keyword follows the closing curly brace of the if block. It signifies the
alternative block of code to be executed when the if condition is false.
5. else block (False block): The code enclosed within the curly braces {} immediately
following the else keyword is executed only if the condition in the if statement evaluates
to false.
How it Works (Flow of Execution):
1. The program encounters the if-else statement.
2. The condition inside the parentheses is evaluated.
3. If the condition is true (evaluates to a non-zero value):
○ The code block within the if block is executed.
○ The code block within the else block is skipped.
○ The program then proceeds to the statement immediately following the closing curly
brace of the else block.
4. If the condition is false (evaluates to zero):
○ The code block within the if block is skipped.
○ The code block within the else block is executed.
○ The program then proceeds to the statement immediately following the closing curly
brace of the else block.
Example:
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number % 2 == 0) {
printf("%d is an even number.\n", number);
} else {
printf("%d is an odd number.\n", number);
}
printf("End of the program.\n");
return 0;
}