Alright im trying to create a program that allows the user to input numbers into an array and then will take the average of all the numbers within the array but im getting very strange results

any help is much appreciated

#include <stdio.h>
#include <stdlib.h>
#define SIZE 9 
int main(void)
  int sum ;
  int average;
  int num;
  int a[SIZE];
  int i;
  printf(" Input Numbers (enter -1 to end):\n");
           scanf( "%d", a[SIZE]);
           while( num != -1) {
  for ( i = 0; i > 0; ++i)
      sum  += a[i];
  average = sum/i;
  printf(" Input Numbers (enter -1 to end):\n");
printf("average = %d\n", average);
  return 0;
7 Years
Discussion Span
Last Post by darkbreaker

Try initializing these values

int sum = 0;
int average = 0;
int num = 0;
int i = 0;


scanf( "%d", &a[SIZE]);

Edited by gerard4143: n/a


the problem is right now it will always crash directly after i input the first number, but i think forgetting hte & before a was also a problem, thanks


What happens here when i == 0

average = sum/i

also this

printf(" Input Numbers (enter -1 to end):\n");
           scanf( "%d", &a[SIZE]);

doesn't do what you think it does...Currently this code inputs a value past the end of the array a.

Edited by gerard4143: n/a


I know i shouldn't do this... but this is the code you want:

#define ARRSIZE 9

int main(void)
    int arr[ARRSIZE],i,sum=0;
    float average;
    for(i = 0; i < ARRSIZE; i++){
        printf("(%d/%d) Input a number: ",i+1,ARRSIZE);
        sum += arr[i];
    average = sum / ARRSIZE;
    printf("\nThe average is %.1f\n\n",average);
    return 0;

Please take some time to undestand each part of the program. If you can't undestand something post it here.

Note that sum is initialized with the value 0, otherwise it would contain random numbers wich would be added with the input values at this part:

sum += arr[i];

Edited by darkbreaker: n/a



i thing you forgot

average = (float)sum / ARRSIZE;

Oh yeah, it needs the casting otherwise it returns int. :)
Thank you.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.