LearnFrenzy
Sign in Take a free test

Control Instructions · Decision Making Programs · Question 1

Largest of three numbers in C (nested if and ternary) Solution, output & explanation

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

Write max3() that returns the largest of three integers, correct for negative and equal values.

Solution
main.c
#include <stdio.h>

int max3(int a, int b, int c) {
    if (a >= b)
        return a >= c ? a : c;
    else
        return b >= c ? b : c;
}

int main(void) {
    printf("%d %d %d\n", max3(3, 9, 4), max3(-1, -5, -2), max3(7, 7, 7));
    return 0;
}

Output Verified by compiling and running

9 -1 7

One comparison picks the bigger of a and b, and a conditional operator compares it with c. Using >= makes ties work, and nothing assumes the numbers are positive.

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