functions

I want to write a function which will sum up odd numbers between N and M (int). N and M are parameters of function. anyone here to help?
thanks in advance.

( in C++ | I'm using Microsoft Visual Studio 2010)
Last edited on
First you need to check the parity of N and M to determine which odd number to start and end.
Then you can do the calculation either by Sum of Arithmetic Sequence Equation, or continuously adding in a loop.
well, I didn't get what you said.
there I meant that - let's say I've entered from keyboard ---- N=10 and M=15. so I want function to sum up numbers, which are odd between(also equal to N and M) 10 and 15. 10<x<15 . so they are 11 + 13 + 15 ..
so program should show me 39.

I couldn't write a body of that function, couldn't think a way
Hello,

this should solve your problem:

This is the one if you want for function to add M and N in sum:
1
2
3
4
5
6
7
8
9
10
11
12
13
int sum(int N, int M){


     int difference, sum=0, k=0;
     difference = M-N+1;
     for (int i=0; i<difference; i++){
          k=N+i;
          if(k%2!=0)
               sum+=k; 
     }
     
     return sum;
}



And this is one that sums odd numbers without N and M:

1
2
3
4
5
6
7
8
9
10
11
12
13
int sum(int N, int M){


     int difference, sum=0, k=0;
     difference = M-N;
     for (int i=1; i<difference; i++){
          k=N+i;
          if(k%2!=0) 
               sum+=k;
     }
     
     return sum;
}


In case you want to sum even numbers, just replace if(k%2!=0) with if(k%2==0). :-)

Thank you for reading!

S.
Thanks !!!
Well, what I told you is pretty much the pseudocode.
Since it's a rather simple 2-step function, I don't know what to tell you further without solving the problem for you.
Topic archived. No new replies allowed.