C++ program to find sum of marks entered by 30 students using for loop or while loop/

Dani AI

Generated

A few practical notes and fixes that make the thread answers complete and robust.

’s snippet has the right idea but a small typo causes a compile error: the program prints total while the accumulator is named totalmarks. Consistent names (or a single total) fix that error. ’s hint about summing array elements is fine, but storing all marks is unnecessary if only the total (and maybe the average) is required.

A minimal, corrected example with basic input validation:

#include <iostream>

int main() {
    const int STUDENTS = 30;
    int total = 0;
    for (int i = 0; i < STUDENTS; ++i) {
        int mark;
        std::cout << "Enter mark for student " << (i + 1) << ": ";
        while (!(std::cin >> mark)) {
            std::cin.clear();
            std::cin.ignore(1000, '\n');
            std::cout << "Invalid input. Enter an integer: ";
        }
        total += mark;
    }
    std::cout << "Total marks = " << total << '\n';
    return 0;
}

A modern alternative: collect into a std::vector<int> and use std::accumulate (makes computing averages trivial), or skip storage entirely when only the sum is needed.

Troubleshooting and best practices:

  • Prefer a named constant for the student count (avoid magic numbers).
  • Validate input to avoid infinite loops on bad input.
  • If marks or the number of students can be large, use a wider accumulator (long long).
  • Use for when the count is known; use while only when reading until a condition is met.
  • Avoid using namespace std; in real projects to prevent name collisions.

These small changes remove compile errors and make the program robust for typical classroom data.

Recommended Answers

All 2 Replies

i am learning arrays in c++. and i think if you try for it then you can do it very easily.

as a hint
you should start loop from 0 to 29 and add values like
sum+=array[index]

if you put your efforts here it will be very easier for us to identify where you are going wrong. So , don't forget to put here your code.

// find total marks of 30 students using for loop
#include <iostream>
using namespace std;

int main()
{
    int marks[30];              
    int totalmarks = 0;         

    for(int j = 0; j < 30; j++ )
    {
        cout << "Enter marks of student " << j+1;
        cin >> marks[j];                         
        totalmarks = totalmarks + marks[j];
    }
    cout << "\nTotal marks of 30 student = " << total ;
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.