COUNT ODDS AND EVENS

I'm currently doing a course on edx Intro to C++ and need to take 4 integers from a user and then depending on the amount of odds or even numbers say "more odds, more evens even number of odds and evens...So far in this course (I'm on Week 5) we haven't done inputs more than 2 from the user and since its asking for a specific amount and any input could be odds or evens I'm unsure how to go about it. I guess without actually typing line by line on what to do, could you tell me specific things I should read up on? if else statement seems the right way to go and maybe arrays? Any help is appreciated, thanks.

Hello poptarts,

I would start with brushing up on io, more the i part, followed by if/else and for loops. A good tutorial and reference is https://www.learncpp.com/

I would then suggest using pencil and paper to plan the program then program your plan.

When you do start writing the program work with a little bit at a time or in small steps. Compile and test often.

If nothing else work up a plan and pose it. You may get some suggestions that you have not thought of or a different approach.

Or wait long enough and someone will write the program for you and you will not have to do any work.

Andy
do you need to echo the numbers passed into the program back, as in 'you had more odds, they are 3,7, and 13' or you just need to say 'moar odds and stuff' ?
if you don't need to echo the numbers, you don't need to store them, you can read the same variable over and over:
cin x;
if x is odd, odds++
else evens++
cin x... //repeat the code, or if you know of loops, do a small loop here

if you DO need to echo the values back, then having an array is a good choice.

what you described (which may not contain all the requirements) can be done in about 5 lines (heavily condensed) with a for loop and 3 integers. It could be 10 or so lines with comments and all.

1
2
3
4
5
6
7
8
9
10
11
12
13
unsigned int odds = 0, x;
for(int i = 0; i < 4; i++)
{
 cout <<"enter a number\n";
 cin >> x;
 odds += x&1; //cuteness.  evens add zero. odds add 1.
//this is 'bitwise' and, so each bit of 1 (000000000001) and the other number (x...x0) or(x...x1)
//are 'anded' so the 1's leading zeros kills the high order bits of the input and the input's final 
//low order bit determines the result. 
//this is the same result as the more explict
//if(x%2==1)
//  odds++;
}

