# Finding largest, smallest, average in a loop

This is a discussion on Finding largest, smallest, average in a loop within the C Programming forums, part of the General Programming Boards category; Oh hi. I'm currently trying to level up my C skills and got stuck. I'm trying to write a program ...

1. ## Finding largest, smallest, average in a loop

Oh hi. I'm currently trying to level up my C skills and got stuck.

I'm trying to write a program that will allow a user to enter infinite numbers (one at a time) with a way to stop entering values, and once it stops it immediately displays:

Lowest number:
Highest number:
Number of values entered:
Average of numbers:

I'm pretty new to C and programming in general and what I can't figure out is:

-how to end the loop with something other than a number, preferably a char, so that it doesn't affect the average/lowest/highest

-how to output the lowest and highest numbers in a loop (would be easier to figure out were it finite and I could just type a bunch of printf/scanf)

What I have so far:

Code:
```#include <stdio.h>#include <stdlib.h>

#define pause system("pause")

main(){
//n = amount of numbers input
//x = number given by user
//s = smallest number
//l = largest number

int x = 1, n = -1, s = 999, l = -1;
float sum = -1;

while(x != 0){

printf("Enter a number:  (0 to quit)\n");
scanf("%d", &x);
sum += x;
n = n + 1;

}

printf("Numbers entered: %i \n", n);

if(x < s){
s = x;
printf("Smallest number: %i \n", s);
}

if(x > l){
l = x;
printf("Largest number: %i \n", l);
}

printf("Average: %.2f \n", sum/n);

pause;

}```

2. To calculate the smallest value, presumably you need to compare each value with the <smallest to date> within the body of the loop, rather than trying to do it outside the loop body. Similarly for the largest. First time through the loop, the smallest (and largest) would be computed as the first entered.

In other words, put the if() statements inside the loop body.

And kill that abomination related to pause (both the macro, and using system("pause")). There are plenty of other threads available here describing workable alternatives.

And a tip: never name a variable 'l' (lower case 'L'). It looks too much like the digit '1' on many screens and, if you make an error, problems are really hard to track down and fix.

3. Do you want to count the number 0 when incrementing "n"? I'd think you would rather skip that particular value when determining how many values have been entered.

4. one way you could stop on a char is to check the return value of scanf. it returns the number of fields successfully converted. if you enter a character instead of a number, it will return 0. at that point you could just quit or, the character will still be in the input buffer, as scanf would not consume it if there was no match. so you could scanf("%c") to see if it is a 'q' or whatever.

5. Or just let any character or text string that's not a number mean ”quit”.