0

I am creating a simple code to take integer value 10 times. If at any point, the users enters the value '5', the system should print a message, "You entered 5, you lose". Here is the code

int main()
{
  int num = 0;
  int i;
  for (i = 1; i<= 10; i++)
{
    cout << "Enter a number other than 5\n";
    cin >> num;
    if (num == 5)
    {
        cout << "Hey, you entered 5. You lose!\n";
        break;
    }
}
  cout << "You win!";
  return 0;
}

Now what I dont know is, how do close the program after users enters 5. I am very new to coding so Im really sorry if this question sound stupid. Also, it would be vet nice of you if you could explain in the most easiest way you can. Thank you

Aryan
  • 103
  • 1
  • 1
  • 8
  • 2
    Do you like reading? [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – moooeeeep Sep 04 '16 at 11:27

3 Answers3

1

You could do this:

for (i = 1; i<= 10; i++)
{
    cout << "Enter a number other than 5\n";
    cin >> num;
    if (num == 5)
    {
        cout << "Hey, you entered 5. You lose!\n";
        return 0; // This will end function main and return 0. Thus your program will end.
    }
}

And some more reading.


The way you had it break would simply stop the for loop. This however:

  cout << "You win!";

would still get printed. If you use return, no more statements from main will get executed. Because return will end the function in which it is called, in this case, main.

Community
  • 1
  • 1
Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
  • Thank you. Also, does returning 0 always shuts the program? – Aryan Sep 04 '16 at 11:21
  • @Aryan Depends where you call it, if inside main, yes. If just from some regular function, then this has nothing to do with exiting the program. Return just ends the function inside which it is called – Giorgi Moniava Sep 04 '16 at 11:22
0

Now what I dont know is, how do close the program after users enters 5.

Replace

break;

with

exit(0);

or

return 0;

break will only exit from the loop, and you're printing cout << "You win!"; unconditionally.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
0

The other two approaches mentioned above are undoubtedly the best. But still, if you have some unfinished business that you want to take care of even after the user enters 5 you can take help of a temporary variable say temp.

int main()
{
    int num = 0,tmp=0;
    int i;
    for (i = 1; i<= 10; i++) {
        cout << "Enter a number other than 5\n";
        cin >> num;
        if (num == 5) {
            tmp=1;
            cout << "Hey, you entered 5. You lose!\n";
            break;
        }
        //unfinished work
    }
    //unfinished work
    if(tmp==0)
        cout << "You win!";

    return 0;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190