Loops

Pages: 1234567
Sorry dude but that isn't right.

I did leave out a semicolon, but it is not where you think it is.

If ReturnMenu is equal to 'Y' then you an ifinite loop, because the ; creates a null statement.

You need to understand what a compound statement is.

1
2
3
4
5
6
7
8
9
10
11
12
while(test-expression) // no semicolon
      single statement;  // semicolon this is executed only if test-expression is
                                 // false 
// execution jumps to here if test-expression is false

while(test-expression) {    // no semicolon the braces indicate a compound     
                                      //   statement
     // these are executed only if test-expression is
     // true
      muliple  statements;  // semicolon affter each one
}   
// execution jumps to here if test-expression is false   


Can you see now where the ; should go?

A compound statment can appear any where a single statement can.

The same idea applies to if, for, switch etc. Functions definitions are always in braces.

I normally use braces around single statements as a defensive measure. When you come to add more lines later, this can save you.

Perhaps I should explain how the loops work in detail - I am not sure you have fully got it yet. Looking at the code above for a while loop:

The test-expression is evaluated, if true then the statement (or compound statement) is executed, if test-expression is false then execution continues with the next line of code after the statement (or compound statement). This procedure is repeated (loops around).

I think you should look at the examples in the reference section of this site, for all the things you want to use.

Cheers TheIdeasMan



I know you are trying to teach me (make me think) how and why, not just show me the way to do it. I like that but the code without the semi colon where it is now, doesn't work. It completely skips the "ShowMenu" function.

This :
1
2
3
4
 while (ReturnMenu == 'Y');
        {
        ShowMenu();
        }

Only works this way.

and this way:

1
2
while (ReturnMenu == 'Y');
        ShowMenu();


I would Like you to copy the code into your compiler.

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
SGM3 wrote:
Only works this way.
Nope, both won't work due to the semicolon right after the while statement. It's an empty loop that will loop forever if ReturnMenu would be 'Y'. But since ReturnMenu isn't set at all the wile loop doesn't make sense at all.
It does work. I am using it now.

I am not trying to argue with anyone.

It works.

Normally I agree that the semicolon creates an endless loops or sometimes the loop does nothing at all. But, It is working now.

I take that back. The loop does do nothing. (not in the sense that I am accustomed to) ha

I removed the loop. It is useless given that the loop is defined in the ShowMenu function.
Ok here is some code from the reference section on this site - as I said in my last post - you need to read all these.

1
2
3
4
5
6
7
8
9
 int n;
  cout << "Enter the starting number > ";
  cin >> n;

 while (n>0) {
    cout << n << ", ";
    --n;
  }


This is just same as what I said earlier.

The problem is that this code is the while statement of the do while loop:
1
2
3
4
do {


}while ( PlayAgain == 'Y' ); 


This is another reason why do-whiles are confusing, why I don't like them and why I am asking you to change them to while loops.

I don't wish to use my compiler, because it is on my linux disk and I don't have access to the net at the moment, so I would have to reboot to get at it.

Now, for your code:

You should have a ProcessMenuOption function, instead of having the switch inside ShowMenu.

You still have do while loops - better to convert them to while's.

1
2
3
while ( PlayAgain == 'Y' ){

};


You still have this logic which is counterintuitive as per the discusssion about IsOperator function:

(PlayAgain != 'Y' && PlayAgain != 'N')

Now this could be done better:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

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


See how you are asking to "play again" twice ? Perhaps PlayAgain could be a function, just like IsOperator?


TheIdeasMan

Another thing :

You have the same "play again" code in main as well as in the calculator, which is another reason to have it as a function.

TheIdeasMan
I may not be getting it. This does not work with ||. It does nothing. I tried all sorts of combinations to get it to work using your explanation but it only works like that. I don't understand why.
(PlayAgain != 'Y' && PlayAgain != 'N')

while loops must be confusing to me because I understand the do while that I am using. I am having a problem looping the menu in a while loop.

I am asking to play a second time which follows Invalid input. It is to display something if the user inputs something that is not requested.

I don't like a blank screen, until the requested input is put in.
Last edited on
Phil123 explained that code won't work with ||'s.

I am saying write a PlayAgain function that is very similar to IsOperator and get rid of "(PlayAgain != 'Y' && PlayAgain != 'N')" altogether because it is counterintuitive.

