• conditional branchingstatements are used to control the flow of
execution based on conditions.
• These statements allow a program to choose different paths of
execution depending on whether a condition is true or false.
• A condition is usually formed using:
• Relational operators (<, >, <=, >=, ==, !=)
• Logical operators (&&, ||, !)
The if Statement
Theif statement is used to execute a block of code only when a given
condition is true.
Syntax
if (condition)
{
statement(s);
}
5.
Program: Check whethera number is positive
#include <stdio.h>
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num > 0)
{
printf("The number is
positive");
}
return 0;
Sample Output
Enter a number: 5
The number is positive
6.
The if–else Statement
•The if–else statement allows execution of one block when the condition is true
and another block when the condition is false.
Syntax
if (condition)
{
statement(s);
}
else
{
statement(s);
}
7.
Program: Check whethera number is even or odd
#include <stdio.h>
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num % 2 == 0)
{
printf("The number is even");
}
else
{
printf("The number is odd");
}
return 0;
}
Sample Output
Enter a number: 7
The number is odd
8.
Nested if–else Statement
Whenan if or else block contains another if–else statement, it is called
nested if–else. Syntax
if (condition1)
{
if (condition2)
{
statement(s);
}
else
{
statement(s);
}
}
else
{
statement(s);
/*C program tofind the largest number among
three number */
// using nested if-else
#include <stdio.h>
int main()
{
int c = 10, b = 22, a = 9;
/* Finding largest by comparing using
relational operators */
if (a > b) {
if (a > c)
printf("%d is the largest number.", a);
else
printf("%d is the largest number.", c);
}
else {
if (b > c)
printf("%d is the largest number.", b);
else
printf("%d is the largest number.", c);
}
return 0;
}
Output
The numbers A, B and C are: 10, 22, 9
22 is the largest number.
11.
If-else-if statement/ else–ifLadder
The else–if ladder is used to check multiple conditions
sequentially.
As soon as a condition becomes true, the corresponding block
is executed and the rest are skipped.