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"