i wrote this code but it is not giving my desired output

i want to draw this pattern
1 2 3 4 5
1 3 5 7
1 4 7
1 5
1
Last edited on
First, code tags <> help reading:
1
2
3
4
5
6
7
8
9
for ( int i=1; i<=5; i++ )
{
  for ( int j=1; j<=5; )
  {
    cout<<j;
    j=j+i;
  }
  cout<<"\n";
}

Would the logic be more clear, if you would call the i either row or line?

That aside, the inner loop repeats while j<=5. With that condition you cannot possibly reach 7.

How many numbers are on one row? Can you express that as a function of the row number?
The code you've written will just write:

1 2 3 4 5


five times. I trust that you can see why this is so?

First you need to analyse the pattern, and understand the logic behind it.

- What is the relationship between the numbers on a line. How is that line generated?
- What is the relationship between one line and the next? Is there a simple pattern that would allow you to know, given one line, what numbers should be on the next line?

Once you understand the pattern, then you can think about coding it.
Last edited on
i tried hard nbut couldn't understand how to print 7
Can you print this pattern:
1 5
2 4
3 3
4 2
5 1
i tried hard nbut couldn't understand how to print 7

Printing is something you do with code.

I've already told you, don't bother thinking about code until you've understood the logic of the pattern. You shouldn't be thinking about printing anything at all, until you've done that.

Hint:

For the FIRST row, each number is one higher than the previous one.

Now, what is the rule for the SECOND row?

What is the rule for the THIRD row?

etc... etc...
Last edited on
Topic archived. No new replies allowed.