I have written a C++ program to let the users entering positive numbers using a do while
loop. Notwithstanding, when I try to convert the do while
loop into a while
loop, the expected output is not the same as do while loop. The code is as below:
#include <iostream>
using namespace std;
int main()
{
int n;
do
{
cout << "Enter a non-negative integer: ";
cin >> n;
if (n < 0)
{
cout << "The integer you entered is negative. " << endl;
}
}
while (n < 0);
return 0;
}
The terminal requires the user to reenter the number until it is positive for the above code that I have written. However, I try to convert the do while
loop to while
loop as shown below, there is no output at all.
May I know which part I have written wrongly? Thank you.
#include <iostream>
using namespace std;
int main()
{
int n;
while (n < 0)
{
cout << "Enter a non-negative integer: ";
cin >> n;
if (n < 0){
cout << "The integer you entered is negative. " << endl;
}
}
return 0;
}