How can I add a while loop to this code, so it can continue then adding some code to make it stop when I command it to?
#include <iostream>
using namespace std;
int main()
{
int a,b;
cout<<"Enter first number: ";
cin >> a;
cout<<endl<<"Enter second number: ";
cin >> b;
if(a>b)
cout<<"The first number is greater than the second number"<<endl;
else if (a<b)
cout<<"The first number is not greater than the second number"<<endl;
else if (a==b)
cout<<"Both numbers are equal"<<endl;
One last thing: When using the break statement to stop a loop, it can't be inside a case label (in a switch), because it will just break the switch. In this situations you need to instead use if/elses, or use conditions for the loop.
{
int a,b;
cout<<"Enter first number: ";
cin >> a;
cout<<endl<<"Enter second number: ";
cin >> b;
if(a>b)
cout<<"The first number is greater than the second number"<<endl;
else if (a<b)
cout<<"The first number is not greater than the second number"<<endl;
else if (a==b)
cout<<"Both numbers are equal";
cout << "\n Do you want to exit? (Y/N)\n";
cin >> Answer;
}
#include <iostream>
usingnamespace std;
int main() {
char Answer = 'y';
while (Answer == 'y' || Answer == 'Y') {
int a,b;
cout<<"Enter first number: ";
cin >> a;
cout<<endl<<"Enter second number: ";
cin >> b;
if(a>b)
cout<<"The first number is greater than the second number"<<endl;
elseif (a<b)
cout<<"The first number is not greater than the second number"<<endl;
elseif (a==b)
cout<<"Both numbers are equal";
cout << "\n Do you want to go again? (Y/N)\n";
cin >> Answer;
}
return 0;
}
You'll also have to assign the value 'y' or 'Y' to Answer.