If else Statement in C Programming
- Tech Area
- April 25, 2024
In this tutorial, We will see how to use if and if else statement in C programming language.
C if Statement
The syntax of the if
statement in C programming is:
if (test expression)
{
// code
}
How if statement works?
The if
statement evaluates the test expression inside the parenthesis ()
.
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.
if statement
// Program to display a number if it is negative
#include<stdio.h>
#include<conio.h>
void main()
{
int number;
clrscr();
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 example.");
getch();
}
Output 1
Enter an integer: -1
You entered -1.
The if statement example.
When the user enters -1, the test expression number<0
is evaluated to true. Hence, You entered –1 is displayed on the screen.
Output 2
Enter an integer: 2
The if statement example.
When the user enters 2, the test expression number<0
is evaluated to false and the statement inside the body of if
is not executed
C if….else Statement
The if
statement may have an optional else
block. The syntax of the if..else
statement is:
if (test expression) {
// run code if test expression is true
}
else {
// run code if test expression is false
}
How if…else statement works?
If the test expression is evaluated to true,
statements inside the body of if
are executed.
statements inside the body of else
are skipped from execution.
If the test expression is evaluated to false,
statements inside the body of else
are executed.
statements inside the body of if
are skipped from execution.
if….else statement
#include<stdio.h>
#include<conio.h>
void main()
{
int age;
clrscr();
printf("Enter your age = ");
scanf("%d", &age);
// true if age is greater than and equal to 18
if (age>=18) {
printf("You can vote.");
}
else {
printf("You can not vote.");
}
getch();
}
Output
Enter your age = 12
You can not vote.
When the user enters 12, the test expression age>=18
is evaluated to false. Hence, the statement inside the body of else
is executed.
Join 10,000+ subscriber