# Calculating an average

• 03-01-2006
Andy123
Calculating an average
Hey,

I am new to C and need to make a console app that allows a user to enter as many payments as they like and when a command say "STOP" is entered it calculates the average of the numbers they entered. Could some tell me the best way to achieve this....Would it be with an array, loop or something else.

P.S I have a couple of manuals but am not sure what I should be looking for.

Thanks :)

Andy
• 03-01-2006
cwr
If you only need the average, you could keep a running total and a count of the number of items and divide the running total by the number of items when they've finished inputting the numbers.
• 03-01-2006
duochon
U can use FOR command !
Ex:
Code:

```For(i=0;i<n;,i++) {   printf("type %d number:",i);   scanf("%d",&i); }   sum=0   for(i=0;i<n;i++)   sum = sum + i;   printf("Avarage is %d",sum/n);```
That is simple code !
• 03-01-2006
SlyMaelstrom
Quote:

Originally Posted by duochon
U can use FOR command !
Ex:
Code:

```For(i=0;i<n;,i++) {   printf("type %d number:",i);   scanf("%d",&i); }   sum=0   for(i=0;i<n;i++)   sum = sum + i;   printf("Avarage is %d",sum/n);```
That is simple code !

First off, it's for, not For. Secondly, why would you read into your control variable in a count control loop?
• 03-01-2006
cwr
To the OP, please completely ignore duochon's post, in case you're tempted not to. If they actually tested the code they gave, they'd not have posted it.
• 03-01-2006
CrazedBrit
Yeah, ditto what cwr and sly said. Don't bother reading his post. But do try using a for loop, then show us what you come up with and we'll be happy to help you work through the problem.
-Crazed
• 03-01-2006
SlyMaelstrom
It's tough to flat out say, "Use a for loop", especially with the way he want to sum. If you're talking about an undefined amount of user input, then a while or do while loop would suit you better.
• 03-01-2006
CrazedBrit
Oop my bad. You're right Sly it would be best to use a while loop for that, but, it would still be possible to do it using an infinite loop with a break statement.
-Crazed
• 03-02-2006
swgh
Try this:

Code:

```#include <stdio.h> int main() { int average; int counter = 1; int total = 0; int num; while ( counter <= 25 ) { printf("Enter an amount: "); scanf("%d", &num); total = total + num; counter++; } average = total / 10; printf("\nThe average is %d, average); getchar(); return 0; }```
• 03-02-2006
swgh
EDIT

Sorry, last line of code should read:

Code:

`printf("\nThe average is %d", average);`
• 03-02-2006
Ideswa