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);
  system("PAUSE");	
  return 0;
}

Try initializing these values

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

also

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

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.

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

#include<stdio.h>
#include<stdlib.h>
#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);
        scanf("%d",&arr[i]);
        sum += arr[i];
    }
    average = sum / ARRSIZE;
    printf("\nThe average is %.1f\n\n",average);
    
    system("pause");
    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];

@darkbreaker

i thing you forgot

average = (float)sum / ARRSIZE;

@darkbreaker

i thing you forgot

average = (float)sum / ARRSIZE;

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.