Conditional Statements
Use if to specify a block of code to be executed, if a specified condition
is true
Use else to specify a block of code to be executed, if the same condition
is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed.
The if Statement
Use the if statement to specify a block of code to be executed if a
condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
#include <stdio.h>
int main() {
if (20 > 18) {
printf("20 is greater than 18");
return 0;
The else Statement
Use the else statement to specify a block of code to be executed if the
condition is false.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
#include<stdio.h>
int main(){
int number=0;
printf("Enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
else
{
printf("odd number");
}
return 0;
}
The else if Statement
Use the else if statement to specify a new condition if the first condition
is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}
#include <stdio.h>
int main() {
int time = 22;
if (time < 10) {
printf("Good morning.");
} else if (time < 20) {
printf("Good day.");
} else {
printf("Good evening.");
return 0;
C Program to Calculate Grade of Student
#include <stdio.h>
int main(void)
{
int num;
printf("Enter your mark ");
scanf("%d",&num);
printf(" You entered %d Marks n", num);
if(num >= 80){
printf(" You got A grade n");
}
else if ( num >=60)
{
printf(" You got B grade n");
}
else if ( num >=40){
printf(" You got C grade n");
}
else if ( num < 40){
printf(" You Failed in this exam n");
printf(" Better Luck Next Time n");
}
return 0;
}