while loops must be confusing to me because I understand the do while that I am using. I am having a problem looping the menu in a while loop.


This is pretty simple isn't it?

1
2
3
4
5

while ( PlayAgain ==  true){

};


We probably need 2 things:

1
2
3
4

bool PlayAgain;
void WantToPlayAgain(); // a function that asks the question and sets the PlayAgain variable this function will have something similar to IsOpeator in it.


TheIdeasMan
Last edited on
I am not using that calculator anymore. I am going to attempt to write one.
Ok - I am sorry. So many posts about different parts of the code. I get sidetracked with one and lose track of other parts.

I hope I am not coming off as a %##.

I really appreciate your help. I just get frustrated with myself when I don't understand things.
If you are writing another one, I am hoping you have a methodology to do it?

I you do, write it in a blank file as comments, then write the code after each comment. This will help you organise your thoughts logically and is a simple way to design your program. The comments serve as documentation.

If you don't have another methodology, then you might write more code and find your self in the same situation as you are now.

We were making goods progress with the original code, and I hope that you have learnt quite a bit from it.

Don't loose heart now, I think we can do this thing !!

Cheers TheIdeasMan
Ok then I will keep the old one. I thought you didn't like it.
Well it was a bit of a mess when I first came across it, and I was thinking of other algorithms like K&R RPN calculator, and how compilers process mathematical expressions.

So, post your code once you have done ProcessMenu() and WantToPlayAgain().

TheIdeasMan

I do not understand this bool function and how to apply it to my needs.
Phil123's examples are not clear to me and is futile.
This stuff I have been doingis beyound my knowledge, which is good.
But, searching the internet for information that makes sense is a needle in a haystack.

Please show me where the code should 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
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
150
151
152
153
154
155
156
157
158
#include <iostream>
#include <cstdlib>
#include <ctime>

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

bool ReplayGuessing(char PlayAgain);

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

int main()
{
    EnterName();


        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;

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

                    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



}
void EnterText()
{
    cout << "Enter Text" << endl;
}

bool ReplayGuessing(char PlayAgain)
{
    PlayAgain = toupper(PlayAgain); // Note!
    while ( PlayAgain != 'Y' && PlayAgain != 'N')
    {
        cin.clear();
        cin.ignore(1000, '\n');
        cout << "\nInvalid input. Would you like to play again? (Y/N) ";
        cin >> PlayAgain;
        PlayAgain = toupper(PlayAgain);
    }
    return (PlayAgain == 'Y');  // Note!
}
void WantToPlayAgain()
{
    char PlayAgain;

        cout << "\nWould you like to play again? (Y/N)  " << endl;
        cin >> PlayAgain;                   //option to play again - loop
        PlayAgain = toupper(PlayAgain);
}
    cout << "Enter text" << endl;
}
Last edited on
Remove line 133 to 136. Line 139: while (ReplayGuessing(PlayAgain));

1
2
3
4
5
6
7
8
9
10
11
12
13
bool ReplayGuessing(char PlayAgain)
{
    PlayAgain = toupper(PlayAgain); // Note!
    while ( PlayAgain != 'Y' && PlayAgain != 'N')
    {
        cin.clear();
                                cin.ignore(1000, '\n');
                                cout << "\nInvalid input. Would you like to play again? (Y/N) ";
                                cin >> PlayAgain;
                                PlayAgain = toupper(PlayAgain);
    }
    return (PlayAgain == 'Y');  // Note!
}
Still have problems.

I updated the code in my recent post. I am getting

"Line 156 expected constructor, destructor, or type conversion before '<<' token"
"Line 157 expected declaration before '}' token


My code only goes up to line 155...
Bool is not a function it is a type which is either true or false. You can see how it works by looking at the IsOperator function.

But, searching the internet for information that makes sense is a needle in a haystack.


There is heaps of reference info on this site. Otherwise Google "C++ while loop example" as an example.

Here's what I meant by the ProcessMenu function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{
char MenuOption;

    EnterName();

while (MenuOption != 'Q');
        {
        ShowMenu();
        cin >> MenuOption;
        MenuOption = toupper(MenuOption);

        ProcessMenu(MenuOption )
        }
