C program to find the largest number among three numbers (Using, nested if-else)

by | Jan 11, 2023 | C, C Programs

Introduction

This program will find the largest number of the three numbers entered by the user. There are different methods to perform this code.

Here we will use the nested if-else loop

Moreover, to understand this program, you should know about

1. C programming operators

2. C nested if…else statement

Program

#include<stdio.h>
int main()
{ int x,y,z;
printf("enter three numbers:\n");
scanf("%d %d %d",&x,&y,&z);
if(x>y) // whether ‘x’ is greater than ‘y’
{
if(x>z) // whether ‘x’ is greater than ‘z’
{
printf("%d is the greatest number",x); // ‘x’ is greater of all
}
else
{
printf("%d is the greatest number",z);
}
}
else if(y>x) // whether ‘y’ is greater than ‘x’
{
if(y>z) // whether ‘y’ is greater than ‘z’
{
printf("%d is the greatest number",y);// ‘y’ is greater of all
}
else
{
printf("%d is the greatest number",z);
}
}
else // neither ‘x’ nor ‘y’ then ‘z’ is greatest among three
{
printf("% is greatest number",z);
}
}

 

Output

Explanation

In the above code, we take three values from the user and store them in x, y, z respectively.

if(x>y)

firstly, we check whether x is greater than y or not. If it is true then the body of the ‘if’ statement is executed. In its body, we will check whether x is greater than z using if(x>z) statement. If it gives a true result, it means ‘x’ is the greatest among all three.

If the above statement is false, then the else if statement i.e.

else if(y>x) will be executed, and the same process will be followed as above.

If this statement also gives a false result, then the last statement i.e.

else

{

printf(“% is greatest number”,z);

}

gets executed.

 

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.