When programs contain conditions statements are used.
if statement
If the statement is used when the program has one condition and related output.
#include<stdio.h>
#include<conio.h>
int main(){
int n;
printf("Enter a value:");
scanf("%d", &n);
if(n%2==0){
printf("Even.");
}
getch();
return 0;
}
if-else statement
This statement is used when the program has one condition and related two outputs.
#include<stdio.h>
#include<conio.h>
int main(){
int n;
printf("Enter a value:");
scanf("%d", &n);
if(n%2==0){
printf("Even.");
}
else{
printf("Odd.");
}
getch();
return 0;
}
if-else if statement
This statement is used when a program has multiple conditions and related output.
#include<stdio.h>
#include<conio.h>
int main(){
int n;
printf("Enter 10th class percentage:");
scanf("%d", &n);
if(n>=60){
printf("First division.");
}
else if(n>=45){
printf("Second division.");
}
else if(n>=33){
printf("Third division.");
}
else{
printf("Fail.");
}
getch();
return 0;
}
Nested if statement
This statement is used when a program has a condition within a condition.
#include<stdio.h>
#include<conio.h>
int main(){
int a,b,c;
printf("Enter three different numbers:");
scanf("%d %d %d", &a, &b, &c);
if(a>b){
if(a>c){
printf("A is greater.");
}
else{
printf("C is greater.");
}
}
else if(b>a){
if(b>c){
printf("B is greater.");
}
else{
printf("C is greater.");
}
}
getch();
return 0;
}
Conditional statements
It is an alternative to the if-else statement, or it is also called the single-line statement
#include<stdio.h>
#include<conio.h>
int main(){
int n;
printf("Enter a value:");
scanf("%d", &n);
n%2 == 0 ? printf("Even.") : printf("Odd.");
getch();
return 0;
}
Switch statements
It is an alternative of an if-else if statement to check multiple conditions in a single program.
#include<stdio.h>
#include<conio.h>
int main(){
int day;
printf("Enter a number from 1-7:");
scanf("%d", &day);
switch(day){
case 1:
printf("Sunday.");
break;
case 2:
printf("Monday.");
break;
case 3:
printf("Tuesday.");
break;
case 4:
printf("Wednesday.");
break;
case 5:
printf("Thursday.");
break;
case 6:
printf("Friday.");
break;
case 7:
printf("Saturday.");
break;
default:
printf("Invalid value.");
break;
}
getch();
return 0;
}