Angela
Angela

Reputation: 9

I am having trouble understanding results from a line of code in the c++ for dummies book

This is the entire code:

#include <iostream>
using namespace std;

int main() {
    int i, j, x; 

    for (x=0, i=0, j=10; i <= 5, j <= 20;  i++, j=j+2, cout<<i+j, x+=i+j)
    {

    }
    return 0;
}

This line specifically:

for (x=0, i=0, j=10; i <= 5, j <= 20;  i++, j=j+2, cout<<i+j, x+=i+j)

I understand what it does. There are two variables which increase at different rates which are both added to a single variable repeatedly. However, I don't understand why the result is so large. The result is 131619222528. (x=0). Aren't you adding something like 10+13+16... All the way up to 25? How can the result possibly be that large?

Upvotes: -1

Views: 59

Answers (1)

Vikas
Vikas

Reputation: 99

You can divide the loop into 3 parts. Part A is the initialization of variables: x=0, i=0, j=10; Part B is the condition that needs to be met for the loop to continue: i <= 5, j <= 20; Part C is the action taken AFTER the first iteration of the loop: i++, j=j+2, cout<

So what happens is loop 1: Nothing (the cout is in part C) loop 2: i is incremented to 1, j is incremented to 12, cout i+j prints 13 loop 3: i is incremented to 2, j is incremented to 14, cout i+j prints 16 etc. etc. You get all those numbers in a line.

Upvotes: 2

Related Questions