return 0;
}


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
void ProcessMenu(char MenuOption ){

switch ( MenuOption )
        {

            case 'A':
                UseCalculator();
                break;

            case 'B':
                PlayGuessingGame();
                break;

            case 'C':
                EnterText();
                break;

            case 'Q':  // Quit the program
                exit(0);
                break;

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

        }
}



1
2
3
4
5
6
7
8
9
10
11
12
void ShowMenu() {

cout << endl;
        cout << "\t\t\t_______________________________" << endl;
        cout << "\t\t\t| What would you like to use? |" << endl; 
        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|   (Q) Quit                     |" << endl;
        cout << "\t\t\t|_____________________________|" << endl;
}



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
bool WantToPlayAgain()
{
    bool PlayAgain = true;
    char Response = 'N';
    cout << "\nWould you like to play again? (Y/N)  " << endl;

    cin >> Response ;                   
     Response = toupper(Response );
   switch (Response ) {
   case 'Y':
      return true;
      break;
   default:
      return false;
       break;
   }

}


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
while ( PlayAgain == true ) {

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

         if (num < 1 || num > 10 || cin.fail())  {    //error checking
                        
          cin.clear();                // clearing bad input, without enter "dslfkjn"
           cout << "\nInvalid input. Pick a number (1-10)  ";
           continue;  //start the while loop again
           }

                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

                       PlayAgain = WantToPlayAgain() ;

}
                


ReplayGuessing is now unneccesary

You need to write a function that handles the new Quit option on the Menu

See how you go with that


Last edited on
Doesn't work...

The semi colon here:
while (MenuOption != 'Q');
The program does nothing after entering in a name.

If I put a semi colon in it just repeats the menu.
If I select the Guessing game it just outputs "guessing game" then goes back to menu.

The Q works by itself at the menu. But if someone wanted to quit while in the guessing game I can see how a quit function could be useful.

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
#include <iostream>
#include <cstdlib>
#include <ctime>

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

bool WantToPlayAgain()
{
    bool PlayAgain = true;
    char Response = 'N';
    cout << "\nWould you like to play again? (Y/N)  " << endl;

    cin >> Response ;
     Response = toupper(Response );
   switch (Response )
   {
        case 'Y':
        return true;
        break;
        default:
        return false;
        break;
   }

}

void EnterName();
void ShowMenu();
void ProcessMenu(char MenuOption);
void UseCalculator();
void PlayGuessingGame();
void EnterText();
void MenuReturn();

int main()
{
    char MenuOption;

            EnterName();

        while (MenuOption != 'Q')
        {
            ShowMenu();
            cin >> MenuOption;
            MenuOption = toupper(MenuOption);

            ProcessMenu(MenuOption);
        }
            return 0;
}

void EnterName()
{
    string name;

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

void ShowMenu ()
{
    cout << endl;
        cout << "\t\t\t_______________________________" << endl;
        cout << "\t\t\t| What would you like to use? |" << endl;
        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|   (Q) Quit                  |" << endl;
        cout << "\t\t\t|_____________________________|" << endl;
}

void ProcessMenu(char MenuOption )
{
    switch ( MenuOption )
    {

            case 'A':
                UseCalculator();
                break;

            case 'B':
                PlayGuessingGame();
                break;

            case 'C':
                EnterText();
                break;

            case 'Q':  // Quit the program
                exit(0);
                break;

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

    }
}
void UseCalculator()
{
    cout << "\nCalculator" << endl;
}
void PlayGuessingGame()
{
    srand(time(NULL));

    int num = 0;
    char PlayAgain = 'Y'; // Program replay

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

        while ( PlayAgain == true )
        {
            cout << "Pick a number: (1-10)  " << endl;
            cin >> num;                         //users number choice
            cin.ignore(1000, '\n');

            if (num < 1 || num > 10 || cin.fail())
            {        //error checking
                cin.clear();                // clearing bad input, without enter "dslfkjn"
                cout << "\nInvalid input. Pick a number (1-10)  ";
                continue;  //start the while loop again
            }

                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

                      PlayAgain = WantToPlayAgain();

        }
}
void EnterText()
{
    cout << "Enter Text" << endl;
}
Last edited on
char PlayAgain = 'Y';

should be

bool PlayAgain = true;

Did you see what I did by changing the while to

if (num < 1 || num > 10 || cin.fail())


Pages: 1234567