Exercise 1. Write a program that uses one variable int n and asks the user to input an even number. If the user enters an even number, the program prints the value entered by the user. If the user enters an odd number, the user is asked again to enter an even number. Then the code should finish by printing the number and whether the number is even or odd.
How do i do this? we only just learned loops such as using i=1, i++, i <= n
int n;
cout << "Enter the even number";
cin >> n;
int i=1;
while ( i <= n )
if ( n % i != 0 )
cout << " Enter the even number. ";
else if ( n % i == 0 )
cout << n << " is even."<<endl;
i++;
return 0;
not sure what im doing...:(
confused on how to do " If the user enters an odd number, the user is asked again to enter an even number. "
ok i changed it
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter the even number";
cin >> n;
if ( n % 2 != 0 )
cout << " Enter the even number. ";
else if ( n % 2 == 0 )
cout << n << " is even."<<endl;
return 0;
}
but how do i keep making it ask the user when the user types in an odd number tho?
Please wrap your code in [code][/code]-tags, it makes it more readable.
You will have to use a loop, loops keep repeating the code within them until a condition is met, whcih could be a condition you would use in an if statement (while-loop) or a counter reaching a certain value.
In this case, you could use a while loop as such:
1 2 3 4
while ( (n%2) > 0) //while n is odd
{
//ask for the number
}
#include <iostream>
usingnamespace std;
int n;
cout << "Enter the even number";
cin >> n;
while( n % 2 > 0 )
cout << " Enter the even number. ";
if ( n % 2 == 0 )
cout << n << " is even."<<endl;
return 0;
}
when i type in 1 it makes a infinite loop. im sorry but im so confused right now