2

I have to find the maximum and the minimum using a sentinel controlled repetition.

"maximum” is not working properly. Can anyone help me with some clue about what’s wrong in my code?

#include<stdio.h>

int main() { 
  int number;
  int min;
  int max;

  do {
    printf("Enter a number (-1 to quit): ");
    scanf("%d",&number);
    if( number >= 0 ) {
      if(number < min )
        min = number;
      if( number > max )
        max = number;

    }
    else if( number < 1 )
      printf("the number is not valid \n");
  } 

  while( number != -1 );

  printf("Minimum=%d\n",min);
  printf("Maximum=%d\n",max);

  system("pause");

  return 0;
}
pmr
  • 58,701
  • 10
  • 113
  • 156
Nomics
  • 706
  • 5
  • 14
  • 2
    You should initialize local variables. – Mat Nov 06 '12 at 19:27
  • Enter a number (-1 to quit): 44 Enter a number (-1 to quit): 32 Enter a number (-1 to quit): 2 Enter a number (-1 to quit): -1 the number is not valid Minimum=2 Maximum=2674276 (Maximum is not working). :/ – Nomics Nov 06 '12 at 19:28
  • @Marc it's working. I set max = 0. Why dont I need to initialize "min"? – Nomics Nov 06 '12 at 19:31
  • one sec, im writing my answer how to set min and max – Marc Nov 06 '12 at 19:33
  • @Nomics my answer is updated – Marc Nov 06 '12 at 19:39
  • In plus, I think your professor would like to see a 3*N/2 complexity, not 2*N complexity as you did. For this, you group the elements in pairs of 2, and write 3 comparaisons in each branch. – alinsoar Nov 06 '12 at 20:05

1 Answers1

2

The value of your variables not initialized were 2674276, all numbers were smaller so your min was fine

but no number was bigger than this so it was your max.

You need to initialize your min and your max with the first number

I would do something like

max = -1
min = -1

do {
    printf("Enter a number (-1 to quit): ");
    scanf("%d",&number);
    if( number >= 0 ) {
      if(max == -1)
      {
         max = number //Means it's the first time so your max and min are the first number
         min = number
      }
      else
      {
         if(number < min )
            min = number;
         if( number > max )
          max = number;

      }
    }
    else if( number < 1 )
      printf("the number is not valid \n");
  } 

  while( number != -1 );
Marc
  • 16,170
  • 20
  • 76
  • 119