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

Program doesn't execute for loop until the end

I’m writing a code to enter subjects’ information where I put void function and array as an object. But not sure when I wanna loop it, it doesn’t come until the end. Have a look at the code.

void calculateCGPA::getGPA() {
    cout << "Enter the the name of the subject: ";
    cin >> subjectName;
    cout << "Enter the credit hour:";
    cin >> credithour;
    cout << "Enter the grade: ";
    cin >> grade;
}

int main () {
    for (year=1; year<=4; year++) {
        for (sem=1; sem<=2; sem++) {
            cout << "Enter total subject you take in Year " << year << " Semester " << sem <<": ";
            cin >> totalSubjectSem;
            calculateCGPA ob[totalSubjectSem];
            for(int i = 1; i <= totalSubjectSem; i++) {
                cout << "Subject " << i << ": \n";
                ob[i].getGPA();
              }
        }
    }
    
return 0;   
}

enter image description here

Here’s the error. You can see the compiler only shows until entering the subject name but credit hour and grade are omitted. What should I do?

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

Expected: It should everything in void function until 3 (since I put 3) and then start over again "Enter total subject you take in Year 1 sem 2" but it also omits that

>Solution :

Take note that in C++ 0 is the first element, and n-1 is the last element. By looping to n, you cause a buffer overflow, hence resulting an error.

A solution would be as follows

void calculateCGPA::getGPA() {
    cout << "Enter the the name of the subject: ";
    cin >> subjectName;
    cout << "Enter the credit hour:";
    cin >> credithour;
    cout << "Enter the grade: ";
    cin >> grade;
}

int main () {
    for (year=0; year<4; year++) {
        for (sem=0; sem<2; sem++) {
            cout << "Enter total subject you take in Year " << year << " Semester " << sem <<": ";
            cin >> totalSubjectSem;
            calculateCGPA ob[totalSubjectSem];
            for(int i = 0; i < totalSubjectSem; i++) {
                cout << "Subject " << i << ": \n";
                ob[i].getGPA();
              }
        }
    }
}
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