Home work help

I'd like you guys to look over my code and see if I did anything wrong. I missed my class, so i'm just not sure if I answered the question correctly. I personally think it's totally wrong but idk.

question number 1.
Write a program that reads a set of integers and then finds and prints the sum of the even and odd integers.

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
  #include <iostream>
using namespace std;

const int num = 10;
int main() {
    
    int n = 1;
    
    while (n <= num) {
        if (n % 2 == 0) {
            int sume;
            sume = sume + n;
            n++;
            cout << "The value of your even numbers is : " << sume << endl;
        }
    
        else{
            int sum;
        sum = sum + n;
            n++;
            cout << "The value of your odd number is : "<< sum << endl;
        }
    }
    
    return 0;
1
2
3
4
5
6
7
8
9
10
11
int n, even , odd;
cout << "enter number: ";
while(cin >>n)
{	
if( n == n/2*2 )
	even+=n;
else	
	odd+=n;
cout << "enter another number: ";	
}
cout << "\nsum even = " << even << "\nsum odd =" << odd << endl;	
How does your formula (n== n/2*2) work to find an even number?

if n =2 then 2==2/4 which is 2==1/2?

I haven't learned the even+=n part, could you write the long version of that formula? is it even = even + n?
How does your formula (n== n/2*2) work to find an even number?

if n =2 then 2==2/4 which is 2==1/2?
Arrr. ORDER OF OPERATIONS! Multiplication and division has the same priority and executes left to right.
2/2*21*22.

However using modulo operator is faster and easier n % 2 == 0even

I haven't learned the even+=n part, could you write the long version of that formula? is it even = even + n?
Yes
actually jackelinblack it would 2==2 because 2/2 = 1 multiply by 2 and you get 2. Also even += n is the same thing as even = even +n so you're correct. Remember that order of operation is important.
Last edited on
oh ok thanks. In general how do you know which way is faster?
Two trivial operations against one. It could possibly be optimised by compiler, but it is not guaranteed. Additionally n==n/2*2 is cryptic and requires consulting an n type to determine what it actually does.
from what I can remember, if you have a finite list and you want to reiterate that list over a loop, I would say that using modulus operator is more suitable for that situation than doing x+= y. Sometimes it's not about which is fastest but what is more suitable, convenient and efficient I.E expressing the remainder other than a decimal, having a list and wanting to see how many are left over etc etc. Did I answered your question or no? If not, then I apologize for wasting your time.
Last edited on
lol no but it's ok.
Topic archived. No new replies allowed.