the output of a simple code

Hi!
First, sorry for my english.
I start to learn c++ and I have some questions about some code.

1
2
3
4
5
6
7
8
9
10
11
 #include <iostream>
using namespace std;
int main()
{ 
    int i,j,k=0;
    for (i=1;i<=5;i++)
        for (j=i;j<=8;j++)
            k++;
    cout<<k; return 0; 
}


Why the output of this code is 30 ?
My logic:So initally k=0.For i=1;1<=5 (true) i becomes 2.
Then for j=1; 1<=8 (true) j becomes 2 and k becomes 1.
Then I start again with i=2;i<=5(true) i becomes 3.
For j=2;2<=8 j becomes 3 and k becomes 2
and so on

If the code would be
1
2
3
4
5
6
7
8
9
10
 #include <iostream>
using namespace std;
int main()
{ 
    int i,j,k=0;
    for (i=1;i<=5;i++)
            k++;
    cout<<k; return 0; 
}

The output is 5, I get that.But why it becomes 30 if I add the line for (j=i;j<=8;j++)
Try writing it as
1
2
3
4
5
6
7
    for (i=1;i<=5;i++) {
        cout << "i=" << i << endl;
        for (j=i;j<=8;j++) {
            cout << "j=" << j << endl;
            k++;
        }
    }


In other words, it's software - so you can change it.

If you don't understand something, then change it so you can add code (anything you like) which might help you understand what's going on.

In a few weeks, you'll get fed up with editing the code and then learn how to use a debugger.
A debugger allows you to stop the code at a point of your choosing, examine variables, change variables, single step lines of code etc etc.
What are you expecting the output to be?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main()
{
   int k { };

   for (int i = 1; i <= 5; i++)
   {
      for (int j = i; j <= 8; j++)
      {
         k++;
         std::cout << k  << '\t';
      }
      std::cout << '\n';
   }

   std::cout << '\n' <<  k << '\n';
}

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

30
if it were j = 1, its easy. you multiply the two... and get 40.
but its j = i. so each inner loop does less than before.
you do (inclusive) 1-8, then 2-8, then 3-8, ...
or the sum of 8+7+6+5+4 -> what is this sum? its 30.
this is important later on as you study the complexity of algorithms. Loops that increment differently or nested loops that are coupled like this have different profiles, usually doing far less work than you might think when you see nested loops.
Last edited on
Topic archived. No new replies allowed.