As we have already seen that the if statement by itself will execute a single statement, or a group of statements when the expression following if evaluates to true, though it does nothing when the expression evaluates to false. Hence, for this distinct case, we need the else statement, which evaluates an expression when the condition is false.
The if block gets executed when the given condition is reached i.e., the condition is true, whereas, the else block is executed when the condition is false.
#include <stdio.h>
int main() {
int age;
printf("Enter Age: ");
scanf("%d",&age);
if(age>18)
printf("Person is an adult for voting.");
else
printf("Person is underage for voting.");
return 0;
}
Enter Age: 12
Person is underage for voting.
Enter Age: 34
Person is an adult for voting.
The nested if-else means an if-else statement within an if or else block. Let’s take an example for better understanding:
#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
if (number1 >= number2) {
if (number1 == number2) {
printf("Result: %d = %d",number1,number2);
}
else {
printf("Result: %d > %d", number1, number2);
}
}
else {
printf("Result: %d < %d",number1, number2);
}
return 0;
}
Enter two integers: 43 23
Result: 43 > 23
Note: also read about Format specifiers in C & Decision-Making in C
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Find the length of the longest absolute path to a file within the abstracted file…
You manage an e-commerce website and need to keep track of the last N order…
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…