while(user == gullible) The goal for this project was to:


  Write a program that continues 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.
  
  Requires:
  
  
  variables, data types, and numerical operators
  basic input/output
  logic (if statements, switch statements)
  loops (for, while, do-while)
  


(I'm not doing the 2 stars one yet)

My questions are:


How can I optimize my code in every possible way? (efficiency, readability, etc)
How can I improve the code syntax?




#include &lt;iostream&gt;  
using std::cout;
using std::cin; 

int main()
{

    int UserNumber = 0;
    int k = 1;
    while (k &lt; 11)
    {
        cout &lt;&lt; "\nEnter any number other than 5: ";
        cin &gt;&gt; UserNumber;

        if (UserNumber == 5)
        {
            cout &lt;&lt; "\n\n\nHey! You weren't supposed to enter 5!\n\n\n";
            exit(0);
        }

        else if (k == 10)
        {
            cout &lt;&lt; "Wow, you're more patient then I am, you win.\n\n\n";
            exit(0);
        }
        k++;
    }

}
A simple rule I (and other) try to apply is : define things in the smallest possible scope.

For instance, int UserNumber = 0; can be moved inside the loop.

Similarly, k can be moved once you've made your loop a for loop : for(int k = 1; k &lt; 11; k++).

Then, computer people love counting from 0. If you write : for(int k = 0; k &lt; 10; k++), I am used to this and I know straight-away that there will be 10 iterations. If you re-index your loop, you'll need to convert else if (k == 10) into a else if (k == 9).

Then, you'll realise that there is no need for this check, you can just move this out of the loop.