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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…