Mia Ng
Mia Ng

Reputation: 3

Adding all value to total in for loop

I'm new to coding. I wrote the below code in C++ and I am not allow to use array.

You will create a console C++ program that uses a nested loop to enter each archer's individual end scores and then displays the total score for each archer.

I am stuck at how to calculate the total end score:

#include <iomanip>

using namespace std;

int main()
{
    int Rounds = 4;
    int Archers = 3;
    int endScore ;

    int average;

    for (int a = 1; a <= Archers ; a++)
    {
        cout <<  endl << "Number " << a << " score" << endl;
        int tEndScore = 0 ;

        for(int i=1; i <=Rounds ; i++)
        {
            cout << "Round " << i << " : " ;
            cin >>  endScore;
            while(cin.fail())           
            {
                cout << endl << "not enter an integer " << endl ;                             
                cout << "Please enter an integer ";
                cin >> endScore;

            }
            tEndScore += endScore;

        }


        cout << endl << "The total score for 4 ends of Archer Number " << a << " is " << tEndScore << endl;
        average =(double) tEndScore/Rounds;
        cout << setiosflags(ios::fixed) << setprecision(2) << endl << "The average score of 4 ends of Archer Number " << a << " is " << average << endl;

    }
}

This is the result after running. It will only use the last value I entered as tEndScore:

image

Upvotes: 0

Views: 582

Answers (1)

RC0993
RC0993

Reputation: 958

You need to shift tEndScore =+ endScore; this line inside the second for loop as

for(int i=1; i <=Rounds ; i++)
{
    ...
    ...
    tEndScore += endScore;
}

And it will be a good practice (And mandatory for your code...) to initialize the tEndScore for each player as

for (int a = 1; a <= Archers ; a++)
{
    tEndScore = 0;
    endScore = 0;
    average = 0;
    ...
    ...
}

You need to replace totalEndScore to tEndScore and totalRounds to Rounds.

Upvotes: 1

Related Questions