Min function gives output 6422164 irrespective of the input

Viewed 35

I want to implement a function that returns the minimum of four elements. I have written the following code:

#include <stdio.h>

int max_of_four(int a, int b, int c, int d) {
  int max;

  if (a > b) {
    if (a > c) {
      if (a > d) {
        max = a;
      }
    }
  } else if (b > a) {
    if (b > c) {
      if (b > d) {
        max = b;
      }
    }
  } else if (c > a) {

    if (c > b) {
      if (c > d) {
        max = c;
      }
    }
  } else {
    max = d;
  }
  return max;
}

int main() {
  // initializing int a, b, c, d, max;
  scanf("%d %d %d %d", &a, &b, &c, &d);
  int ans = max_of_four(a, b, c, d);
  printf("%d", ans);

  return 0;
}

This code is giving me output 6422164 irrespective of the input. What is wrong with my code?

1 Answers

You haven't covered the cases properly, E.g. what if a=1 and b=2 and c=3. The condition in the second if (b>a) will be true and the block entered. Then the condition b>c will be false and no other block will be entered. Finally the uninitialised variable max is returned, returning an undefined value which you see as 6422164.

A better way to write it is to initialise max to the first value and then compare each value in turn to max, updating it if the current number is greater than max.

int max_of_four(int a,int b,int c,int d) {
    int max = a;

    if (b > max) max = b;
    if (c > max) max = c;
    if (d > max) max = d;

    return max;
}
Related