Hi friends, in this tutorial you will learn how to write a program to find the greatest of three numbers in c using nested if statement.
The logic of the program:-
- First of all, we will declare four integer variables as a,b,c, and big. here ‘big’ is used to store the result.
- Inside the first if condition, We will compare ‘a’ with ‘b’. If ‘a’ is greater than ‘b’ then we will compare ‘a’ to ‘c’. In this case if ‘a’ is greater than ‘c’ then ‘a will be stored to the resultant variable ‘big’. On the other hand, if ‘c’ is greater than ‘a’ then ‘c’ will be stored to the resultant variable ‘big’.
- Inside the else condition, we will compare ‘b’ with ‘c’. If ‘b’ is greater than ‘c’ then ‘b’ will be stored to the resultant variable ‘big’. On the other hand, if ‘c’ is greater than ‘b’ then ‘c’ will be stored to the resultant variable ‘big’.
Also read, Biggest of Two Numbers in C Language
Example to find the greatest of three numbers in C using nested if statement
#include<stdio.h>
main()
{
int a,b,c,big;
printf("\n Enter the three numbers: ");
scanf("%d%d%d",&a,&b,&c);
//if condition to compare a and b
if(a>b)
{
//another if condition to a and c
if(a>c)
{
big = a;
}
else
{
big = c;
}
}
else
{
//another if condition to compare b and c
if(b>c)
{
big = b;
}
else
{
big = c;
}
}
printf("\n Biggest number is: %d",big);
}
After running the above program, the user has to enter three numbers manually using space and press the ENTER key. After the execution of the program, the result will be displayed as shown below.
Enter the three numbers: 3 -5 6
Biggest number is: 6
Process returned 0 (0x0) execution time : 7.404 s
Press any key to continue.
Conclusion:- I hope this tutorial will help you to understand the logic of the program. If there is any doubt then please leave a comment below.