C Program: Trying to terminate a loop...

Ello.

I am doing this question for my Computer Science class.

"A set of data consists of an unknown number of positive integers. Each integer is less than 1000 and the data is terminated by 0.
Write a structured algorithm which reads the data and outputs the smallest integer, the largest integer and the average of all the integers (except the terminating 0). You may assume that the data is valid."

And this is my code:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

int num,small,large,avg,count,total;

int main()
{

do{
printf("Please enter positive integers.");
scanf("%d",&num);

if (num<small)
{
small=num;
}

if (num>large)
{
large=num;
}
count=count+1;
total=total+num;
}while(num!=0);
avg=(total/count);
printf("\nThe smallest integer is %d",small);
printf("\nThe largest integer is %d",large);
printf("\nThe average is %d",avg);
getch();
return 0;
}

The problem is that when I input the terminator (0), the smallest integer is displayed as 0, which shouldn't happen.

Can you help? Thanks!
 
Using the do/while loop, it's going to perform the code BEFORE checking if the number is 0. So, either place an if statement at the top to check for 0, or re-write it as a regular while loop.
 
Use the final terminator to show a negative,

On you while statement change that to <0, (less than) then when the loop reaches -1, it will terminate.
 
Back
Top