Home > Net >  How can I make my 'for' statement work fine, and how can I calculate the total?
How can I make my 'for' statement work fine, and how can I calculate the total?

Time:10-15

class score {
private:
    int marks;
    int total;
public:
public:
    score(){ marks = 0; total = 0; }
    void getM();
    void tot();
    void displayM();
    void cinM();
};
void score::displayM()
{
    cout << "The score is " << total << endl;
}

void score::getM()
{
    for (int i = 0; i <= subjects; i  )
        cout << "Enter the score of the subject " << i << endl;
    cin >> marks;
}
   
void score::tot()
{
    total = total   marks;
}

Output is:

Enter the score of the subject 0
Enter the score of the subject 1
Enter the score of the subject 2
Enter the score of the subject 3
Enter the score of the subject 4
Enter the score of the subject 5
// once i write any number it just print 
The score is 3

The output in my mind is:

Enter the score of the subject 0 3
Enter the score of the subject 1 3
Enter the score of the subject 2 1
Enter the score of the subject 3 3
Enter the score of the subject 4 3
Enter the score of the subject 5 2
The score is 15

CodePudding user response:

void score::getM()
{
    cin >> marks;
    tot();
}
   

And then in main,

// main.cpp
int main() {
    score s;
    for(int i=0; i<5; i  ) {
        cout << "Enter the score of the subject " << i 1 << endl;
        s.getM();
    }
    s.displayM();
    return 0;
}

Here is a demo with full code:

// main.cpp
#include<iostream>
using namespace std;

class score {
private:
    int marks;
    int total;
public:
public:
    score(){ marks = 0; total = 0; }
    void getM() {
        cin >> marks;
        tot();
    }
    void tot() {
        total = total   marks;
    }
    void displayM() { 
        cout << "The score is " << total << endl; 
    }
};


int main() {
    score s;
    for(int i=0; i<5; i  ) {
        cout << "Enter the score of the subject " << i 1 << endl;
        s.getM();
    }
    s.displayM();
    return 0;
}

To compile and run

g   -Wall main.cpp
./a.out

The output:

❯ ./a.out 
Enter the score of the subject 1
1
Enter the score of the subject 2
2
Enter the score of the subject 3
3
Enter the score of the subject 4
4
Enter the score of the subject 5
5
The score is 15
  •  Tags:  
  • c
  • Related