Loops

Pages: 123... 7
I am trying to understand loops very well before I move onto the next section of C++.

I am attempting what may be a task beyond my knowledge. I have made a guessing numbers game using if statements and a loop. I want to include that as an extension of the program. I would like to include 3 possible programs within one. I copied the calculator - Have no clue how it works. Just trying to add if into my program options.

Is this possible with loops and ifs? I have included the source as it stands now. Please provide input. Thanks.

Edit I am updating the code as it stands. Because this serves as a cover page to the post. I have scrapped the old code and am starting fresh. This is the code as it stands:

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#include <iostream>
#include <cstdlib>
#include <ctime>

using std :: cin;
using std :: cout;
using std :: string;
using std :: endl;

void EnterName();
void ShowMenu();
void UseCalculator();
void PlayGuessingGame();
void EnterText();
void MenuReturn();

int main()
{
    char ReturnMenu;

    EnterName();

    while (ReturnMenu == 'Y')
        {
        ShowMenu();
        }
                cout << "\nGoodbye." << endl;
                return 0;
}

void EnterName()
{
    string name;

    cout << "Hello, Enter your name." << endl;
    cin >> name;
    cout << "\nHello, " << name << "." << endl;
}

void ShowMenu ()
{
    char MenuOption;
    char ReturnMenu;

    do
    {
        cout << endl;
        cout << "\t\t\t_______________________________" << endl;
        cout << "\t\t\t| What would you like to use? |" << endl;// Options the program offers
        cout << "\t\t\t|-----------------------------|" << endl;
        cout << "\t\t\t|   (A) Basic Calculator      |" << endl;
        cout << "\t\t\t|   (B) Guess the number      |" << endl;
        cout << "\t\t\t|   (C) Print your text       |" << endl;
        cout << "\t\t\t|_____________________________|" << endl;
        cin >> MenuOption;
        MenuOption = toupper(MenuOption);

        switch ( MenuOption )
        {

            case 'A':
                UseCalculator();
                break;

            case 'B':
                PlayGuessingGame();
                break;

            case 'C':
                EnterText();
                break;

            default:
            cout << endl;
            cout << "'" << MenuOption << "' Is not a choice." << endl;
            break;

        }
            cout << "\nWould you like to return to main menu? (Y/N)" << endl;
                cin >> ReturnMenu;
                ReturnMenu = toupper(ReturnMenu);

                while ( ReturnMenu != 'Y' && ReturnMenu != 'N')
                {
                        cout << "\n'" << ReturnMenu << "' Is not an option.\n"
                        "Would you like to return to the main menu? (Y/N)";
                        cin >> ReturnMenu;
                        ReturnMenu = toupper(ReturnMenu);
                }
    }
                while (ReturnMenu == 'Y');
}
void UseCalculator()
{
    cout << "\nCalculator" << endl;
}
void PlayGuessingGame()
{
    srand(time(NULL));

    int num = 0;
    char PlayAgain = 'Y'; // Program replay
    char Game;  // user inputs so far

    cout << "\nGuessing game" << endl;

        do
            {
                    cout << "\nPick a number: (1-10)  ";
                    cin >> num;                         //users number choice
                    cin.ignore(1000, '\n');

                        while (num < 1 || num > 10 || cin.fail())  //error checking - number outside of range
                        {
                            cin.clear();                // clearing bad input, without enter "dslfkjn"
                            cin.ignore(1000, '\n');     // will cause program to go into a crazy loop

                            cout << "\nInvalid input. Pick a number (1-10)  ";
                            cin >> num;                 // re-enter a number within range

                        }

                if (num == (rand() % 10 + 1))
                    //check users number with correct random number
                    cout << "\nCongradulations, you guessed correct." << endl;
                   //if correct display this

                else
                    cout << "\nYou guessed wrong." << endl;       //wrong choice display this

                        cout << "\nWould you like to play again? (Y/N)  " << endl;
                        cin >> PlayAgain;                   //option to play again - loop
                        PlayAgain = toupper(PlayAgain);

                            while (PlayAgain != 'Y' && PlayAgain != 'N') // Play again error check
                            {
                                cin.clear();
                                cin.ignore(1000, '\n');
                                cout << "\nInvalid input. Would you like to play again? (Y/N) ";
                                cin >> PlayAgain;
                                PlayAgain = toupper(PlayAgain);
                            }
            }
                while ( PlayAgain == 'Y' );  // Loop option A
}
void EnterText()
{
    cout << "Enter text" << endl;
}
Last edited on
Line 20 makes you ignore input until an 'n' is reached. So until an 'n' is input, you will not go past that line. I suspect you really meant '\n', or an enter.
Thanks, I feel silly. Made that mistake a few times. I am new to programming so the code at times overwhelms my eyes.
You have the right idea. Everything looks good. I would also surround the menu in another do while. Let's say the user guesses a number but then wants to use your calculator. They would need to relaunch your application. This way when they're done guessing a number, they'll be asked what to do next.
Just a few things I've noticed you will want to fix:

