Even and Odd numbers

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #include <iostream>
using namespace std;

int main ()
{
    int mark[4];

    for(int i=0; i<4; i++)
    {
        if(mark[i] % 2 == 1)
        {
            cout<<"Please enter even numbers!"<<endl;
        }

        else
        {
            cout<<"Enter mark: ";
            cin>>mark[i];
        }
    }
    return 0;
}
what you actualy want to do?? do you want to store even numbers in array only??
then here is the solution...


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  #include <iostream>
using namespace std;

int main ()
{
    int mark[4];

    for(int i=0; i<4;)
    {
        
        
            cout<<"Enter mark: ";
            cin>>mark[i];
        if(mark[i] % 2 != 1)
        {
            
            i++;
        }
        else
        {
            cout<<"Please enter even numbers!"<<endl;   
        }
        
    }
    return 0;
}
Another solution would be something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#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(int const &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 

Thanks bro you gave me a new way to think .....
realy grateful to you........
Topic archived. No new replies allowed.