- How to loop over an array member inside a struct —
s.marks[i] - Why the accumulator should be
doubleorfloat, neverint - How to compute the average robustly by dividing by
sizeof(s.marks) / sizeof(s.marks[0]) - Why
floatdivision differs from integer division when computing the average - How the same pattern scales to a full class of students (an array of structures)
Averaging the Marks
Average marks are just the sum of the marks divided by the number of subjects. If the student scored 85.5, 90.0, and 78.5, the sum is 254.0 and the average is 254.0 / 3 ≈ 84.67. That's it — the arithmetic is trivial. What makes this assignment interesting is where the marks live: inside a struct, in a member called marks that is itself an array. So the loop body isn't sum += marks[i], it's sum += s.marks[i] — you have to go through the struct's dot operator to reach the array, then index into the array.
The other subtlety is the type of the accumulator and the division. If you declare int sum = 0; and the marks are floats, each addition truncates the fractional part — the sum becomes wrong, and the average becomes wrong. If you compute sum / 3 where sum is an integer, you get integer division — 254 / 3 is 84, not 84.67. The accumulator must be a floating-point type (preferably double), and the divisor must be a floating-point value or the division must happen in a floating-point context.
This is the same pattern as the "sum and average of an array" exercise from earlier, but with the array nested inside a struct. Once you're comfortable with s.marks[i], the rest is familiar: a loop, an accumulator, a division, a print. The value of this assignment is that it makes you comfortable navigating a struct to reach an array, which is a pattern you'll use constantly in real C code — process tables, configuration arrays, matrix data, all live inside structs.
💡 In one line: loop over s.marks[i] for i = 0..2, accumulate into a double sum, divide by 3.0, and print with %.2f.
The Sum-Then-Divide Algorithm
In pseudocode, the whole computation is four lines:
sum = 0.0
for i = 0 to 2:
sum = sum + s.marks[i]
avg = sum / 3.0
print avg
Four lines, and the rest of the program is the struct definition, initialization, and a printf. The loop bound is 3, but it's cleaner to write sizeof(s.marks) / sizeof(s.marks[0]) so the code still works if you later change marks from 3 subjects to 5. That's the idiom that separates a working answer from maintainable code.
| Marks | Sum | Average | Notes |
|---|---|---|---|
| 85.5, 90.0, 78.5 | 254.0 | 84.67 | Standard example — no rounding surprises |
| 100.0, 100.0, 100.0 | 300.0 | 100.00 | Maximum — should print cleanly |
| 0.0, 0.0, 0.0 | 0.0 | 0.00 | Zero — tests the average of nothing scored |
| 60.5, 72.0, 88.5 | 221.0 | 73.67 | Repeating decimal — %.2f rounds correctly |
| 50.0, 60.0, 70.0 | 180.0 | 60.00 | Round number — verifies no stray fraction |
The last column is worth noting: 73.67 is a repeating decimal (221.0 / 3 = 73.6666…), so the printed value depends on rounding. %.2f rounds half-up, so 73.6666… prints as 73.67. If you want more precision, use %.6f; if you want fewer, use %.1f. This is a good place to notice that floating-point arithmetic is rarely exact — the average of 221/3 isn't representable in binary floating-point, so the printed value is an approximation. That's fine for grades; for money, you'd use fixed-point or a decimal library.
Complete C Program
Program: average marks of a student using a structure
#include <stdio.h>
struct student {
char name[50];
int roll;
float marks[3];
};
int main(void) {
struct student s = {
"Alice Johnson",
101,
{85.5, 90.0, 78.5}
};
int count = sizeof(s.marks) / sizeof(s.marks[0]);
double sum = 0.0;
for (int i = 0; i < count; i++) {
sum += s.marks[i];
}
double average = sum / count;
printf("Student Record\n");
printf("--------------\n");
printf("Name : %s\n", s.name);
printf("Roll : %d\n", s.roll);
printf("Marks : %.1f, %.1f, %.1f\n",
s.marks[0], s.marks[1], s.marks[2]);
printf("Total : %.2f\n", sum);
printf("Average : %.2f\n", average);
return 0;
}
And here's a variant that reads the marks from the user and computes the average — the more realistic program shape:
Variant: read marks from the user
#include <stdio.h>
#include <string.h>
struct student {
char name[50];
int roll;
float marks[3];
};
int main(void) {
struct student s;
printf("Enter name: ");
scanf(" %49[^\n]", s.name);
printf("Enter roll number: ");
scanf("%d", &s.roll);
printf("Enter marks in three subjects: ");
scanf("%f %f %f", &s.marks[0], &s.marks[1], &s.marks[2]);
int count = sizeof(s.marks) / sizeof(s.marks[0]);
double sum = 0.0;
for (int i = 0; i < count; i++)
sum += s.marks[i];
double average = sum / count;
printf("\nStudent Record\n");
printf("--------------\n");
printf("Name : %s\n", s.name);
printf("Roll : %d\n", s.roll);
printf("Marks : %.1f, %.1f, %.1f\n",
s.marks[0], s.marks[1], s.marks[2]);
printf("Total : %.2f\n", sum);
printf("Average : %.2f\n", average);
return 0;
}
The first version is the assignment answer — it demonstrates the struct, the marks array, the sum, and the average. The second version is what you'd actually write in a real program: it reads the record from the user, then does the same computation. The computation section is identical between the two, which is the point — the average logic is independent of where the marks came from.
Program Output
Student Record
--------------
Name : Alice Johnson
Roll : 101
Marks : 85.5, 90.0, 78.5
Total : 254.00
Average : 84.67
And for the read-from-user variant:
Enter name: Alice Johnson
Enter roll number: 101
Enter marks in three subjects: 85.5 90.0 78.5
Student Record
--------------
Name : Alice Johnson
Roll : 101
Marks : 85.5, 90.0, 78.5
Total : 254.00
Average : 84.67
Try changing the marks and see how the average changes. For example, 100 100 100 should print an average of 100.00; 50 60 70 should print 60.00. Try marks that produce a repeating decimal, like 60.5 72 88.5 — the average is 73.6666…, and %.2f rounds it to 73.67.
Step-by-Step Explanation
Let's walk through the sum-and-average computation for Alice's marks.
1. The struct definition and initialization
Same struct student as before — name, roll, and marks[3]. The positional initializer {"Alice Johnson", 101, {85.5, 90.0, 78.5}} creates a fully populated student. The inner braces around the marks correspond to the array member.
2. The count idiom
sizeof(s.marks) / sizeof(s.marks[0]) computes 3 — the number of elements in the array. This is a well-known C idiom and it's better than hardcoding 3 because it stays correct if you later change the array size. The sizeof(s.marks) is 3 * sizeof(float) = 12 bytes; sizeof(s.marks[0]) is sizeof(float) = 4 bytes; the quotient is 3. The division is integer division but it's exact (no truncation) because both operands are multiples of each other.
3. The accumulator
double sum = 0.0; starts at 0.0, not 0. If you write int sum = 0;, each sum += s.marks[i] truncates the fractional part of the mark. 85.5 becomes 85, 90.0 stays 90, 78.5 becomes 78 — sum = 253 instead of 254. The average would then be wrong. Using double (or at minimum float) preserves the fractional parts. double is preferred because it has 53 bits of precision, enough for grades up to the billions.
4. The loop
For i = 0, 1, 2, add s.marks[i] to sum. After three iterations, sum = 85.5 + 90.0 + 78.5 = 254.0. Notice the loop accesses s.marks[i], not marks[i] — the marks array is a member of s, so you have to go through s to reach it. This is the two-step access: struct member then array index.
5. The average
average = sum / count; — with sum as double and count as int, the int is promoted to double before the division, so the division is floating-point. 254.0 / 3 = 84.6666…. If sum were an int, the division would be integer division: 254 / 3 = 84, losing the fractional part. The type of sum determines the type of the result, not the type of count.
6. Printing with precision
%.2f prints two digits after the decimal point, rounding half-up. 84.6666… becomes 84.67. If you want more precision, use %.4f (four decimal places); if you want fewer, use %.1f (one). The choice is a matter of presentation, not computation — the average is always approximately 84.6666…, and the printf format just controls how many digits are shown.
7. Why this pattern scales
The same code works for any number of students if you change struct student s to struct student class[30] and wrap the whole computation in an outer loop over class[i]. Each iteration does the same sum-then-divide, and you print one average per student. The pattern is the foundation of gradebook software, transcript generators, and any program that has to aggregate per-entity statistics — the entity is a struct, the statistics are a loop over a member array, and the pattern is universal.
🎯 Remember this: sum the marks array with s.marks[i]; use double for the accumulator; divide by sizeof(s.marks) / sizeof(s.marks[0]); print with %.2f. The pattern scales to a full class of students with an outer loop.
Frequently Asked Questions
1. Why do I get 84 instead of 84.67?
Because you're using integer division. If sum is int, sum / 3 is integer division — 254 / 3 = 84, with the fractional part discarded. Change sum to double (or float) and the division becomes floating-point: 254.0 / 3 = 84.6666…, which prints as 84.67 with %.2f.
2. Can I add the marks directly without a loop?
Yes: double sum = s.marks[0] + s.marks[1] + s.marks[2]; works and is arguably clearer for a fixed-size 3-array. The loop is more general — it scales to any array size, and it's what you'd write if the number of subjects were a variable. For this assignment, either style is fine. The loop version is slightly more idiomatic and demonstrates the pattern that generalizes to full-class aggregation.
3. What does sizeof(s.marks) / sizeof(s.marks[0]) do?
It computes the number of elements in the array. sizeof(s.marks) is the total size of the array (3 × 4 = 12 bytes for float[3]), and sizeof(s.marks[0]) is the size of one element (4 bytes). The quotient is 3. This idiom is preferred over hardcoding 3 because it survives if you change the array size — you only have to change the declaration, not every loop bound.
4. Why does the average print as 84.67 and not 84.66?
Because %.2f rounds, not truncates. 84.6666… rounds to 84.67 (the third decimal is 6, which is ≥ 5, so the second decimal is rounded up from 6 to 7). If you want truncation, use %.2f but with the value multiplied by 100, floored, divided by 100 — or just accept that %.2f rounds. Rounding is what you want for grades; truncation would systematically under-report averages.
5. What if the marks are integers instead of floats?
If marks are int, then sum can be int too, but the average still needs to be floating-point — otherwise 254/3 = 84, not 84.67. Use double average = (double) sum / count; — cast sum to double before dividing. Or declare sum as double from the start; the assignment sum += s.marks[i] promotes each int to double implicitly. The latter is simpler.
6. How would I compute the average for a whole class of students?
Change struct student s to struct student class[30], fill each element, then wrap the sum-and-average code in an outer loop: for (int j = 0; j < 30; j++) { /* sum class[j].marks, compute average, print */ }. Each student gets their own average, and you could also compute a class-wide average by summing all marks and dividing by 30 * 3. This is the subject of assignment 25 (sorting an array of students), which builds on the same pattern.
💡 Tip: After this program, try adding a "grade" computation — A for ≥ 90, B for ≥ 80, C for ≥ 70, and so on. That's a simple if-else ladder applied to the average. Then try computing a weighted average where the three subjects have different weights (e.g., 3, 2, 1). Both are small extensions of the same pattern, and both appear in real gradebook software.