from here you know you have 4, and you know # of odds,
so evens is just 4-odds (but you don't need to know that).
but you can work off odds alone, odds can be 0, 1, 2, 3, 4 so logic like
if odds> 2 there are more odds than evens, ... and pick your conditions from there to do the output. you don't even need to count or store or know anything about the evens.

Hopefully this shows you how to think through a logic problem, to unravel the extras (the temptation to count even values, for example) that you don't need from what you DO need, and work through it. The more important thing here is how to think through it and work throug it, not the code itself.
Last edited on
Hey Jonnin, I do not need to echo anything back we haven't gotten to echoes yet. It's just I've never had 4 inputs, I need 4 variables right? but you said I don't need to store them all, so what you're saying is I can define x and have the 4 inputs as x? and the program will keep track of that?

int numOne

cin >> numOne; //this will store all 4 inputs by the user if separated by spaces?

I've seen those ++ and & signs so I'll continue rereading that. I just thought when ever a user needed to input data that you HAD to have a variable for each input.

After rereading your comment 5 times I finally get it now I just need to learn how to put it all together thank you very much.
you are welcome, hopefully it helps.

as to your questions... ask if you are still confused. This stuff takes a little time to make sense when you first see it, but once you do see it, it can't be unseen and you will have made good progress on what this exercise teaches.


I've seen those ++ and & signs so I'll continue rereading that. I just thought when ever a user needed to input data that you HAD to have a variable for each input.

++ means add one to me.
int x = 42;
x++; //x is now 43.
its just a shorthand for x = x+1. -- works too: x = 42; x--; x is now 41.

there are two types of logic, boolean and bitwise. There are multiple uses of the & symbol. You will learn each in time. For now if you do not understand what I am saying you can use x%2 instead. % is the remainder. when you divide by 2, the remainder is 1 or zero, think back to second grade math and long division here. it turns out that odd values divided by two always have a 1 remainder. so if x%2==1 then it is odd, or you can add this up as I did with the &: odds += x%2 will add zero for even values of x (so odd count does not change) and add 1 for odd values. Its the same thing.

there are any number of cool math tricks that have nothing to do with code. remainders are useful in coding, in many ways. You will see the % again, so try to remember it.
Last edited on
yes, it works. Use code tags and you can run it from here, and it looks better. <> button on the editor.

are you unable to test it yourself? That would make things... very difficult.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int main()
{
	const char* const output[] {"More odd than even", "Equal number even and odd", "More even than odd"};

	int cnt[2] {};

	std::cout << "Enter positive numbers (non-number to terminate): ";

	for (int i {}; std::cin >> i; ++cnt[i % 2]);

	std::cout << cnt[0] << " even\n";
	std::cout << cnt[1] << " odd\n";
	std::cout << output[(cnt[0] >= cnt[1]) + (cnt[0] > cnt[1])] << '\n';
}

Hey jonnin, I had to drop out of that course, apparently I was already suppose to have prior experience with another language (python) so can you put on the full code that allows you to enter 4 numbers separated by spaces and spits out either "more evens", "more odds", "same amount of odds and evens" so I can see exact what this code looks like?

in my head it makes sense "x" will be the variable that all 4 numbers will go in once that gets passed down to an if statement that %2 that will determine if its an odd number and if the remainder =1 you set it to "odd" variable. Once that happens you have multiple if else saying more odd, more even...else same amount? I just cant see it.

nvm seeplus did but the non number to terminate can't be there. That also looks like the switch statements.

Yeah I'm going to take Andy's advice and start with that tutorial he recommended. But I really do appreciate all the help.
Hello poptarts,

To be more inline with what you 1st posted:
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
36
37
38
39
40
41
42
#include <iostream>
#include <limits>

int main()
{
    constexpr int MAXNUMS{ 4 };  // <--- Can be changed if you want more than 4 inputs.

    int inputNumber{}, oddNumberCount{};  // <--- ALWAYS initialize your variables.

    std::cout << '\n';

    for (int lc = 0; lc < MAXNUMS; lc++)
    {
        std::cout << " Enter #" << lc + 1 << " of " << MAXNUMS << ": ";
        std::cin >> inputNumber;

        //oddNumberCount += inputNumber & 1;

        //oddNumberCount += inputNumber % 2;

        if (inputNumber % 2)
        {
            oddNumberCount++;
        }
    }

    if (oddNumberCount == MAXNUMS / 2)
    {
        std::cout << "\n There are the same amount of even numbers as odd numbers. And that is: " << oddNumberCount << '\n';
    }
    else if (oddNumberCount > MAXNUMS / 2)
    {
        std::cout << "\n There are more odd numbers. And that is " << oddNumberCount << '\n';
    }
    else
    {
        std::cout << "\n There are more even numbers. And that is " << MAXNUMS - oddNumberCount << '\n';
    }

	return 0;  // <--- Not required, but makes a good break point.
}


Andy
This is what I had in mind, shamelessly stealing from seeplus a bit (his is very clever, by the way, reusing the loop variable as the data variable is neat).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>

int main()
{
 const std::string output[] {"More even than odd", "More even than odd", "Equal number of even and odd", 
 "More odd than even", "More odd than even"};
//5 possible scenarios, 0,1,2,3,4 of them are odd.  correct response for each of those. 
 unsigned int cnt{};
 unsigned int x{};
 std::cout << "Enter 4 positive numbers\n";	
     for (int i {}; i<4; i++) //this just gets 4 and stops, no need to interact to stop. 
	{	 
	 std:: cin >> x;  //one variable, holds all 4 values one by one in the loop
	 cnt += x&1; //add 0 for evens add 1 for odds. 
	}	
 std::cout << output[cnt] << std::endl; //print the correct info for the value of cnt. 
//optional: cout # of odds (cnt) and number of evens (4-cnt)
}


the use of arrays of text to control output is a very useful technique. If you continue in programming, remember this idea.

switch statements are like a block of if/else statements with some extras:
- they only work on integers. most data can be turned into an integer of sorts to make the switch work, easily, though: a small (if any) performance hit for a possible net gain.
- the compiler tries hard to make them lookup tables, which is more efficient than branched logic.
- they can fall-through, that is, you can have the code for 3 do something special for 3 and then execute the code for 4. Its like saying if value==3 do something followed by code you always do. Exploiting fall-through and the lookup table compiler approach, you can get extremely efficient logic blocks from switches.

quick example pseudocode:
switch(value)
case: 3
cout "its 3" //no break here, 3's code will proceed into 4's code
case: 4
cout "it could be 3 or 4"
break; //ends fall through. 4 will not proceed into the 5's code.
case: 5
cout "it can't be 3 or 4 here, its 5"
default: cout "its something else" //you always want a default in case you get an unexpected value.

if you enter 3, you get "its 3" AND "it could be 3 or 4" printed.
if you enter 4, you get "it could be 3 or 4" printed.
if you enter 5, you get "etc its 5"
Last edited on
Topic archived. No new replies allowed.