input to determine even and odd numbers

Hello all, I am new to c++ and I am currently taking a class, but my teacher doesn't really teach anything which is why I am soliciting help. My current problem is that I'm not sure sure how to go about to solve my problem.



The problem: Ask user to input a positive integer then the output should show the odds and even numbers from the number entered

Example, if the user inputs the number '1426' then my codes output should show the even numbers from the number entered.
2,4,6

It should also show the odd numbers as well. Example, if user inputs '134' then it should show.... 1,3 in the output.



Any help or tips would be very appreciative. Like i said, I'm only a month into my c++ class, so any help would be great.
Here is a way to do this:
You should get digit one at a time and check with modulo operator:
if(digit%2==0) then the digit is even and you can store it in array which will hold all even digits, else the digit is odd and you can store it in another array which will hold odd digits.

Here is code, it can be improved in many ways, just for idea:
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
35
#include <iostream>

const unsigned int SIZE=30;

int main()
{
	unsigned int number, evenDigits[SIZE], oddDigits[SIZE], evenIndex=0, oddIndex=0;
	std::cout<<"Enter number: ";
	std::cin>>number;
	unsigned int temp=number;
	while(temp!=0)
	{
		unsigned int digit=temp%10;
		if(digit%2==0)
		{
			evenDigits[evenIndex]=digit;
			evenIndex++;
		}
		else
		{
			oddDigits[oddIndex]=digit;
			oddIndex++;
		}
		
		temp/=10;
	}
	std::cout<<"Even digits: ";
	for(int i=evenIndex-1; i>=0; i--)
		std::cout<<evenDigits[i]<<" ";
	std::cout<<std::endl;
	std::cout<<"Odd digits: ";
	for(int i=oddIndex-1; i>=0; i--)
		std::cout<<oddDigits[i]<<" ";
	return 0;
}
Last edited on
Thanks for the response. I am having a bit of trouble following along since we haven't covered arrays yet. Is there any way i could strip down and make it more accessible so that i could modify it?
Here is bokisof's program slightly modified to print only the even digits, without using an array:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

int main()
{
        unsigned int number;
        std::cout<<"Enter number: ";
        std::cin>>number;
        unsigned int temp=number;

        std::cout << "Even digits:";
        while(temp!=0)
        {
                unsigned int digit=temp%10;
                if(digit%2==0)
                {
                    std::cout << ' '<< digit;
                }
                temp/=10;
        }
        std::cout << '\n';
        return 0;
}

If you want to print the odd numbers also, you could add code to set temp = number again and execute another loop that prints the odd digits instead of the even ones.

Topic archived. No new replies allowed.