C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Decision Making Programs in C

Find greatest among four numbers (nested if)

Introduction

To find the greatest number among four given numbers, we can use nested if-else statements.
The logic compares the numbers step by step, reducing the number of comparisons required.

Example:

  • Compare a and b → store larger in max1
  • Compare c and d → store larger in max2
  • Compare max1 and max2 → the larger one is the greatest

 

C Program: Find greatest among four numbers (nested if)

C

#include <stdio.h>

 

int main() {

    int a, b, c, d;

 

    // Input four numbers

    printf("Enter four numbers: ");

    scanf("%d %d %d %d", &a, &b, &c, &d);

 

    // Find greatest using nested if

    if (a > b) {

        if (a > c) {

            if (a > d) {

                printf("%d is the greatest number.\n", a);

            } else {

                printf("%d is the greatest number.\n", d);

            }

        } else {

            if (c > d) {

                printf("%d is the greatest number.\n", c);

            } else {

                printf("%d is the greatest number.\n", d);

            }

        }

    } else {

        if (b > c) {

            if (b > d) {

                printf("%d is the greatest number.\n", b);

            } else {

                printf("%d is the greatest number.\n", d);

            }

        } else {

            if (c > d) {

                printf("%d is the greatest number.\n", c);

            } else {

                printf("%d is the greatest number.\n", d);

            }

        }

    }

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter four numbers: 45 12 89 23
89 is the greatest number.

OUTPUT 2 :
Enter four numbers: 10 25 5 7
25 is the greatest number.

OUTPUT 3 :
Enter four numbers: 100 200 300 150
300 is the greatest number.
 

Explanation

  1. User inputs four integers: a, b, c, d.
  2. First, compare a and b.
  3. Then, compare the larger of those with c.
  4. Finally, compare the result with d.
  5. The greatest number is printed.