C If Else Statement
C If Else Statement
C If Else Statement
else Statement
In this tutorial, you will learn about if statement (including if...else
and nested if..else) in C programming with the help of examples.
C if Statement
The syntax of the if statement in C programming is:
if (test expression)
{
// statements to be executed if the test expression is true
}
Example 1: if statement
#include <stdio.h>
int main() {
int number;
return 0;
}
Output 1
Enter an integer: -2
You entered -2.
The if statement is easy.
When the user enters -2, the test expression number<0 is evaluated
to true. Hence, You entered -2 is displayed on the screen.
Output 2
Enter an integer: 5
The if statement is easy.
When the user enters 5, 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) {
// statements to be executed if the test expression is true
}
else {
// statements to be executed if the test expression is false
}
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
return 0;
}
Output
Enter an integer: 7
7 is an odd integer.
C if...else Ladder
The if...else statement executes two different codes depending
upon whether the test expression is true or false. Sometimes, a
choice has to be made from more than 2 possibilities.
The if...else ladder allows you to check between multiple test
expressions and execute different statements.
if (test expression1) {
// statement(s)
}
else if(test expression2) {
// statement(s)
}
else if (test expression3) {
// statement(s)
}
.
.
else {
// statement(s)
}
#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
return 0;
}
Output
#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
return 0;
}
If the body of an if...else statement has only one statement, you
do not need to use brackets {} .
For example, this code
if (a > b) {
print("Hello");
}
print("Hi");
is equivalent to
if (a > b)
print("Hello");
print("Hi");