bartukilickaya
bartukilickaya

Reputation: 57

Reading numbers from the user until negative number is given, returning highest,lowest,range and number count?

#include <stdio.h>
#include <math.h>

int main(void) {
  int a,count,highest,lowest,range;
  for(count=0;scanf("%d",&a) >= 0;count++){
    if(count == 0){
      highest = a;
      lowest = a;
    }
    if(a > highest){
      highest = a;

    }
    if(a < lowest){
      lowest = a ;
    }

  }
  range = highest - lowest;
  printf("%d\n %d\n %d\n %d\n",count,highest,lowest,range);
  return 0;
}

the problem is this program does not stop until I press CTRL D however I want it to stop when I enter negative number as you can see in scanf("%d",&a) >= 0; How can I solve this?

Upvotes: 0

Views: 552

Answers (3)

hanie
hanie

Reputation: 1885

this scanf("%d",&a) >= 0 doesn't check a>=0 this check scanf returned, which is about success of taking data and number of inputs taken.

int main(void) {
  int a,count,highest,lowest,range;
 scanf("%d",&a);
 for(count=0;a>= 0;count++){
    if(count == 0){
      highest = a;
      lowest = a;
    }
    if(a > highest){
      highest = a;

    }
    if(a < lowest){
      lowest = a ;
    }
   scanf("%d",&a);
  }
  range = highest - lowest;
  printf("%d\n %d\n %d\n %d\n",count,highest,lowest,range);
  return 0;
}

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 311078

Write the condition in the for loop the following way

for ( count = 0; scanf("%d",&a) == 1 && a >= 0; count++ ){
//...

Also it is better to combine all if statement in a group of if-else statements like

if ( count == 0 ){
  highest = a;
  lowest = a;
}
else if( a > highest ){
  highest = a;
}
else if(a < lowest){
  lowest = a ;
}

Upvotes: 3

Deepu
Deepu

Reputation: 7610

scanf() function in C returns total number of Inputs Scanned successfully or EOF if input failure occurs before the first receiving argument was assigned. So in your case scanf("%d",&a) returns the value 1 even when you enter a negative number. Hence the for loop in your code will not terminate until you press CTRL D.

Upvotes: 2

Related Questions