C++ Exercise

Hello Everybody!

I just recently joined the community. First, I want to start off by saying that I L O V E C++.

Now, I am facing this exercise:

Write a program that continues to ask the user to enter any number other than 5 until the user enters the number 5.
Then tell the user "Hey! you weren't supposed to enter 5!" and exit the program.

This is how I've done it:

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

int main() {
    int x;
    while (x < 4000) {
        cout << "\nEnter any number other than 5: ";
        cin >> x;
    if (x == 5) {
        cout << "Hey! You're not supposed to enter 5!";
    }
    }
    return 0;
}


Then, the exercise continues like this:

★ Modify the program so that after 10 iterations if the user still hasn't entered 5 will tell the user "Wow, you're more patient then I am, you win." and exit.

How do I go about doing this? I really don't know :(
I would appreciate very much detailed answers, not just code, because I'd like to understand the logic behind the code.

Thanks guys!

Last edited on
Welcome!

Right now, your program is invalid, actually. You attempt to use x before initializing it, presumably to 0. C++ requires all variables be properly initialized (if read before being written to), otherwise it's "undefined behavior" (most likely junk values, crashes, etc.)

First, initialize your x to be 0:
int x = 0;

Then, you can change the 4000 to be a 10.
[You can also use a for loop, see: http://www.cplusplus.com/doc/tutorial/control/ loops section]

Inside the if (x == 5) block, add a return 1; (the actual value doesn't matter). This will exit the program, like the prompt tells you to do.

After the while loop, print the "wow, you're more patient..." text.

_____________________________________

Also, pay attention to proper indenting of your code. Your if block (lines 9-11) is within your while block (lines 6-12), so you should indent lines 9-11 one more level over.
Last edited on
Hi Ganado,

First, what does initialize mean? I know the word, but idk what's the purpose of it in C++. Even though I didn't equal x to 0, the program still worked. And, if I equal it to 0, how will the user be able to input a number? Also, initializing a any variable in C++ is the first thing I need to do? Any, x, z , y, k, all to =0? Also, return=1 means "exit the program"?

I did not learn that in my C++ tutorial... I am using w3schools to learn.

Thanks for you message.

I've tried following your advice, and I got this:

#include <iostream>
using namespace std;

int main() {
int x = 0;
while (x < 10) {
cout << "\nEnter any number other than 5: ";
cin >> x;
if (x == 5) {
cout << "Hey! You're not supposed to enter 5!";
}
}
return 0;
}

I still couldn't make it work. If I added the 'return=1' in the 'if' block, the compiler would give me an error...

How would you write the code?

Thanks for your help!


First, what does initialize mean?
It just means to give a variable an initial (starting) value. You must give it a value before you try to compare it (x < 4000).

Even though I didn't equal x to 0, the program still worked.
This is just a coincidence, and shouldn't be relied on. Welcome to C++. Always give a variable a value before comparing it or reading its value. Also, turn on compiler warnings (-Wall on g++, /w4 or /Wall in Visual Studio)

Anyway, I slightly misread your post. You actually want one variable to keep track of as counter variable (for your loop), and another variable to keep track of the value the user inputs.

This can be condensed using a for loop that loops 10 times:

1
2
3
4
5
6
7
8
9
10
for (int i = 0; i < 10; i++) {
    int x;
    cin >> x;
    if (x == 5) {
        cout << "Hey!";
        return 1;
    }
}
cout << "Patient!";
return 0;

Last edited on
Hi Guys,

I've done it! I've done it, let me know if my code is 'good'..

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

int main() {
    int x = 0;
    int k = 1;
    while (k < 11)
    {
        cout << "\nEnter any number other than " << x << ": ";
        cin >> x;
        
        if (x == 5)
        {
            cout << "Hey! You weren't supposed to enter 5!";
        }
        else if (k == 10)
        {
            cout << "Wow, you're more patient than I am, you win";
        }
        k++;
    }
    return 0;
    }
Almost good. The prompt says you should end the program if the user enters 5. You can do this by adding another return 0; after line 14, or by using break; to break out of the loop.
Last edited on
Hey Ganado!

Thanks for your help. I now know that I have to give each variable a value. I will now try your code and try to understand it.

Cheers!
Last edited on
Also, notice what your prompt says when your program starts
Enter any number other than 0

Is that correct?

Since the "magic number" is always 5, you give it a name like this:
1
2
3
4
5
6
7
8
9
10
const int bad_number = 5;

// ...

cout << "\nEnter any number other than " << bad_number << ": ";

if (x == bad_number)
{
    // ...Hey!
}
Last edited on
Hi there Ganado,

I still can't run your code :(
I only posted an excerpt, not complete code. Don't worry that post, just focus on what I said in : http://www.cplusplus.com/forum/beginner/259722/#msg1129029 and
http://www.cplusplus.com/forum/beginner/259722/#msg1129031
Last edited on
Oh okay, sorry for the confusion created, I didn't refresh the page as I was preparing to write my answer and you had already sent me another reply.

I have modified my code like this now, take a look:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int main() {
    int x = 0;
    int k = 1;
    while (k < 11)
    {
        cout << "\nEnter any number other than 5 and the one you entered, which is " << x << ": ";
        cin >> x;
        
        if (x == 5)
        {
            cout << "Hey! You weren't supposed to enter 5!";
return 0;
        }
        else if (k == 10)
        {
            cout << "Wow, you're more patient than I am, you win";
        }
        k++;
    }
    return 0;
    }


Does it look better now? I am now learning about your 'const int bad_number = 5;', I want to try to understand it and write the same exercise using it.
Last edited on
I get it now, so whenever I write 'return=x' I am telling the program to end. :) Perfect.
On line 9, why are you printing x? I thought the only restriction was that they can't enter 5?
e.g. cout << "\nEnter any number other than 5: ";

You also still aren't exiting the program if the user enters 5.
Edit: Now you are, good.
Last edited on
Hi Ganado,

I tried the same exercise using loops, as you suggested. I have something like this:

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

int main() {
    for (int i = 0; 0 < 11; i++) {
    int x;
    cout << "\nEnter a number other than 5: ";
    cin >> x;
    if (x == 5) {
        cout << "Hey! You aren't supposed to enter that number!";
        return 0;
    }
    else if (i == 9) {
        cout << "You win";
        return 0;
    }
    }
    
    return 0;
}


Regarding your question, "On line 9, why are you printing x?". This is the full exercise:

Write a program that ccontinues to asks the user to enter any number other than 5 until the user enters the number 5.
Then tell the user "Hey! you weren't supposed to enter 5!" and exit the program.

★ Modify the program so that after 10 iterations if the user still hasn't entered 5 will tell the user "Wow, you're more patient then I am, you win." and exit.

★★ Modify the program so that it asks the user to enter any number other than the number equal to the number of times they've been asked to enter a number. (i.e on the first iteration "Please enter any number other than 0" and on the second iteration "Please enter any number other than 1"m etc. etc. The program must behave accordingly exiting when the user enters the number they were asked not to.)

On line 9, I was doing the 2 stars part of the exercise.

PS. Still looking into const int bad_number...
I get it now, so whenever I write 'return=x' I am telling the program to end. :) Perfect.

