Nested for loops

Hi its about for loops within a for loop but I dont really understand how I can interpret it. Could someone briefly explain how I can determine what would be printed out from var? Thanks a bunch!
1
2
3
4
5
6
7
8
9
10
int main() {
int var = 0;
for( int i = 0; i <= 99; i++ ) {
  for( int j = 1; j < 100; j++ ) {
var++;
}
var++;
}
cout << "var: " << var << endl;
return 0;
Last edited on
How much does this increase the value of var?
1
2
3
4
for ( int j = 1; j < 100; j++ )
{
  var++;
}

I do assume that you can figure that out. Lets say that the amount is X. We could therefore replace the loop with:
var += X;

Lets insert that into the outer loop:
1
2
3
4
5
6
int var = 0;
for ( int i = 0; i <= 99; i++ )
{
  var += X;
  var++;
}

Plus X and then one more ...
1
2
3
4
5
int var = 0;
for ( int i = 0; i <= 99; i++ )
{
  var += (X+1);
}

How many times does the outer loop repeat? Y times?
1
2
int var = 0;
var += Y * (X+1);

Hi thanks for your reply I got the first and second step but not from the third onwards. How did you var +=(x+1);? But I want to make sure the X we are talking about here is 99? I am really sorry I am just starting to learn about this and it is really confusing me :/
1
2
3
4
5
6
7
8
9
var += X; // add X to var
var++;  // add 1 to var

// is same as

var += X;
var += 1;

// if you add X to var and add 1 to var, surely you add (X+1) to var? 



On first iteration the i==1. On the iteration that does not happen (condition is false) the i==100. The i increments by 1 on every iteration. Therefore, on last iteration i==99.

On the list 1, 2, 3, .. 98, 99 there are indeed 99 discreet values, and thus X==99.
Topic archived. No new replies allowed.