When user input odd numbers it will count. How to make sure it does not count? User need to input 5 even numbers.
Enter mark: 27
Please enter even numbers!
Enter mark: 26
Enter mark: 32
Enter mark: 77
Please enter even numbers!
Enter mark: 54
Enter mark: 66
Enter mark: 42
Median number is: 42
#include <iostream>
int main()
{
std::size_t const requiredEvens = 4u; //unsigned integer
int even[requiredEvens] = {0}; //array for the even numbers
std::size_t evens = 0u; //how many evens have currently been added
int input = 0; //variable used to read into
while(evens < requiredEvens) //loop while we need to get more even numbers
{
std::cout << "Please enter an even number: ";
std::cin >> input;
if(input & 1) //checks if last bit is set (1 bit), same as input % 2 == 1
{
std::cout << "You entered an odd number." << std::endl;
}
else
{
even[evens++] = input; //assign to the array then increment the counter
}
}
std::cout << "The inputted even numbers are: ";
for(intconst &element : even)
{
std::cout << element << ' ';
}
std::cout << std::endl;
return 0;
}
Please enter an even number: 1
You entered an odd number.
Please enter an even number: 2
Please enter an even number: 3
You entered an odd number.
Please enter an even number: 4
Please enter an even number: 5
You entered an odd number.
Please enter an even number: 6
Please enter an even number: 7
You entered an odd number.
Please enter an even number: 8
The inputted even numbers are: 2 4 6 8