Functions in C

Sort by

recency

|

838 Discussions

|

  • + 0 comments

    Less Code:

    int max_of_four(int a, int b, int c, int d) {
        if (b > a)
            a = b;
        if (d > c)
            c = d;
        
        return (a > c) ? a : c;
    }
    
  • + 0 comments
    #include <stdio.h>
    /*
    Add `int max_of_four(int a, int b, int c, int d)` here.
    */
    int max_of_four(int a, int b, int c, int d){
        int max=a;
        int arr[4],n ;
        arr[0]=a;
        arr[1]=b;
        arr[2]=c;
        arr[3]=d;
        while(n>=0 && n<=4){
            if(max<=arr[n]){
                max=arr[n];
            }
            n++;
        }
        return max;
    }
    
    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;
    }
    
  • + 0 comments

    Patch:

    • For example, a function to read four variables and return the sum of them can be written as
    • For example, a function to sum four variables and return the result of them can be written as
  • + 0 comments

    This is a great introduction to understanding functions in C! 11xplay pro

  • + 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));
    }