Appropriate Loop Needed

Hi there, being new to the forum i simply hope this is firstly in the right forum but i am here to ask a question that i have been stumped on for hours and that's choosing the right loop type and how i would go about implementing it into my little practise program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    char Option;

    cout << " \t Choose the option you wish to display: \n";
    cout << "1. Apples" << endl << "2. Bananas" << endl << "3. Carrots";
    cout << "\n" << "\n";

    cin >> Option;

        if(Option == '1')
        {
            cout << "You have selected Apples \n";
        }

        if(Option == '2')
        {
            cout << "You have selected Bananas \n";
        }

        if(Option == '3')
        {
            cout << "You have selected Carrots \n";
        }

    return 0;
}


I need the program to repeat the question and the choices available IF the user doesn't input the right choice number ( 1 - 3 ), i have tried to implement a switch into the code but had no luck but it may be easier, i am just not sure what to do at this point :P Hope someone out there can help me :)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
while (true)
{
    cin >> Option;
    
    if ( 1... )
    {
        ...
    }
    else if ( 2... )
    {
        ...
    }
    else if ( 3... )
    {
        ...
    }
    else
    {
        break;
    }
}
1
2
3
4
do {
    cin >> Option;
    ...
} while( Option < 1 || Option > 3 );

do-while should work best here because you need to run the loop (at least) once, asking the user for input, before checking if if that input is valid.

Please use else if:
1
2
3
4
5
6
7
8
if( Option == 1 ) //checks if Option is 1
    ...
// if( Option == 2 ) //checks if Option is 2,
                          // there is no need to do this is Option was 1,
                          // because Option can't be 1 and 2! Instead use "else":
else if( Option == 2 ) //If and only if Option wasn't 1, check if it's 2
    ...
else if( Option == 3 ) //If and only if Option wasn't 1 or 2, check if it's 3 
Thank you for the replies and thanks Mathhead for the else if usage - best be introducing the good habits now i guess :P also the while( Option < 1 || Option > 3 ) works great, just what i needed thank you :)
No problem, just make sure you understand why it works.
Topic archived. No new replies allowed.