1
2
3
4
if  (Game == 'a' || Game == 'A')
// need a brace here
        do 
        {


1
2
3
4
5
while (PlayAgain == 'y' || PlayAgain == 'Y');
                cout << "Thank you for playing\n";
                cin.ignore();
// and here
    if (Game == 'b' || Game == 'B')


Otherwise when you enter "b" into your program, it'll say "Thank you for playing" even though you didn't play the guessing game.

As for the calculator, you may want to make your own, as that one doesn't seem to be too reliable.
What am I doing wrong? After selecting Game A it runs smoothly. If I choose to not play again I am prompted with return to main menu. It does not do anything.

I also have a similar problem as Phil123 has stated with "Thank you for playing". Where do braces go?

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    srand(time(0));

    char Game;  // user inputs so far
    char Return;
    int num;
    char PlayAgain;
    long L1;
	long L2;
	long L3;
do {
        cout << "What would you like to use?\n"; // 3 options
        cout << "Guess the number (A)\n";
        cout << "Basic Calculator (B)\n";
        cout << "Print your text (C)\n";
        cin >> Game;
        cin.ignore(256, '\n');

    if  (Game == 'a' || Game == 'A') //first trigger to option one
    {
        do
        {
                cout << "Pick a number: (1-10)  ";
                cin >> num;  //users number choice
                cin.ignore(256, '\n');

                while (num < 1 || num > 10)
                { //error checking - number outside of range
                    cout << "Number not within range. Pick a number (1-10)  ";
                    cin >> num;  // re-enter a number within range
                    cin.ignore(256, '\n');
                }
            if (num == (rand() % 10 + 1))
            {  //check users number with correct random number
                cout << "\nCongradulations, you guessed correct. \n";
            } //if correct display this

                else
                    cout << "\nYou guessed wrong.\n"; //wrong choice display this

                cout << "\nWould you like to play again? (y/n)  ";
                cin >> PlayAgain; //option to play again - loop
                cout << "\n";
                cin.ignore(256, '\n');
        }
                while (PlayAgain == 'y' || PlayAgain == 'Y');
                cout << "Thank you for playing\n"; // display text at exit
                cin.ignore();


        cout << "Would you like to return to main menu?  ";
        cin >> Return;
        cout << "\n";
        cin.ignore(256, 'n');

    }
}
    while (Return == 'y' || Return == 'Y');
    cout << "Goodbye\n";
    cin.ignore();


    if (Game == 'b' || Game == 'B')
If I choose to not play again I am prompted with return to main menu. It does not do anything.


Line 61: cin.ignore(256, 'n');

should be: cin.ignore(256, '\n');
Iv'e made that mistake more than twice now. I should be shunned! =p
Thank you!
As Phil123 pointed out "Thank you for playing" would be displayed if the user chose option b. Now I ave an issue with "Goodbye" from adding the loop to return to menu.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
          cout << "\nWould you like to play again? (y/n)  ";
                cin >> PlayAgain; //option to play again - loop
                cout << "\n";
                cin.ignore(256, '\n');
        }
                while (PlayAgain == 'y' || PlayAgain == 'Y');
                cout << "Thank you for playing\n"; // display text at exit
                cin.ignore();


        cout << "Would you like to return to main menu?  ";
        cin >> Menu;
        cout << "\n";
        cin.ignore(256, '\n');

    }
   }
    while (Menu == 'y' || Menu == 'Y');
    cout << "Goodbye\n";
    cin.ignore();


    if (Game == 'b' || Game == 'B')


I know I need braces, but cannot figure out where.

Also If you play through option one and return to the main menu you cannot select option b anymore. It keeps asking what you would like to use.
Last edited on
Edit: Going to give you a few examples, one sec

1
2
3
4
if (num == (rand() % 10 + 1))
	cout << "\nCongradulations, you guessed correct. \n";
