Ali Tabibzadeh
Ali Tabibzadeh

Reputation: 193

Getting a program to start over and get a new value?

I am working with a program which requires a value to put in a variable and do some stuff on it. The problem is that I want the program to start over again and ask the user for a new value to process the new value again.

For example look at this code, which requires a number as a grade to rate it. When the processing was done I want the program to ask for a new grade ( next student for instance ).

#include <iostream.h>

int main (int argc, const char * argv[])
{
    int n;
    cout<< " Please Enter your grade : " ;
    cin>>n;
    switch (n/10) {
        case 10: cout<< " A+ : Great! ";

        case 9:
            break;
        case 8: cout<< " A : Very Good ";
            break;

        case 7: cout<< " B : Good " ;
            break;
        case 6: 
        case 5:
        case 4:
        case 3:
        case 2:
        case 1:
        case 0: cout<< " Failed ";
            break;

        default:
            break;
    }
    return 0;
}

Upvotes: 2

Views: 4266

Answers (1)

hrishikeshp19
hrishikeshp19

Reputation: 9028

What you need is a while loop

int main (int argc, const char * argv[])
{
    int n;
    while(1) {
        cout<< " Please Enter your grade : " ;
        cin>>n;
        switch (n/10) {
            case 10: cout<< " A+ : Great! ";

            case 9:
            case 8: cout<< " A : Very Good ";
                break;

            case 7: cout<< " B : Good " ;
                break;
            case 6: 
            case 5:
            case 4:
            case 3:
            case 2:
            case 1:
            case 0: cout<< " Failed ";
                break;

            default:
                break;
        }
        cout<<"do you wish to continue?(y/n)";
        cin>>some_declared_variable;
        if (some_declared_variable == 'n')
            break; //hopefully this will break the infinite loop
    }
    return 0;
}

Upvotes: 3

Related Questions