### sum and mean of the number in loop

Hi there, so I made this program that ask users to enter a series of number and then the program will show the total number that the user entered, the sum and mean of the number. Below is my coding:

 ``123456789101112131415161718192021222324252627`` ``````#include #include #pragma warning (disable:4996) #define SENTINEL -999 void main() { int n=0, i=0, sum = 0; float mean = 0; do { printf("Give me any integer (-999 to stop): "); scanf("%d", &n); if (n != SENTINEL) i += 1; sum = sum + n; mean = sum / i; } while (n != SENTINEL); printf("total number you has keyed in : %d\n", i); printf("sum of the numbers: %d\n", sum); printf("Mean of the numbers: %.3f\n", mean); system("pause"); } ``````

For the input, I put 2 and 4, so total number that I had keyed in is 2 and the sum is 6,while the mean is 3.000. However, the program gave me the wrong sum and mean.
I think there's problem with the sum and mean coding, any help will be appreciated and thank you for helping.
If you encounter the sentinel then you need to exit the loop immediately, not continue to the end of the loop.

Change
`if (n != SENTINEL)`
to
`if (n == SENTINEL) break;`

That will make it "work" (well, do what you intend anyway), but there's a lot still wrong with the code.

Also, you only need to compute the mean ONCE, not on every loop.
You need L15-16 within the body of the if statement. As it stands if n is the sentinel then sum also includes the sentinel. mean should be calculated once the loop has terminated.

Consider:

 ``1234567891011121314151617181920212223242526`` ``````#include #include #pragma warning (disable:4996) #define SENTINEL -999 void main() { int n = 0, i = 0; float sum = 0; do { printf("Give me any integer (-999 to stop): "); scanf("%d", &n); if (n != SENTINEL) { ++i; sum += n; } } while (n != SENTINEL); printf("total number you has keyed in : %d\n", i); printf("sum of the numbers: %.0f\n", sum); printf("Mean of the numbers: %.3f\n", sum / i); //system("pause"); }``````

Last edited on
Topic archived. No new replies allowed.