while loops Modify the program you wrote for the previous exercise so that it ke
ID: 3879511 • Letter: W
Question
while loops
Modify the program you wrote for the previous exercise so that it keeps reading positive integers and classifying them as ODD or EVEN until the user inputs -1. No classification should be produced for the -1.
everything looks good but i cant get it to keep outputting
MY CODE SO FAR
#include<iostream>
using namespace std;
int main()
{
while (true)
{
int number, remainder;
cin >> number;
remainder = number % 2;
if (number == -1)
break;
if (remainder == 0)
cout << "Even " << endl;
else
cout<< "ODD " << endl;
return 0;
}
}
Explanation / Answer
Remove the return statement from the while loop and keep it outside the while loop.
Return statement makes the control exit or switch from the executing function, here in this case the main function (i.e is the driver function) which will cause stoppage of execution of the complete program.
Modified Code :
#include<iostream>
using namespace std;
int main() {
while (true) {
int number, remainder;
cin >> number;
remainder = number % 2;
if (number == -1)
break;
if (remainder == 0)
cout << "Even " << endl;
else
cout<< "ODD " << endl;
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.