Reputation: 37
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;
}
Upvotes: 2
Views: 891
Reputation: 2412
In the while
version of your code, you do not know what the value of n
is, as it is not initialized before you use it in the while (n<0)
loop.
int main()
{
int n;
// HERE YOU DO NOT KNOW IF n is NEGATIVE OR POSITIVE, YOU EITHER NEED TO INITIALIZE IT OR
// ENTER IT by cin >> 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;
}
You then need to rearrange a little bit to get the same ouput as well as to use the first input of n
which is out of the loop.
For instance, this will provide the same output:
#include <iostream>
using namespace std;
int main()
{
int n=-1;
cout << "Enter a non-negative integer: ";
cin >> n;
while (n < 0)
{
if (n < 0)
{
cout << "The integer you entered is negative. " << endl;
cout << "Enter a non-negative integer: ";
cin >> n;
}
else
{
// if positive you get out of the loop
break;
}
}
return 0;
}
Upvotes: 1
Reputation: 190
You have to take the n before while(n<0) statement:
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter a non-negative integer: ";
cin >> 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;
}
Or you may initialize it with negative number:
#include <iostream>
using namespace std;
int main()
{
int n=-1;
while (n < 0)
{
cout << "Enter a non-negative integer: ";
cin >> n;
if (n < 0)
cout << "The integer you entered is "
<< "negative. " << endl;
}
return 0;
}
Upvotes: 0