understand for loops

I am new to this and trying to understand for loops.
I put this in the computer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# include <iostream>
using namespace std;
int main()
{         
int sum = 1;
int N = 4;
         
for( int i = 1; i < N; ++i )
    sum = N* i;
             
std::cout << "The sum is " << sum << std::endl;

    
    
        return 0;
}


The loop is adding together the last two numbers of N. if N is 10 it adds 9 * 10 = 90. if it is 5 it adds 5*4=20.
I dont get it?
What you're trying to do is :

1
2
3
sum = 1 + 2 + 3
end for loop
sum = 6


What you're actually doing is :

1
2
3
4
5
sum = 1 * 4
sum = 2 * 4
sum = 3 * 4
end for loop
sum = 12


Try this:

1
2
3
for(int i=0; i<N; ++i) {
	sum = sum + i;
}
You start off with sum = 1.

The first time through, sum = N(4) * i(1) which makes sum = 4.
The second time through, sum = N(4) * i(2) which makes sum = 8.
The third time through, sum = N(4) * i(3) which makes sum = 12.

i is no longer < N so the loop ends and prints sum.

i will always be 1 less than N the last time through.

How would i multiply those numbers together? 5! or 4! ?
Looks like you need to change the "N* i" to "N + i" Also, with N initialized to 4, I don't see how it's getting up to 10. Maybe instead of "sum = N* i;" try placing the cout statement there. i.e.
1
2
3
4
5
6
int sum = 1;
	int N = 4;
	for( int i = 1; i < N; i++) {
   sum = (N + i);
   cout << "the sum is " << sum << endl;
	}

By using this I got

the sum is 5
the sum is 6
the sum is 7

Thank you very much!
Topic archived. No new replies allowed.