Adding only even numbers in C

Risc91

Junior Member
Mar 11, 2000
21
0
0
I have to write this program in for one of my classes and part of it has to take in two odd numbers and add the even numbers in between. I'm having trouble writing the loop to only add the even numbers. It always adds them all. Can anyone help?
 

CSoup

Senior member
Jan 9, 2002
565
0
0
Do you mean if you have a list:
1
2
3
4
5

you want as the output

6
12

?

or is this what you want?

user enters 1 and 5
answer is 6 (2+4)


I'll assume you want the second thing. You can either code it based on the fact that the numbers entered are odd or not.

a = 1;
b = 5;
num = 0;
for(i = a + 1; i < b; i +=2){
num += i;
}
 

Risc91

Junior Member
Mar 11, 2000
21
0
0
yes the last one..... If a user enters 1 and 5 it will add all the even numbers in between, 2+4 and output its sum, which would be 6 in this case.
 

CSoup

Senior member
Jan 9, 2002
565
0
0
The code I show above assume that the contract of the two numbers entered being odd are satisfied.