Q)Write a C++ program that takes a positive integer from user and store it in variable
posNumber. Follow these conditions;
If the number is less than 1, print wrong input.
If it is 1, Print its value.
If value is greate than 1, check the value is it Even or Odd.
If it is Even, half it and print.
If it is Odd, multiply it by 3 and print result.
Repeat the whole process until user enter 1.(use while loop for repetation of this whole process)
The problem in this code is that whenever i enter the even odd loop it runs infinite loop of the answer what should i modify in this program so that after the answer of even or odd is printed the program then loops back to "ENTER A POSITIVE INTEGER" until i press 1. Thanks
#include<iostream>
usingnamespace std;
int main()
{
la:cout <<"ENTER A POSITIVE INTEGER:";
int posNumber=0;
cin >> posNumber;
while(posNumber!=1)
{ //this part runs even if the while part is false
if(posNumber<1)
{
cout <<"WRONG INPUT"<<endl;
goto la;
}
elseif(posNumber==1)
{
cout <<"Value is" <<posNumber;
}
elseif(posNumber>1)
{
if((posNumber%2)==0)
{
posNumber/=2;
cout << "value is "<<posNumber;
//If it is Even, half it and print.
//If it is Odd, multiply it by 3 and print result.
}
else
{
posNumber*=3;
cout << "value is "<<posNumber;
}
}
}
cout <<"\nTHANK YOU";
return 0;
}
#include<iostream>
usingnamespace std;
int main()
{
int posNumber=0;
while(posNumber!=1)
{
cout <<"ENTER A POSITIVE INTEGER:";
cin >> posNumber;//this part runs even if the while part is false
if(posNumber<1)
{
cout <<"WRONG INPUT"<<endl;
}
elseif(posNumber==1)
{
cout <<"Value is " <<posNumber<<endl;;
}
elseif(posNumber>1)
{
{
if((posNumber%2)==0)
{
posNumber/=2;
cout << "value is "<<posNumber<<endl;
//If it is Even, half it and print.
//If it is Odd, multiply it by 3 and print result.
}
else
{
posNumber*=3;
cout << "value is "<<posNumber<<endl;
}
}
}
}
cout <<"\nTHANK YOU";
return 0;
}
changed it and now when i enter 8 it shows value is 4 value is 2 value is 1 thank you and exits the loop where the output should be value is 4 and prompt for a positive integer