C if-else
Used for conditional execution of code.
A block of code is given and execueted to check if a given condition is true or flase. It goes for another block if the condition is false. Syntax
A block of code is given and execueted to check if a given condition is true or flase. It goes for another block if the condition is false. Syntax
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Example
#include <stdio.h>
int main() {
int num = 10;
// Check if num is even or odd
if (num % 2 == 0) {
printf("%d is even.\n", num);
} else {
printf("%d is odd.\n", num);
}
return 0;
}
The above example checks the condition if num % 2 == 0
if the condition is false then it goes to the else block.
if the condition is false then it goes to the else block.
C else if
Multiple conditions are checked using else if.
Syntax
Syntax
if (condition1) {
// Code to be executed if the condition1 is true
} else if(condition2) {
// Code to be executed if the condition1 is false and condition2 is true
} else {
// Code to be executed if all conditions are false
}
Example
#include <stdio.h>
int main() {
int score = 75;
// Grading based on the score
if (score >= 90) {
printf("Grade A\n");
} else if (score >= 80) {
printf("Grade B\n");
} else if (score >= 70) {
printf("Grade C\n");
} else {
printf("Grade F\n");
}
return 0;
}
Quick Recap
Topics Covered
C if - else
Practice With Examples in Compilers
The Concepts and codes you leart practice in Compilers till you are confident of doing on your own. A Various methods of examples, concepts, codes availble in our websites. Don't know where to start Down some code examples are given for this page topic use the code and compile
Example 1
Example 1
Example 2
Example 3
Example 4
Example 5