Introduction
In C programming, nested loops are extremely useful for managing multi-dimensional data like student marks in multiple subjects. In this tutorial, we’ll write a C program to calculate the total and average marks of 5 students across 3 subjects using nested for
loops.
This program is ideal for learning how to process structured data like a table or matrix using arrays and loops.
Problem Statement
Create a program that accepts marks for 5 students, each with 3 subjects. The program should calculate the total and average for each student using nested for
loops.
C Program to Calculate Average and Total
#include <stdio.h>
int main() {
int marks[5][3];
int total;
float average;
// Input marks for 5 students and 3 subjects
for (int i = 0; i < 5; i++) {
printf("Enter marks for Student %d:\n", i + 1);
for (int j = 0; j < 3; j++) {
printf("Subject %d: ", j + 1);
scanf("%d", &marks[i][j]);
}
}
// Calculate total and average
for (int i = 0; i < 5; i++) {
total = 0;
for (int j = 0; j < 3; j++) {
total += marks[i][j];
}
average = total / 3.0;
printf("Student %d - Total: %d, Average: %.2f\n", i + 1, total, average);
}
return 0;
}
Explanation
- 2D Array: Used to store marks of 5 students and 3 subjects.
- Nested for loops: Outer loop handles students, inner loop handles subjects.
- Calculation: Total is the sum of 3 subject marks; average is total divided by 3.
Sample Output
Enter marks for Student 1:
Subject 1: 75
Subject 2: 80
Subject 3: 70
...
Student 1 - Total: 225, Average: 75.00
...
Why This Program is Important
- Helps understand nested loops
- Great for handling structured data
- Foundation for multidimensional array operations in C
Conclusion
This C program to calculate average and total of 5 students using nested loops is a practical exercise for beginners. It reinforces loop control, 2D array handling, and logic building in C.