i have no clue on how to create this program

I am suppose to write a program that uses one variable int n and asks the user to input an even number. If the user types in a even #, the program prints the #. if the users enters an odd #, the user is asked to enter the even # again. Then the code prints whether the # is even or odd.


How do i do this??? please help thank you.
Last edited on
The modulus function (%) comes in handy in this case. Remember- the modulus function divides and outputs the remainder. What number evenly divides into all even numbers, but no odd numbers?
Two.

so im writing the code right now

#include <iostream>
using namespace std;

int main() {

int n;
cout << "Input an even number";
cin >> n;

if ( n % 2 == 0 )
cout << n << "is even";
else if ( n % 2 !=0 )
cout << n << "is odd";

Not sure what to do for "If the user types in a even #, the program prints the #. if the users enters an odd #, the user is asked to enter the even # again."
Well, do you know what a while loop is?
yeah but im just not sure how to write the code and where to place it.
Last edited on
I have an example @boy3005

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//EnterEven.cpp
//This program need an even number. -mandatory

#include <iostream>
using std::cout;
using std::cin;
using std::endl;

int main(){

bool keepLooping=true;

while(keepLooping){ //while keepLooping is true
cout<<"Enter a number: ";
int number;
cin>>number;
if(number%2==0)
	keepLooping=false;

}//end while


return 0; //indicates success
}//end main 



Enter a number: 1
Enter a number: 1
Enter a number: 3
Enter a number: 5
Enter a number: 4
#include <iostream>
using namespace std;

int main() {

bool keepLooping=true;

int n;
while (keepLooping) {
cout << " Input an even number.";
cin >> n;
if ( n % 2 ==0 )
cout << n << " " << endl;
if ( n % 2 ==0 )
keepLooping=false;
if ( n % 2 ==0 )
cout << n << " is even." << endl;
}


return 0;
}

dunno if this is right?
Yes its right! but have redundant steps

1.-
if ( n % 2 ==0 )
cout << n << " " << endl;

You dont have to check if n%2 is equal to 0 again
to assign false to keepLooping variable,
and after that check again if n%2==0 to print
cout << n << " is even." << endl;

you can do this:
1
2
3
4
if ( n % 2 ==0 ){
cout << n << " is even" << endl;
keepLooping=false;
}

i dont include
else
cout << n << "is odd";

right?
Depends what you expect from your program behavior

if the users enters an odd #, the user is asked to enter the even # again. Then the code prints whether the # is even or odd.


i have my doubts.
Topic archived. No new replies allowed.