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>
usingnamespace 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?
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.
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;
}