-1

I wrote a program in c++ that is made up of two for loops like this:

   for(int i=1; i<3; i++)
   {
       for(int j=1; j<3; j++)
       {
       cout<<j<<"\t"<<2*j*i<<endl;
       }
    }

with output:

1    2
2    4
1    4
2    8

But I’m not interested in output with format like this, what I’m looking for is that after the first for loop over j with i=1 is finished, the output of the for loop over j with i=2 prints in a new column like below.

1    2    1    4
2    4    2    8
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458

1 Answers1

2

Invert the loops

for(int j = 1; j < 3; ++j)
{
  for(int i = 1; i < 3; ++i)
  {
    std::cout << j << "\t" << (2 * j * i) << "\t"; // No std::endl here
  }
  std::cout << std::endl;
}

Moreover, some suggestions about your code:

  • Use pre-incrementation when it's possible (++i instead of i++). Check the difference here.
  • Keep the namespace std on your types (std::cout, std::endl). You will avoid a lot of beginner mistakes.
  • Add spaces in your code, it's moooooore clear (std::cout << j << "\t" << (2 * i * j) << std::endl is easier to read than std::cout<<j<<"\t"<<(2*i*j)<<std::endl )
Caduchon
  • 4,574
  • 4
  • 26
  • 67