Search code examples
c++loopsc++11do-whilegoto

How can I skip the goto statement if the user enters marks less than 100


Note: I am a beginner. I have used goto statement to execute if the user enters marks more than 200 but if the user has entered marks less than 100 then the rest of the code should run. How can I do that ?

Here is the piece of code

#include <iostream>
using namespace std;
int main()
{
    int a, b, c, d, e;
    float sum, perc;
    int total = 500;
INPUT:
    cout << "Enter marks for English" << endl;
    cin >> a;
    cout << "Enter marks for Urdu" << endl;
    cin >> b;
    cout << "Enter marks for Maths" << endl;
    cin >> c;
    cout << "Enter marks for Computer" << endl;
    cin >> d;
    cout << "Enter marks for Islamiat" << endl;
    cin >> e;

    if (a > 100 && b > 100 && c > 100 && d > 100 && e > 100) {
        cout << "You must enter all subject marks below 100" << endl;
    }
    goto INPUT;
    sum = a + b + c + d + e;
    perc = (sum / total) * 100;
    if (a <= 100 && b <= 100 && c <= 100 && d <= 100 && e <= 100) {
        cout << "Percentage is = " << perc << "%" << endl;
    }
    else {
        cout << "You must enter marks below 100" << endl;
        return 0;
    }

    if (perc >= 50) {
        cout << "Congratulations you are Passed" << endl;
    }
    else {
        cout << "You are fail" << endl;
    }

    return 0;
}

Solution

  • Just use do-while loop as for example

    bool success = false;
    
    do
    {
        cout << "Enter marks for English" << endl;
        cin >> a;
        cout << "Enter marks for Urdu" << endl;
        cin >> b;
        cout << "Enter marks for Maths" << endl;
        cin >> c;
        cout << "Enter marks for Computer" << endl;
        cin >> d;
        cout << "Enter marks for Islamiat" << endl;
        cin >> e;
    
        success = not ( a > 100 || b > 100 || c > 100 || d > 100 || e > 100 );
    
        if ( not success ) 
        {
            cout << "You must enter all subject marks below 100" << endl;
        }    
    } while ( not success );