Empty Output on a program that prints the maximum number out of 3

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • elpidahope
    New Member
    • Jan 2022
    • 1

    Empty Output on a program that prints the maximum number out of 3

    I don't understand what's wrong. My program prints only half the output. It doesn't print the maximum number. Here's the code if you wanna check it.

    Code:
    #include <stdio.h>
    
    int main() {
    
        int a, b, c;
        int max;
    
        printf("\n1st number: ");
        scanf("%d", &a);
        printf("\n2nd number: ");
        scanf("%d", &b);
        printf("\n3rd number: ");
        scanf("%d", &c);
    
        if (b > a && b > c){
            max = b;
            printf("\nMax number is ", max);
        }
        if (c > a && c > b){
            max = c;
            printf("\nMax number is ", max);
        }
        if (a > b && a > c){
            max = a;
            printf("\nMax number is ", max);
        }
    
        return 0;
        
    }
  • dev7060
    Recognized Expert Contributor
    • Mar 2017
    • 655

    #2
    I don't understand what's wrong. My program prints only half the output. It doesn't print the maximum number. Here's the code if you wanna check it.
    Add a format specifier for max.
    Code:
    printf("\nMax number is %d", max);

    The statement may also be written just once after all the ifs.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      Suppose all three of your numbers are equal to each other ... all of the if tests will fail, max will be uninitialized, and nothing will print.

      People don’t always do what you expect. What would you like to happen if the user types xyz instead of a number?

      Your code doesn’t scale well. Suppose tomorrow you need to change your program to find the maximum of four numbers instead of three? Every if condition has to change and the logic gets more complicated. Another approach is to tentatively set the maximum value to the first number and then compare the tentative maximum to each number in turn, updating the tentative maximum whenever you find a larger number.

      Comment

      Working...