else
	cout << "\nYou guessed wrong.\n";


is the same as:

1
2
3
4
5
6
7
8
if (num == (rand() % 10 + 1))
{
	cout << "\nCongradulations, you guessed correct. \n";
}
else
{
	cout << "\nYou guessed wrong.\n";
}


Take a look at this:

1
2
3
4
5
if (num == (rand() % 10 + 1))
	cout << "If, display this\n";
else
	cout << "Else, display this\n";
cout << "This will always be displayed!!!\n";


And this:


1
2
3
4
5
6
7
8
9
10
if (num == (rand() % 10 + 1))
{	
	cout << "If, display this\n";
	cout << "If, display this too\n";
}
else
{
	cout << "Else, display this\n";
	cout << "Else, also display this\n";
}


You can mix and match, and it's fine:


1
2
3
4
5
6
7
if (num == (rand() % 10 + 1))	
	cout << "If, display this\n";
else
{
	cout << "Else, display this\n";
	cout << "Else, also display this\n";
}


This:

1
2
cout << "Thank you for playing\n"; 
cin.ignore(); // this doesn't seem necessary 


1
2
if (Game == 'b' || Game == 'B') // This should be inside of your main while loop
// It should come right after the end brace for your first if statement, the: if (Game == 'a' || Game == 'b') 


Alright, time for me to go to bed. Good luck with the debugging session, I'll check back in the morning
Last edited on
It is at the top of the post. I have been keeping it up to date.
I did mess around with the braces.

Thank you for explaining the braces. Helped a lot on the individual statements.

I cannot figure out what you mean by

(Game == 'b' || Game =='B')

should come after the first "if" and in the main "while". As silly as it may sound..what is the main "while"? The main loop I thought was a "do while".
Unless you are referring to the "while" in the "do". If that is the case I moved braces all over and it gives me errors. I temporarily replaced the calculator code with a 'cout' to make things a little clearer, for me.

My head hurts... ha Its 2AM. I am determined to figure this out, but I hit a wall. Going to try and get some sleep.

Source as of now at the top of post.
Last edited on
Maybe this quick bit of code can help you out:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
do {
   //displayMenu

   //switch
   case 'a':
   case 'A':
      do {
         //guess a number
      } while (playAgain);
      break;
   case 'b':
   case 'B':
      do {
         //calculator
      } while (playAgain);
      break;
   case 'c':
   case 'C':
      do {
         //print your text
      } while (playAgain);
      break;
} while(!exit);


It's only a basic outline of what I think the program should look like, and if you haven't used switches yet, you can use if/else statements as well.
Last edited on
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    srand (time(NULL));

    char Game;
    char Menu = 'Y';
    int num = 0;
    char PlayAgain = 'Y';

	do	{
            cout << "What would you like to use?\n"
			 "Guess the number (A)\n"
			 "Basic Calculator (B)\n"
		 	 "Print your text (C)\n";
            cin >> Game;

			while (Game != 'a' && Game != 'A' && Game != 'b' && Game != 'B' && Game != 'c' && Game != 'C')
			{
				cin.clear();
				cin.ignore(1000, '\n');

				cout << "\nInvalid input. Pick a function (a, b, c):  ";
				cin >> Game;  
			}

			if  (Game == 'a' || Game == 'A')
			{
				do
				{
					cout << "Pick a number: (1-10)  ";
					cin >> num;

					while (num < 1 || num > 10 || cin.fail())
					{     
						cin.clear();
						cin.ignore(1000, '\n');

						cout << "\nInvalid input. Pick a number (1-10):  ";
						cin >> num;  
					}

					if (num == (rand() % 10 + 1))
						cout << "\nCongradulations, you guessed correct. \n";                   
					else
						cout << "\nYou guessed wrong.\n"; 

					cout << "\nWould you like to play again? (y/n)  ";
					cin >> PlayAgain; 

					while (PlayAgain != 'y' && PlayAgain != 'Y' && PlayAgain != 'n' && PlayAgain != 'N')
					{
						cin.clear();
						cin.ignore(1000, '\n');
						cout << "\nInvalid input.  Would you like to play again? (y/n)  ";
						cin >> PlayAgain;
					}

				}  while (PlayAgain == 'y' || PlayAgain == 'Y');
                                                     
			}

			if (Game == 'b' || Game == 'B')
			{
				// Game B stuff goes here
			}

			if (Game == 'c' || Game == 'C')
			{
				// Game C stuff goes here
			}


			cout << "\nThank you for playing\n"
					"\nWould you like to return to the main menu? (y/n)  ";
			cin >> Menu;

			while (Menu != 'y' && Menu != 'Y' && Menu != 'n' && Menu != 'N')
			{
				cin.clear();
				cin.ignore(1000, '\n');
				cout << "\nInvalid input.  Would you like to return to the main menu? (y/n)  ";
				cin >> Menu;
			}

		} while (Menu == 'y' || Menu == 'Y');

	cout << "Goodbye\n";
	return 0;
}


