I compiled this:
Code:
#include <stdio.h>
int main() {
int marks[4][4]; /* declare an array to store 4 values */
int j; /* array index */
int sum = 0;
float average;
printf("Enter the marks of 4 students :- \n");
// read marks of 5 students
for ( j = 0; j < 4 ; j++ ) {
printf("Marks of student %d : ", j+1);
scanf("%d", &marks[j]); /* input marks of student 'j' in index 'j' */
}
/* Compute sum and average */
for ( j = 0; j < 4 ; j++ ) {
sum += marks[j]; /* add the value in each index of the array */
}
average = (float)sum / 4;
printf("Sum : %d\n", sum);
printf("Average : %f\n", average);
return 0;
}
and the compiler gave me these warnings:
Code:
test.c: In function ‘main’:
test.c:14:15: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int (*)[4]’ [-Wformat=]
scanf("%d", &marks[j]); /* input marks of student 'j' in index 'j' */
^
test.c:19:13: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
sum += marks[j]; /* add the value in each index of the array */
^
I did not get "error redeclaration int sum", and in fact eyeballing the code shows that the int variable named sum is only declared once, so the error message you cited does not make sense.
To fix the warnings from my compiler:
- You need to fix the logic error where your comment says "read marks of 5 students", but your code actually just reads 4 values. You probably want a nested loop: the outer loop would loop over each of the 5 students, and the inner loop would the student's marks one by one. Oh, and you either need to fix your comment, or fix the code so that there is space to store the marks for 5 rather than 4 students.
- Likewise, you need a nested loop to add the student marks. But perhaps you are supposed to compute the sum and average for each student? Check your requirements.