if Statement in C Programming
Decision Making in C
In this lesson, we will understand what if statement is and how to use it in C programming along with some example.
What is if Statement
The if statement is the most simple decision making statement in C programming. Using if statement we test some condition, if the condition is true then a block of statements is executed otherwise not.
if Statement Syntax
if(condition)
{
/* Statements to execute if
condition is true */
}
In the above syntax inside the brackets ( ) of if statement we will write our condition. If the condition is true then the statements written within the curly braces { } of if statement will execute otherwise not. We can write our condition using Arithmetic, Relational and Logical operators.
Now let's see some examples for more understanding.
Example 1 (Condition using Relational operator)
C program to check if an integer variable's value is greater than 10.
#include <stdio.h>
#include <conio.h>
int main()
{
int a=25;
if(a>10)
{
printf("Yes %d is greater than 10",a);
}
return 0;
}
Output
Yes 25 is greater than 10
Here you can see that the condition (a>10) is true because the value of a is greater than 10. So the statement which is written inside the curly braces of if statement has executed and the output is printed on the screen.
Example 2 (Condition using Arithmetic and Relational operator)
C program to check if the sum of 2 integer variable's value is greater than 10.
#include <stdio.h>
#include <conio.h>
int main()
{
int a=10, b=5;
if(a+b>10)
{
printf("Yes %d is greater than 10",a+b);
}
return 0;
}
Output
Yes 15 is greater than 10
Here you can see that we have used Arithmetic and Relational operator in the condition (a+b>10) and the condition is also true because the value of a+b is greater than 10. So the statement which is written inside the curly braces of if statement has executed and the output is printed on the screen.
Example 3 (Condition using Arithmetic, Relational and Logical operator)
C program to check if an integer variable's value is an even number and is also greater than 10.
#include <stdio.h>
#include <conio.h>
int main()
{
int a=18;
if(a%2==0 && a>10)
{
printf("%d is an even number and is also greater than 10",a);
}
return 0;
}
Output
18 is an even number and is also greater than 10
Here you can see that we have used Arithmetic, Relational and Logical operator in the condition (a%2==0 && a>10) and both the conditions a%2==0 and a>0 are also true because the remainder of the modulus division a%2 is equal to 0 and also value of a is greater than 10. So the statement which is written inside the curly braces of if statement has executed and the output is printed on the screen.