Valhalla Legends Forums Archive | C/C++ Programming | for computer science class

AuthorMessageTime
treyreese
I have to write a program where you enter as many ints as you want and 0 to stop the input. At the end of the program it outputs the numbers in the series, the average, largest number, smallest number, difference between the largest and smallest number. All works except displaying the smallest number, it always displays 0, she wants it to display the next smallest. The difference doesnt work b/c of the smallest number problem.

[code]
do
{
printf("Enter integer, zero to stop: ");
scanf("%d", &a);
if (a != 0) {
number++;
sum += a;
avg = a / number;
if (a > max) max=a;
if (a < min) min=a;
}
}
while (a !=0);[/code]
January 30, 2004, 7:46 PM
Tuberload
Use just a while loop instead of a do/while. This way the loop will exit when 0 is entered before doing anything with the data.

Use while loops when you aren’t sure how many times the loop will have to repeat itself, and do/while loops when you have to perform at least one iteration.

Now in your situation you do not need to perform at least one operation because if 0 is entered nothing needs to happen.
January 30, 2004, 7:57 PM
treyreese
could you give me an example, im not to go with while loops...
January 30, 2004, 8:08 PM
Tuberload
[code]
do
{
printf("Enter integer, zero to stop: ");
scanf("%d", &a);
if (a != 0) {
number++;
sum += a;
avg = a / number;
if (a > max) max=a;
if (a < min) min=a;
}
}
while (a !=0);
[/code]
Nothing in the above code stops 0 from being assigned to a. That is why you are getting zero from your minimum. If you were to change it to the following you would prevent this from happening:

[code]
printf("Enter integer, zero to stop: ");
scanf("%d", &a);
While (a != 0)
{
number++;
sum += a;
avg = a / number;
if (a > max) max=a;
if (a < min) min=a;
printf("Enter integer, zero to stop: ");
scanf("%d", &a);
}
[/code]

Or I guess you could just move the scanf() inside your if (a != 0) block.
January 30, 2004, 8:22 PM
treyreese
im still getting 0 for my minium
January 30, 2004, 8:28 PM
treyreese
ok i got it to work with this.... btw, min is declared to be 1000000

[code]
do
{
printf("Enter integer, zero to stop: ");
scanf("%d", &a);
if (a <= 0)
break;
number++;
sum += a;
avg = sum / number;
if (a > max) max=a;
if (a < min) min=a;

}

while (1);[/code]
January 30, 2004, 9:13 PM

Search