If the test expression is evaluated to true, statements inside the body of if are executed. If the test expression is evaluated to false, statements inside the body of if are not executed. The if statement may have an optional else block.
if statement allows us to select an action based on some condition. It gives programmer to take control over a piece of code. Programmer can control the execution of code based on some condition or user input. For example - if user inputs valid account number and pin, then allow money withdrawal.
if statement works like "If condition is met, then execute the task". It is used to compare things and take some action based on the comparison. Relational and logical operators supports this comparison.
If statement perform action based on boolean expression true or false.
A C expression that evaluates either true or false is known as Boolean expression. However, in C programming there is no concept of true or false value.
In C we represent true with a non-zero integer and false with zero. Hence, in C if an expression evaluates to integer is considered as Boolean expression.
The syntax of the if statement in C programming is:
if(boolean_expression)
{
// body of if
}
Flowchart of if statement
Example if statement
// Program to display a number if it is negative
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// true if number is less than 0
if (number < 0) {
printf("You entered %d.\n", number);
}
printf("The if statement is easy.");
return 0;
}
Output
Enter an integer: -2
You entered -2.
The if statement is easy.
Simple if works as "if some condition is true then do some tasks". It doesn't specifies what to do if condition is false. A good program must think both ways. For example - if user inputs correct account number and pin, then allow money withdrawal otherwise show error message to user.
if...else statement is an extension of simple if. It works as "if some condition is true then, do some task otherwise do some other task".
Syntax of if...else statement
if(boolean_expression)
{
// Body of if
// If expression is true then execute this
}
else
{
// Body of else
// If expression is false then execute this
}
In above syntax if the given Boolean expression is true then, execute body of if part otherwise execute body of else part. In any case either body if or body of else is executed. In no case both the blocks will execute.
Flowchart of if...else statement
Example of if....else statement
// Check whether an integer is odd or even
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// True if the remainder is 0
if (number%2 == 0) {
printf("%d is an even integer.",number);
}
else {
printf("%d is an odd integer.",number);
}
return 0;
}
Output
Enter an integer: 7
7 is an odd integer.