You are on page 1of 3

Chapter: 4 Control structure 2.

If-else statement
- In this case, either of two statements is executed depending upon the
1. If statement value of expression. Statement-1 us executed if the expression is true,
- When there is a single option to be executed on the basis of TRUE else statements-2 is executed.
result of a condition, then if () statement is used. - Syntax:
- Syntax: If(condition)
If(condition) {
{ Block if statements;
Block if statements; }
} else
- Flowchart: {
Block if statements;
}

- Flowchart:

Example: WAP to check a given number is even or odd.

#include <stdio.h>
#include<conio.h>
void main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
// True if num is perfectly divisible by 2
if(num % 2 == 0)
{
printf("%d is even.", num);
}
if(num % 2 == 1)
{ Example: WAP to check a given number is even or odd.
printf("%d is odd.", num);
} #include <stdio.h>
getch(); #include<conio.h>
} void main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
// True if num is perfectly divisible by 2
if(num % 2 == 0)
{
printf("%d is even.", num);
}
else
{
printf("%d is odd.", num);
}
getch();
}

3. Nested If-else statement


- The if else statement which is again if else statements repeated is called
nested if else statements.
- Syntax:
Example: WAP to inpuy three different numbers and find the largest among three
if (Condition1) numbers.
{
if(Condition2) #include <stdio.h>
{ void main() {
Statement1; int a,b,c;
} printf("Enter three numbers: ");
else scanf("%d%d%d", &a, &b, &c);
{
Statement2; if (a >b) {
} if (a >c)
} printf("%d is the largest number.", a);
else else
{ printf("%d is the largest number.", c);
if(Condition3) } else {
{ if (b >c)
Statement3; printf("%d is the largest number.", b);
} else
else printf("%d is the largest number.", c);
{ }
Statement4; Getch();
} }
}

- Flowchart:
if (b >c)
4. If-else if statement printf("%d is the largest number.", b);
else
- When there is a need to select an option for execution out of multiple printf("%d is the largest number.", c);
options on the basis of the result of multiple condition then if else if }
statement is used. Getch();
}
- Syntax:

if (Condition1)
{
Statement_1;
}
elseif(Condition2)
{
Statement2;
}
Elseif(Condition)
{
Statement3;
}
------------
----------
else
{
Statement 4;
}
- Flowchart:

Example: WAP to inpuy three different numbers and find the largest among three
numbers.

#include <stdio.h>
void main() {
int a,b,c;
printf("Enter three numbers: ");
scanf("%d%d%d", &a, &b, &c);

if (a >b) {
if (a >c)
printf("%d is the largest number.", a);
else
printf("%d is the largest number.", c);
} else {

You might also like