Conditional Statements
Conditional Statements
You have already learned that C supports the usual logical conditions from mathematics:
You can use these conditions to perform different actions for different decisions.
The if Statement
The if in C is a decision-making statement that is used to execute a block of
code based on the value of the given expression.
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
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
In the example below, we test two values to find out if 20 is greater than 18. If the condition
is true, print some text:
Example
if (20 > 18) {
printf("20 is greater than 18");
}
Example
int x = 20;
int y = 18;
if (x > y) {
printf("x is greater than y");
}
void main()
{
int gfg = 9;
// if statement with true condition
if (gfg < 10) {
printf("%d is less than 10", gfg);
}
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
}
Example
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
// Outputs "Good evening."
}
return 0;
}
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
}
Example
int time = 22;
if (time < 10) {
printf("Good morning.");
} else if (time < 20) {
printf("Good day.");
} else {
printf("Good evening.");
}
// Outputs "Good evening."
return 0;
}
#include <stdio.h>
int main()
{
int year;
/*
* If year is exactly divisible by 4 and year is not divisible by 100
* or year is exactly divisible by 400 then
* the year is leap year.
* Else year is normal year
*/
if(((year % 4 == 0) && (year % 100 !=0)) || (year % 400==0))
{
printf("LEAP YEAR");
}
else
{
printf("COMMON YEAR");
}
return 0;
}
int main()
{
int num;
if(num > 0)
{
printf("Number is POSITIVE");
}
if(num < 0)
{
printf("Number is NEGATIVE");
}
if(num == 0)
{
printf("Number is ZERO");
}
return 0;
}
int main()
{
char ch;
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
printf("Character is an ALPHABET.");
}
else
{
printf("Character is NOT ALPHABET.");
}
return 0;
}
#include <stdio.h>
int main()
{
char ch;
return 0;
}