# Average of user input in a loop problem

• 10-02-2012
Average of user input in a loop problem
Anyone please help me know what I'm I doing wrong, I been trying to figure it out literally for the past 3 hours.

Here's the problem:
Write a C program to read positive integers, until the value -1 is read and print the average of the values.

This is my code, the average is off for some reason:

Code:

```#include <stdio.h> int main (void) {         int num,sum=0;       double avg;         printf("Type a positive number");       scanf("%d",&num);                   for(num;num>=-1;num--)       {       printf("%d\n",num);          sum=sum+num;       }             avg= sum/(num+1);        printf("\n\nThe average is:%d\n",avg);          getch(); }```
• 10-02-2012
oogabooga
Integer arithmetic essentially truncates any fractional result. Try:
Code:

`avg= (double)sum/(num+1);  // make sum a double to ensure division is done with floating-point math`
Now that I look at it, your loop control is completely screwed up too.
• 10-02-2012
I tried it but still the average is not right...
My loop control is screwed up? in where? ;o
• 10-02-2012
laserlight
Your loop condition is wrong. Actually, the choice of a for loop is inappropriate here; use a while loop (or do while loop) instead.
• 10-03-2012
Click_here
"num" is -2 after exiting the 'for' loop - I'm assuming that this is not what you wanted

Code:

```avg= sum/(num+1); = sum/(-2+1); = sum/-1;```
• 10-03-2012
How can I fix the value of num so it's what I typed into scanf?

I just need to know that and the avg will work, anyone please help if you can.
• 10-03-2012
laserlight
You shouldn't "fix" the value of num. Rather, you should be reading into num in the body of the loop, exiting the loop when -1 is read.
• 10-03-2012
I feel so stupid but isn't that's what I was doing? I made that for loop from n to -1 then it exited. Please give me a hint on the code in where should I correct it. :eek:
• 10-03-2012
std10093
You want the user to input something again and again until he hits -1.So he is going to type something again and again....So you did well for using a loop.Inside the loop you should do all the procedure for the user..
Every time,the problem says,you read the input and if it is -1,then you should exit the loop :)
• 10-03-2012
laserlight
Quote:

I feel so stupid but isn't that's what I was doing?

No, you read into num exactly once, even if -1 was not the first input.

Quote:

I made that for loop from n to -1 then it exited.

Write a C program to read positive integers, until the value -1 is read and print the average of the values.
It does not state:
Write a C program to read a positive integer. Loop from that positive integer until -1, decrementing the value on each iteration.

Therefore, you must keep reading in the body of the loop. Failure to do so is definitely a mistake.
• 10-03-2012