For loop (odd and even integers) question.

Hello,

I am new to C++ and am taking a class at a local community college. One of our handouts shows how a for loop works, except I don't know how or what it is doing exactly.. Here is the code that is written in the handout:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  #include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    const int MAX = 20;
    
    int count, oddsum = 0, evensum = 0, i = 1, j = 2;
    
    cout << endl << "The sum of all . . ." << endl;
    cout << " n | odd integers | even integers" << endl;
    cout << "   | up to     is | up to     is" << endl;
    cout << "   |   |      |   |   |      |" << endl;
    cout << "   | \\|/     \\|/   |  \\|/   \\|/" << endl;
    cout << "   |              |" << endl;
    
    for (count = 1; count <= MAX ; count++)
    {
        oddsum +=i;
        evensum +=j;
        cout << setw(2) << count
        << "  | " << setw(4) << i << setw(7) << oddsum
        <<"    |" << setw(4) << j << setw(7) << evensum << endl; 
        
        i += 2;
        j += 2;
    }
    
    cout << endl;
    cin.get();
    return 0;
}


I understand what the int count is doing, but for everything else after that, I have no idea how it's calculating the odd and even integers. Initially, it calculates the i as //oddnumber + 1 = 1 and evennumber + 2 = 2. After this, how does it calculate for the other variables? I don't understand the order of how the code works.

Any help is appreciated.

Thank you.
Well every other number is odd, or even, example 1,3,5,7,9

So when you say i=1(line10), then i+=2(line27), your jumping to the next odd number....
Last edited on
Topic archived. No new replies allowed.