To find the largest among 3 numbers entered by the user in C programming, nested if can be used which is implemented in following program:
Example 1: Source Code to Find Largest Number Using nested if..else Statement
#include<stdio.h> int main() { int a,b,c; printf ("Enter three numbers n"); scanf("%d n %d n %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 { if(b>c) printf("%d is the largest number.",b); else printf("%d is the largest number.",c); } return 0; }
Here, the 3 numbers given by user is stored in variables a, b and c respectively. The first if statement checks if a>b, if it is true then second if statement is checked i.e. a>c, if this is also true then a is the largest among the three. If the second if condition is false (i.e. if a is not greater than c) then c is the largest among the three. However, if the first if condition is false (i.e. if a is not greater than b) then the condition b>c is checked, if this is true then b is the largest among the three and if this is false then c is the largest.
Example 2: Source Code to Find Largest Number Using if..else Statement
#include<stdio.h> #include<conio.h> int main() { int a,b,c; printf ("Enter three numbers n"); scanf ("%d n %d n %d", &a, &b, &c); if (a>b && a>c) printf ("%d is the largest number.", a); else if (b>a && b>c) printf ("%d is the largest number.", b); else printf ("%d is the largest number.", c); return 0; }
Here, the statement if (a>b && a>c) checks whether a is greater than both b and c and if it is true then displays “a is the largest”. If it is false then the second condition is checked. If the second statement is true then b is the largest is displayed and if this condition is also false then c is the largest is displayed.
Output
Enter three numbers 12 40 10 40 is the largest.