Home > Software engineering >  Max of 4 numbers using another function (max of 2)
Max of 4 numbers using another function (max of 2)

Time:11-30

i'm new to C and learning, this is more about how i can use a function inside another function, i'm trying to get the max of 4 numbers using another function that determines the max of 2. the errors i get are "expected expression before int" and "to few arguments to function max2", i tried to search what they mean however i didn't really understand much... thank you for any help

int max2(int a, int b) {
        if(a > b) {
            printf("%d is the max\n", a);
        }
        else {
            printf("%d is the max\n", b);
        }
}



int max4(int a, int b, int c, int d) {
        
        if(a > b)
        {
            if(a > c)
            {
                max2(int a, int d);
            }
            else
            {
                max2(int c, int d);
            }
        }
        else
        {
            if(b > c)
            {
                max2(int b, int d);
            }
            else
            {
                max2(int c, int d);
            }
        }
} 

int main() {
    max4(666,853,987,42);
}
 

CodePudding user response:

You declare functions returning int, but those functions return nothing. Probably you'd want something like this:

#include <stdio.h>

int max2 (int a, int b) { return a > b ? a : b; }
int max4 (int a, int b, int c, int d) { return max2(max2(a, b), max2(c, d)); }

int main (void) {
        printf("%d is the max\n", max4(666,853,987,42));
}

CodePudding user response:

Welcome to programming!

You should take a closer look here to see why you are incorrectly calling (important keyword) your function.
Additionally you should look into the return keyword. (A quick look at this answer or the more in depth Microsoft article should help)

Also, as mentioned in the comments, your solution is a bit weird.
Try finding the max of 20 numbers, by using for or while loops, as well as an array.

Happy learning!

  •  Tags:  
  • c
  • Related