LearnFrenzy
Sign in Take a free test

Decision Making · Decision Making Programs · Question 1

Largest of four numbers in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Find the largest of four integers using simple comparisons.

Solution
main.c
#include <stdio.h>

int max4(int a, int b, int c, int d) {
    int m = a;              /* the best so far */
    if (b > m) m = b;
    if (c > m) m = c;
    if (d > m) m = d;
    return m;
}

int main(void) {
    printf("%d %d\n", max4(12, 45, 7, 45), max4(-3, -8, -1, -6));
    return 0;
}

Output Verified by compiling and running

45 -1

Keeping a running maximum needs exactly three comparisons for four values and scales to any number of values, unlike nested if-else trees. Starting from a (not 0) handles negative numbers.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links