
basic array help
im trying to get a good understanding of arrays and have run into a few problems, just a few minor pieces of code im missing probally.
i want to write a program that lets me scanf numbers into the array and exit if they enter a negative number. then find the average of the numbers i did enter.
i tried to use a function for the average portion but i couldnt get it work, and the average system i have set up know does not work at all... perhaps there is a way to leave the
open so i dont have extra 0's and adding to the total sum to divide by at the end process if the program terminates early.
here is my code so far
Code:
#include <stdio.h>
int main() {
int numbers[10];
int i;
int count = 10;
int sum = 0;
double average;
printf("\nEnter the numbers:\n");
for(i = 0; i < count; i ++) // scanf into the array
{
printf("%2d> ",i+1);
scanf("%d", &numbers[i]);
if(numbers[i]<0){
break;}
}
for(i=0; i<10; i++){
sum += numbers[i]; // to keep up with the total after each input
}
average = sum/numbers[i];
printf("the mean is: %lf ", average);
return 0;
}
and the average is wrong i cant make it calculate correctly...

You are dividing by the last number you read in, not by the number of numbers. You want
Code:
average = sum/10.0;

what if the program exits early because i entered a negative number on the 3rd one so im dividing by 10 when i should be only dividing by 2

Well, in that case you need to keep a running total of numbers you've entered. The index of your first loop will do the trick; if you then rename the index of your second loop to something else you can do
Code:
average = ((double) sum)/i;
Do you see how this works? In the first loop you've entered 'i' nonnegative numbers and then a negative one to exit the loop. Just a few things to watch out for:
*you must typecast to double type because otherwise it will do integer division and throw away the remainder (ie. 7/3 = 2, not 2.33333333333333, in integer division)
*You need to separately handle the case that the first number is negative, because there are then no numbers to be added and you'll divide by zero if you're not careful
*You need to handle the case that the user doesn't enter a negative one at all, and the loop terminates normally. If you use my suggestion, it will fail to count the last number entered.

ok thank, i did that but still came up with the wrong answer like 73839292.300, when all i entered was 1,1,1: answer should have been 1... could this be messing it up?
Code:
for(i = 0; i < count; i ++) // scanf into the array
{
printf("%2d> ",i+1);
scanf("%d", &numbers[i]);
if(numbers[i]<0){
break;}
}
for(i=0; i<count; i++){
sum += numbers[i]; // to keep up with the total after each input
}
im using the i in two loops, is it messing it up when i come down to do this
Code:
average = ((double)sum)/i;

You need to use something other than 'i' for the second loop, otherwise you will overwrite your count. Try using a new index variable for the second loop.