If statement in C programming with example



If statement in C programming with example



 When we need to execute a block of statements only when a given condition is true then we use if statement. In the next tutorial, we will learn C if..else, nested if..else and else..if.

C – If statement

Syntax of if statement:
The statements inside the body of “if” only execute if the given condition returns true. If the condition returns false then the statements inside “if” are skipped.
if (condition)
{
//Block of C statements here
//These statements will only execute if the condition is true
}

Flow Diagram of if statement

Example of if statement

#include <stdio.h>
int main()
{
int x = 20;
int y = 22;
if (x<y)
{
printf
("Variable x is less than y");
}
return 0;
}
Output:
Variable x is less than y
Explanation: The condition (x<y) specified in the “if” returns true for the value of x and y, so the statement inside the body of if is executed.

Example of multiple if statements

We can use multiple if statements to check more than one conditions.
#include <stdio.h>
int main()
{
int x, y;
printf
("enter the value of x:");
scanf
("%d", &x);
printf
("enter the value of y:");
scanf
("%d", &y);
if (x>y)
{
printf
("x is greater than y\n");
}
if (x<y)
{
printf
("x is less than y\n");
}
if (x==y)
{
printf
("x is equal to y\n");
}
printf
("End of Program");
return 0;
}
In the above example the output depends on the user input.
Output:
enter the value of x:20
enter the value of y
:20
x
is equal to y
End of Program

Post a Comment

Previous Post Next Post