Structure Assignment 3 — Find the Average Marks of a Student
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the Average Marks of a Student Using a Structure

📑 On this page:
  • Averaging the Marks
  • The Sum-Then-Divide Algorithm
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to loop over an array member inside a struct — s.marks[i]
  • Why the accumulator should be double or float, never int
  • How to compute the average robustly by dividing by sizeof(s.marks) / sizeof(s.marks[0])
  • Why float division 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.

Diagram showing a struct student with marks 85.5, 90.0, 78.5 being summed in a loop to 254.0 and divided by 3 to give 84.67

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.5254.084.67Standard example — no rounding surprises
100.0, 100.0, 100.0300.0100.00Maximum — should print cleanly
0.0, 0.0, 0.00.00.00Zero — tests the average of nothing scored
60.5, 72.0, 88.5221.073.67Repeating decimal — %.2f rounds correctly
50.0, 60.0, 70.0180.060.00Round 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.

📖 Related Tutorials

  • 1. Create a Structure to Represent a Student
  • 2. Initialize and Display the Details of a Student Using a Structure
  • 4. Create a Structure to Represent a Book
  • Accessing Structure Members
  • Array of Structures
  • Arrays Within Structure
  • Structure Initialization
  • All 25 Structure Assignments

Previous Topic: -->> 2. Initialize and Display the Details of a Student Using a Structure   ||   Next Topic: -->> 4. Create a Structure to Represent a Book


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.