If( test expression )
Statement block if TRUE
If( test expression )
{
Statement block if condition TRUE
}else{
Statement block if condition False
}
#include <stdio.h>
int main(void){
int num1;
printf("Enter the number ");
scanf("%d",&num1); // Enter numbers
if(num1 <= 10)
{
printf(" Your number is less than or equal to ten");
}
else
{
printf(" Your number is more than ten"); // printng outputs
}
return 0;
}
#include <stdio.h>
int main(void){
int num;
printf("Enter a number less then or equal to 100 : ");
scanf("%d",&num);
if(num >= 80)
printf(" First Division " );
else {
if(num>= 60){
printf(" Second Division ");
}else{
if( num>=40){
printf(" Third Division ");
}else{
printf(" Fail ");
}
}
}
return 0;
}
if(expression is true){
// statement to execute
}
else if ( expression is true){
// statement to execute
}else if ( expression is true){
// statement to execute
}
else {
// final statement to execute if nothing is ture
}
Example
int main()
{
int x=20;
if(x>=30){
printf(" I am greater than or equal to 30 \n");
}else if(x<20){
printf(" I am less than 20 \n");
}else
printf("I am greate than or equal to 20 but less than 30 \n");
}
This example demonstrates how to use a simple if-else statement to check if a number is positive or negative.
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num >= 0) {
printf("%d is positive.\n", num);
} else {
printf("%d is negative.\n", num);
}
return 0;
}
Output:
Enter a number: 5
5 is positive.
---
This example shows how to use if-else if-else to categorize an age.
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age < 13) {
printf("You are a child.\n");
} else if (age < 20) {
printf("You are a teenager.\n");
} else if (age < 60) {
printf("You are an adult.\n");
} else {
printf("You are a senior citizen.\n");
}
return 0;
}
Output:
Enter your age: 25
You are an adult.
---
This example demonstrates using nested if-else statements to check for even or odd numbers.
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num >= 0) {
if (num % 2 == 0) {
printf("%d is an even number.\n", num);
} else {
printf("%d is an odd number.\n", num);
}
} else {
printf("The number is negative.\n");
}
return 0;
}
Output:
Enter a number: 12
12 is an even number.
18-08-2023 | |
Write an if-else statement to check if the grade is above or equal to 60 |