GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 01-Nov-2007, 12:32
avg81 avg81 is offline
New Member
 
Join Date: Nov 2007
Posts: 5
avg81 is on a distinguished road

Sum of the even numbers between n1 and n2


Could someone please help me with this example in a repetition nested control structure from my textbook.

sum of the even numbers between n1 and n2

CPP / C++ / C Code:
int n1, n2, i, sum = 0;
// assign values to n1 and n2
for (i = n1; i <= n2; i++)
if (i % 2 == 0 )
sum = sum + i;
//output sum

say I assign n1=3 and n2=11
ok now i enter the for loop i % 2 never equals 0 so how do the sum of the even numbers between 3 and 11 get added ? Boggeling!
Last edited by admin : 01-Nov-2007 at 16:50. Reason: Please insert your C/C++ example codes between [CPP] and [/CPP] tags
  #2  
Old 01-Nov-2007, 13:37
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,710
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: quick problem


Quote:
Originally Posted by avg81
say I assign n1=3 and n2=11
ok now i enter the for loop i % 2 never equals 0 so how do the sum of the even numbers between 3 and 11 get added ? Boggeling!

Your book should explain how the modulus operator (the '%') works. It gives the remainder after integer division.

The expresson i % 2 is equal to zero if (and only if) the integer i divided by 2 has zero remainder. That's precisely what is needed to identify an even number.

CPP / C++ / C Code:
#include <stdio.h>

int main()
{
    int n1, n2, i;
    int sum = 0;
    n1 = 3;
    n2 = 11;

    for (i = n1; i <= n2; i++) {
        if (i % 2 == 0) {
            printf("Adding %d\n", i);
            sum = sum + i;
        }
    }
    printf("sum = %d\n", sum);
    return 0;
}

Output:
Code:
Adding 4 Adding 6 Adding 8 Adding 10 sum = 28

Regards,

Dave
Last edited by davekw7x : 01-Nov-2007 at 14:12.
  #3  
Old 01-Nov-2007, 14:39
avg81 avg81 is offline
New Member
 
Join Date: Nov 2007
Posts: 5
avg81 is on a distinguished road

Re: quick problem


so are you saying even though (i % 2 != 0) because 3 % 2 = 1

the program would still execute sum = sum + 1; ????

it looks like to me the program shouldnt execute sum = sum + 1 because the if condition is not met in if (i % 2 == 0 )


CPP / C++ / C Code:
for (i = n1; i <= n2; i++)
    if (i % 2 == 0 )
    sum = sum + i;
   //output sum

Last edited by admin : 01-Nov-2007 at 16:52. Reason: Please insert your C/C++ example codes between [CPP] and [/CPP] tags
  #4  
Old 01-Nov-2007, 14:51
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,710
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: quick problem


Quote:
Originally Posted by avg81
so are you saying even though (i % 2 != 0) because 3 % 2 = 1

the program would still execute sum = sum + 1; ????
Yes.
Quote:
Originally Posted by avg81
it looks like to me the program shouldnt execute sum = sum + 1 because the if condition is not met in if (i % 2 == 0 )
The if() statement only applies to the very next statement. If you want it to apply to more than one statement, you put braces {} around the block of statements, as I did in my example. I personally think that that is a good habit to get into: Always use braces {} after the if() stuff, even if you don't need them. In your code, it only needed the next statement and braces were not required.

In your program the only statement that got executed for a true condition is the sum = sum + i. The statements after that always get executed.

Try again. I respectfully suggest that you not just look at the code; compile and execute it.
CPP / C++ / C Code:
#include <stdio.h>

int main()
{
    int n1, n2, i;
    int sum = 0;
    n1 = 3;
    n2 = 11;

    for (i = n1; i <= n2; i++) {
        printf("i = %d\n", i);
        if (i % 2 == 0) {
            printf("  ==> Adding %d\n", i);
            sum = sum + i;
        }
    }
    printf("sum = %d\n", sum);
    return 0;
}

Output:
Code:
i = 3 i = 4 ==> Adding 4 i = 5 i = 6 ==> Adding 6 i = 7 i = 8 ==> Adding 8 i = 9 i = 10 ==> Adding 10 i = 11

If something happens that you don't understand, then make the program tell you what it is seeing. If you still don't get it, then show us exactly what code you are trying and exactly what your output is. (You might also tell us what compiler you are using. Sometimes it makes a difference to people who are trying to help.)

Regards,

Dave
  #5  
Old 01-Nov-2007, 14:58
avg81 avg81 is offline
New Member
 
Join Date: Nov 2007
Posts: 5
avg81 is on a distinguished road

Re: quick problem


thanks for your help. I just joined the forum today and am now loving it!
  #6  
Old 01-Nov-2007, 15:25
davis
 
Posts: n/a

Re: quick problem


Quote:
Originally Posted by avg81
thanks for your help. I just joined the forum today and am now loving it!

Welcome. You'll find that your questions were answered by one of the forums' best resources here on GIDForums. Dave is one of the most helpful people to turn to when you have a problem.

There are quite a few good programmers on this forum who are ready to help, particularly when posters follow the guidelines and ask questions that are reasonably understandable.

