while loop error

I am writing a programming tutorial program and I am having some difficulty with a while loop. For this loop, I want the final selection to proceed to the next topic in the tutorial but after selecting the last section the program ends. I am sure my error is small but would appreciate any insight you could provide

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
33
34
35
36
37
38
39
40
41
42
43
  			while (choice != 5)
			{

				if (choice == 1)
				{
					cout << "While loops are a conditional loop for situations " << endl;
					cout << "were it only iterates when true from the beginning. " << endl;
					cout << "If the first iteration is false the loop will not" << endl;
					cout << "iterate at all." << endl;
					cout << "please make another selection" << endl;
					cin >> choice;
				}
				else if (choice == 2)
				{
					cout << "Do-while loops are a post test conditional loop" << endl;
					cout << "for situation where you always want it to iterate" << endl;
					cout << "at least once." << endl;
					cout << "please make another selection" << endl;
					cin >> choice;
				}
				else if (choice == 3)
				{
					cout << "For loops are a pretest loop with built in" << endl;
					cout << "expressions for initializing, teasting" << endl;
					cout << "and updating. This loop is ideal for" << endl;
					cout << "situations where the exact number of " << endl;
					cout << "iterations is known" << endl;
					cout << "please make another selection" << endl;
					cin >> choice;
				}
				else if (choice == 4)
				{
					cout << "The if /else if loop is used to test mulitiple " << endl;
					cout << "conditions" << endl;
					cout << "please make another selection" << endl;
					cin >> choice;
				}

				else if (choice ==5)
					// topic 3
					cout << "welcome to topic 3";
			}
		}
How about
1
2
3
4
5
while ( choice != 5 ) {
    // your 1 to 4 choices as written
    // remove choice == 5 code
}
cout << "welcome to topic 3";
Hello PermThesis,

Note: It is most often better to post the whole code than what you think is wrong.

What is the setup before the while loop? How do you get a value for "choice"?

If "choice" is 1 to 4 you will enter the while loop. If "choice " is greater than 5 you will enter the while loop, but the if/else if statements will never match and nothing will happen except that you will likely have an endless loop.

If choice is equal to 5 the while condition becomes false and the loop fails.

For now yo might want to end the if/else if statements with a final else to catch anything that is not a valid choice. You may also want to put a "break" statement to exit the while loop if "choice" is invalid.

If I could see the rest of the code I would have other suggestions.

Hope that helps,

Andy
Topic archived. No new replies allowed.