Updated.
Last edited on
I think I understand this. But, there are issues.

When asked to play again. It says invalid input. When you re-enter your choice prompted with invalid input, it doesn't do anything.

Updated, top if post
You should get rid of the cin.ignore(1000, '\n'); whenever you have, say, cin >> PlayAgain preceding it, since you now clear bad input anyways, it's no longer necessary
Last edited on
Invalid input. Would you like to play again is still displayed after saying "y" or "n".

It seems to be asking twice.

"Would you like to play again" y (or no)
"Invalid input. Would you like to play again?" // It works from here. only exception is that you can type anything into here other than 'y' and it acts as a 'n'.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  if (num == (rand() % 10 + 1))
                    //check users number with correct random number
                    cout << "\nCongradulations, you guessed correct. \n";
                   //if correct display this

                else
                    cout << "\nYou guessed wrong.\n"; //wrong choice display this

                        cout << "\nWould you like to play again? (y/n)  ";
                        cin >> PlayAgain; //option to play again - loop
                        cout << "\n";

                            while (PlayAgain != 'y' && PlayAgain != 'Y' && PlayAgain != 'n' && PlayAgain != 'N');
                            {
                                cin.clear();
                                cin.ignore(1000, '\n');
                                cout << "Invalid input. Would you like to play again? (y/n) \n";
                                cin >> PlayAgain;
                            }
            }
                while (PlayAgain == 'y' || PlayAgain == 'Y');
Semi-colons are very evil.

1
2
3
4
5
6
7
8
while (PlayAgain != 'y' && PlayAgain != 'Y' && PlayAgain != 'n' && PlayAgain != 'N');  // bad semi-colon, 
             // get rid of it and it should solve your problems
                            {
                                cin.clear();
                                cin.ignore(1000, '\n');
                                cout << "Invalid input. Would you like to play again? (y/n) \n";
                                cin >> PlayAgain;
                            }



Copy this into your compiler, and check out the difference between the two.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

int main()
{
	int i = 1;
	while (i == 1); // because of this semi colon, and the fact that i == 1 equals to true, the program will never display the message
 // to be more specific, the while loop will continue looping forever, but it 
// doesn't do anything because you didnt tell it to do anything, by putting a 
// semi colon after the while (i == 1) you're basically saying "ok, that's it, don't do anything"
	{
	cout << "Now why wouldn't THIS message be displayed to the screen?";
	}


	return 0;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
	int i = 1;

	while (i == 1)
	{ // I'm telling the compiler this is the beginning of the while loop
	cout << "This will loop forever\n";
	} // and here I'm telling the compiler that's the end of it


	return 0;
}


Take a look at how while loops and do while loops work. Here are two examples:

1
2
3
4
5
6
7
8
9
do
{
 // do stuff, and then if test expression == true, then do stuff again
} while ( /* test expression goes here */ );  // notice the semi-colon

while ( /* test expression goes here */ ) // notice how we don't have a semi-colon here
{
 // ensure the test expression == true, then do stuff
}


I hope this clears up things for you - let me know if you have any other questions. The difference between a do while loop and a while loop is with a do while loop, you want to "do stuff" and then evaluate whether or not you want to keep "doing stuff." Where as with a while loop, you have to FIRST evaluate if you want to "do stuff" and then after that it's the exact same thing as a do while loop.
Last edited on
I have a quick question on the topic. I've always known do whiles to have a semi colon after them. What happens when there is no semi colon? Do you just get error? Or will it run the next section AFTER the while?
If you're missing a semi-colon for the do while loop, you'll get an error that says "hey, where the hell is your damn semi-colon?"

Actual error message:

error C2143: syntax error : missing ';' before 'return'
(in this case, I omitted the semi-colon before return 0; for my int main() function)
Last edited on
Pages: 123... 7