How to loop when entering multiple similar items?

I am only one week into programming and I'm trying to learn how to use a loop. I need to ask the user to enter in 5 different test scores, and instead of repeating the step 5 times (what I did below), how can I make a loop to do it for me?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <cmath>
using namespace std;

int main () 
{

double project_1,test_1,test_2,test_3,test_4,test_5,overall_grade;

cout << "Please enter project_1 grade\n";
cin >> project_1;

cout << "Please enter test_1 grade\n";
cin >> test_1;
cout << "Please enter test_2 grade\n";
cin >> test_2;
cout << "Please enter test_3 grade\n";
cin >> test_3;
cout << "Please enter test_4 grade\n";
cin >> test_4;
cout << "Please enter test_5 grade\n";
cin >> test_5;

overall_grade = ((test_1 + test_2 + test_3 + test_4 + test_5)/5) 

cout << "Your grade is\n";
cout << overall_grade;

return 0;

}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

int main()
{
    const int NSCORES = 5 ;

    double total_score = 0 ;

    for( int i = 0 ; i < NSCORES ; ++i ) // repeat NSCORES times; for i = 0, 1, 2, .... (NSCORES-1)
    {
        std::cout << "Please enter test_" << i+1 << " score: " ;

        double score ;
        std::cin >> score ; // read the score of this test
        // assume that we are not required to validate the score; for example, score must be in the range (0,100)

        total_score += score ; // add to total
    }

    const double average_score = total_score / NSCORES ; // compute average

    std::cout << "average score: " << average_score << '\n' ;
}
Topic archived. No new replies allowed.