return 0 specifically ends MAIN and ONLY main.
Later, you will have code in other functions, and that (a return statement, the value (or lack of one) provided will not always be zero in other functions) causes the FUNCTION YOU ARE IN to end, not the PROGRAM. This is critical to understand.

Return of a non-zero from main tells your OS that your program failed to execute properly. zero is the correct value to just end main. There are other 'kill the program NOW' keywords that can be used for critical failures / aborts, but you generally want to make your code exit by getting back into main and ending there (via a return statement or hitting the end of the function).

what return does, is say "stop here and hand this result back to who called you". In main, the caller is the operating system, and the value expected is an error code, and the code 0 means "all was well".

lets take another look at the idea, with a simple function now, to see how return works.


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>

int func(int i) 
{
    if (i == 5) 
    {
        return 1;  //stops function, not program, here if true
    }
   return 0;  //implied else, stops this function, but not the program, see?
}

using namespace std;

int main() 
{
    for (int i = 0; 0 < 11; i++) 
  {
    int x;
    cout << "\nEnter a number other than 5: ";
    cin >> x;
    if( func(x) == 1) //compare the value returned from func to 1 
              cout  << "Hey! You aren't supposed to enter that number!";

    if (i == 9) 
     {
        cout << "You win";
        return 0;
      }   
    
    return 0;
  }
}
Last edited on
Topic archived. No new replies allowed.