C Program Using Pointer to Structure
Problem
Write a C program to accept the marks of 10 students in 5 subjects and find
their total and average using a pointer to structure.
Explanation
• We create a structure Student that stores 5 subject marks, total, and
average.
• We create an array of 10 such structures.
• A pointer to structure is used to access and store the data.
• For each student:
– Input 5 marks.
– Calculate total as the sum of all marks.
– Calculate average as total / 5.
• Results are displayed for all 10 students.
C Program
1 // Easy C program using pointer to structure
2
3 # include < stdio .h >
4
5 # define STUDENTS 10
6 # define SUBJECTS 5
7
8 // Structure to store student details
9 struct Student {
10 int marks [ SUBJECTS ];
11 int total ;
12 float average ;
13 };
1
14
15 int main () {
16 struct Student s [ STUDENTS ];
17 struct Student * ptr = s ;
18 int i , j;
19
20 // Input marks for each student
21 for ( i = 0; i < STUDENTS ; i ++) {
22 printf ( " \ nEnter marks for Student % d :\ n " , i + 1);
23
24 // Read 5 subject marks
25 for ( j = 0; j < SUBJECTS ; j ++) {
26 printf ( " Subject % d : " , j + 1);
27 scanf ( " % d " , &( ptr + i ) - > marks [ j ]);
28 }
29
30 // Calculate total
31 ( ptr + i ) - > total = 0;
32 for ( j = 0; j < SUBJECTS ; j ++) {
33 ( ptr + i ) - > total += ( ptr + i ) - > marks [ j ];
34 }
35
36 // Calculate average
37 ( ptr + i ) - > average = ( ptr + i ) - > total / ( float ) SUBJECTS ;
38 }
39
40 // Display the results
41 printf ( " \n - - - - - - - RESULTS - - - - - - -\ n " );
42 for ( i = 0; i < STUDENTS ; i ++) {
43 printf ( " \ nStudent % d :\ n " , i + 1);
44 printf ( " Total Marks = % d \ n " , ( ptr + i ) - > total );
45 printf ( " Average = %.2 f \ n " , ( ptr + i ) - > average );
46 }
47
48 return 0;
49 }
Output Format
Enter marks for Student 1:
Subject 1: 78
Subject 2: 82
...
Total Marks = 400
Average = 80.00