• Welcome to Valhalla Legends Archive.
 

for computer science class

Started by treyreese, January 30, 2004, 01:46 PM

Previous topic - Next topic

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.


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);

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.
Quote"Pray not for lighter burdens, but for stronger backs." -- Teddy Roosevelt
"Your forefathers have given you freedom, so good luck, see you around, hope you make it" -- Unknown

treyreese

could you give me an example, im not to go with while loops...

Tuberload


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);

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:


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);
}  


Or I guess you could just move the scanf() inside your if (a != 0) block.
Quote"Pray not for lighter burdens, but for stronger backs." -- Teddy Roosevelt
"Your forefathers have given you freedom, so good luck, see you around, hope you make it" -- Unknown

treyreese

im still getting 0 for my minium

treyreese

ok i got it  to work with this.... btw, min is declared to be 1000000


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);