You may want to take a moment to review the guidelines and to also consider using [c++] ...your code... [/c++] tags for your code...as Dave did in his response to you. These help format the code in a visually appealing manner similar to syntax highlighting code editors and is one of the better features of this forum compared to others "out there."


:davis:
  #7  
Old 01-Nov-2007, 18:28
Blake's Avatar
Blake Blake is offline
Member
 
Join Date: Nov 2005
Posts: 172
Blake will become famous soon enough

Re: Sum of the even numbers between n1 and n2


It looks like your question is already answered, but just FYI, you could compute this without using a loop at all, like this:

CPP / C++ / C Code:
int sumEven(int n1, int n2)
{
  int start = n1 + (n1 % 2);
  int end = n2 - (n2 % 2);
  return (end - start + 2) * (end + start) >> 2;
}

This comes from the formula derived by Gauss for the sum of the numbers from 1 through n:

1 + 2 + ... + n = (n + 1) * n / 2

Multiplying each side by 2, we get

2 + 4 + ... + 2n = (n + 1) * n

Now, we'll add (n + 1) * 2m to each side for some integer m.

(n + 1) * 2m + 0 + 2 + 4 + ... + 2n = (n + 1) * n + (n + 1) * 2m

We'll factor each side now:

(0 + 2m) + (2 + 2m) + (4 + 2m) + ... + (2n + 2m) = (n + 1) * (n + 2m)

Now, start is the smallest even integer that is greater than or equal to n1 (the first number in the sum), and end is the largest even integer that is less than or equal to n2 (the last number in the sum).

The sum is then (0 + start) + (2 + start) + (4 + start) + ... + (end + start)

We'll use the following substitutions:
n = (end - start) / 2
m = start / 2

Then we have

(0 + start) + (2 + start) + (4 + start) + ... + (end + start)
= ((end - start)/2 + 1) * ((end - start)/2 + start)
= [(end - start + 2) / 2] * [(end - start + 2*start)/2]
= (end - start + 2) * (end + start) / 4

Dividing by four is the same as shifting right by 2, so we get
(end - start + 2) * (end + start) >> 2
__________________
www.blake-foster.com
  #8  
Old 01-Nov-2007, 20:19
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,710
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Sum of the even numbers between n1 and n2


Quote:
Originally Posted by Blake
It looks like your question is already answered, but just FYI, you could compute this without using a loop at all, like this:...

And, what is the sum of even integers between -11 and -3? The Original Poster's algorithm gives the correct answer: -28. By my reckoning your program gives -42. Now, Gauss's methodology works for integers in all ranges (negative and positive). At what point did you introduce the error(s) in the program?

Regards,

Dave
"The purpose of computing is insight not numbers."
---Richard W. Hamming
  #9  
Old 01-Nov-2007, 20:37
Blake's Avatar
Blake Blake is offline
Member
 
Join Date: Nov 2005
Posts: 172
Blake will become famous soon enough

Re: Sum of the even numbers between n1 and n2


Good point. This fixes that problem:

CPP / C++ / C Code:
int sumEven(int n1, int n2)
{
  int start = n1 + (n1 & 1);
  int end = n2 - (n2 & 1);
  return (end - start + 2) * (end + start) >> 2;
}

I just changed the modulus operators to the bitwise and operator. This works because n % 2 can be negative, while n & 1 is always positive since the high-order bit is forced to be zero.

I also made a mistake typing out my derivation. I derived it by hand and then typed it, so the end result is right. I just copied one step incorrectly.

the last bit should read:

The sum is then (0 + start) + (2 + start) + (4 + start) + ... + (end - start + start)

We'll use the following substitutions:
n = (end - start) / 2
m = start / 2

Then we have

(0 + start) + (2 + start) + (4 + start) + ... + (end - start + start)
= ((end - start)/2 + 1) * ((end - start)/2 + start)
= [(end - start + 2) / 2] * [(end - start + 2*start)/2]
= (end - start + 2) * (end + start) / 4
__________________
www.blake-foster.com
Last edited by Blake : 01-Nov-2007 at 21:53.
  #10  
Old 01-Nov-2007, 21:20
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,710
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Sum of the even numbers between n1 and n2


Quote:
Originally Posted by Blake
...Then we have...

I agree. You (and Gauss) do good work.

Some insight into the "%" operator is always interesting. If we are dealing with positive ints, there isn't much ambiguity.

However...given that a%b can give a negative result (when a is negative), would it have worked if you had used abs(n1 %2) and abs(n2%2) instead of the neater (sneaky, but clever/cool) bit operations?

Regards,

Dave
 
 

Recent GIDBlogMeeting the populace by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Table killer9012 C++ Forum 29 10-Oct-2006 21:15
subscript error in coding warborules C Programming Language 6 27-Nov-2005 17:16
sorting numbers through array zidanefreak01 C++ Forum 3 26-Jun-2005 02:41
Linear Search eccoflame C Programming Language 3 19-Apr-2005 08:36
[CONTEST?]Data Structure Test dsmith C Programming Language 2 06-Jun-2004 15:13

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 03:44.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.