Hi guys, I have just written 2 versions of this simple program:
#include <iostream>
using std::cin;
using std::cout;
int main ()
{
cout << "This program counts from 10 to 0. \nGuess the missing number.\n";
int n;
int f;
for (n=10; n>0; n--)
{
if (n==5) continue;
cout << n << ", ";
}
cout << "So, type the missing number here: ";
cin >>f;
if (f==5)
cout << "Well done!\a\a\a";
while (f!=5)
{
cout << "Wrong answer, try again!\nEnter the number here: ";
cin >> f;
}
return 0;
}
I compiled it and executed it but it doesn' work properly: if I guess the number on the first attempt, all good, but, say that at the first attempt I try with 4 (and the program will obviously say tht that's wrong asking me to try again) and then I type 5, the program terminates, without showing me "Well done" and ringing the system alarm three times.
Now in the second version I changed the order of the if statement and the while loop so that line 17 and 18 come after the while loop:
#include <iostream>
using std::cin;
using std::cout;
int main ()
{
cout << "This program counts from 10 to 0. \nGuess the missing number.\n";
int n;
int f;
for (n=10; n>0; n--)
{
if (n==5) continue;
cout << n << ", ";
}
cout << "So, type the missing number here: ";
cin >>f;
while (f!=5)
{
cout << "Wrong answer, try again!\nEnter the number here: ";
cin >> f;
}
if (f==5)
cout << "Well done!\a\a\a";
return 0;
}
Now, this one here works fine. What I would like you guys to help me with, is to understand why.
thanks