Functions in C

  • + 0 comments

    Since this problem is still at the basic stage (no loops, macros, or conditionals introduced yet), I thought I'd share a solution that sticks to the fundamentals: just functions and some simple math.

    I’ve seen many solutions here that use macros or ternary operators, which are definitely efficient, but I wanted to explore if we can solve it differently.

    #include <stdio.h>
    #include <stdlib.h>
    
    int max(int x, int y);
    int max_of_four(int a, int b, int c, int d);
    
    int main() {
        int a, b, c, d;
        scanf("%d %d %d %d", &a, &b, &c, &d);
        int ans = max_of_four(a, b, c, d);
        printf("%d", ans);
        
        return 0;
    }
    
    int max(int x, int y) {
        return (x + y + abs(x - y)) / 2;
    }
    
    int max_of_four(int a, int b, int c, int d) {
        return max(max(a, b), max(c, d));
    }