Search code examples
cwhile-loopdoublemaxminimum

How to find max&min in while loop - c


I know that this is very easy question for you, but for me as beginner very hard. To get to thing. I have to create program that will take as many numbers as I want and then write max and min from them. Numbers can have decimals so that´s why double. Everything goes great as far as I trouble-shot until while cycle begins. I always get 0 on output on both min and max values. Anyone knows why? Code:

 main() {
  int a = 0, b = 0, min = 1000, max = 0;
  printf("How many numbers do you want to enter\n");
  scanf("%d", & a);
  b = a;
  double n[b];
  printf("Write those numbers\n");
  for (b = 0; a > b; b++) {
    scanf("%lf", & n[b]);
  }
  b = 0;
  while (1) {
    if (n[b] < n[b + 1])
      max = n[b + 1];
    if (min > n[b])
      n[b] = min;
    b++;
    if (b == a)
      break;
  }
  printf("Minimum: %lf\nMaximum: %lf", min, max);
}

Solution

  • Printing an int using a conversion specifier for double is not a good idea, but invokes the infamous Undefined Behaviour.

    The compiler might have noticed you about this. If it didn't, then increase its warning level. For GCC use -Wall -Wextra -pedantic.

    So to fix this either make min and max be double

      int a = 0, b = 0;
      double min = 1000., max = 0.; /* Such initialisations limit your input. */
    

    or leave them be int (decreasing accuracy), and print them as what there are, namely int

      printf("Minimum: %d\nMaximum: %d\n", min, max);