Guys I need help. can you help me determine what are the things that i'll used to run my program like this:

Enter 5 numbers but refuse to display if the value is an odd number. Display only even numbers and the sum of all even number.

I'm not asking for the whole thing but the idea only. Hoping for your kindness. thanks

But ...

do not really need to use an array, if it's ok to process and display the even numbers as they are entered :)

@ddanbe ... we both seem to be stuck on the night shift +1 :)

Edited 1 Year Ago by David W

You can check for even numbers using the % operator on an int:

int even = 2, odd = 5;
std::cout << "even: " << even % 2 << " odd: " << odd % 2 << std::endl;

any even number will return 0 when you do % 2 to it, while odd numbers will return 1. You can use this in an if statement to do things with only one of the kinds (even or odd) of number.

@ravenous: this also works with even & 1 This will also return 0 if even is even, 1 if even is odd.

@ddanbe: very true :)

Do you know if that's more efficient? I suspect it is; unless there's some cunning way of implementing mod, or something like that...

I would think and decent compiler would make even % 2 and even & 1 the same operation. My rule of thumb is write clear and legible code. This will help with maintainability and will generally allow the optimizer to take care of most optimizations that can been done. mike_2000_17 wrote a very nice guide showing how you can really get a nice performance increase in your code without using any sort of micro optimizations.

This article has been dead for over six months. Start a new discussion instead.