Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading