Not printing input list c

I'm not sure why it only prints the last student's information and I need the display to be separate from the user input. So it can print a list of all the user has put in the input.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
  #include <stdio.h>

struct student
{
	int id, semester, finalgrade;
	char name[20];
}info;

int main()
{
	int sum=0, average=0, i, n;
	
	printf("Enter amount of students: \n");
	scanf("%d", &n);
	
	printf("\nEnter information of students: \n");
	for(i=0; i<n ;i++)
	{
		printf("Enter id: \n");
        scanf("%d", &info.id);
		printf("Enter name: \n");
        scanf("%s", &info.name);
        printf("Enter semester: \n");
        scanf("%d", &info.semester);
        printf("Enter final grade: \n");
        scanf("%d", &info.finalgrade);
        printf("\n");
        
        sum = sum + info.finalgrade;
	}
	average = sum/n;
	printf("\nThe average of the final grades of all the students: %d", average);
	
	for(i=0; i<n ;i++)
	{
		printf("\n%d\n", info.id);
		printf("%s\n", info.name);
        printf("%d\n", info.semester);
        printf("%d\n", info.finalgrade);
        printf("\n");
	}
}
Hi,

Each time the for loop on line 17 executes, you overwrite your data each time, so the last data is the only info left in the variables. You need to store the data in a data structure, such as an array. An array's size must be fixed at compile time.

Also, when you use scanf, make use of it's return value to see if it worked.

Line 29 can use the += operator, rather than sum = sum +

There is a compiler warning on line 22.

Good Luck !!
Last edited on
Topic archived. No new replies allowed.