Home > Back-end >  look for the sum of array
look for the sum of array

Time:12-12

This code is almost done, the only problem is when I try to run it the correct sum is not displayed. What am I doing wrong here? I think it's correct but I feel like something is missing.

For example:

Enter size: 3

Enter element 1: 2

Enter element 2: 4

Enter element 3: 6

Sum: 12

Average: 4.00

#include <stdio.h>
int main() {
    int size, i;
    float n[1000], avg, sum = 0.0;

    printf("Enter size: ");
    scanf("%d",&size);

    for (i = 0 ; i < size ; i  ) {
        printf("Enter element %d: ", i 1);
        scanf("%f",&n[i]);
        sum  =n[i];
    }

    printf("Sum: %d\n",sum);

    avg = sum / size;
    printf("Average: %.2f",avg);

    return 0;
}

CodePudding user response:

You are using %d for the float format specifier. Replace:

printf("Sum: %d\n", sum);

with:

printf("Sum: %f\n", sum);

CodePudding user response:

#include <stdio.h>
int main()
{
int array[10];
int i , size;
int sum=0;
float average=0;

printf("Enter the size of array");
scanf("%d",&size);
for(i=0 ; i<size ; i  )
{
scanf("%d",&array[i]);
}
for(i=0 ; i<size ; i  )
{
sum=sum array[i];
}
printf("Sum of array element is: %d\n",sum);
average=sum/size;
printf("Average of the element of array: %.2f",average);
return 0;
}
  • Related