Skip to content
Advertisement

How to make pattern of numbers in java using only two variables?

JavaScript

this is the required pattern and the code which i used is

JavaScript

as you can see i used the variable k to print the numbers. My question is that is there a way to print the exact same pattern without using the third variable k? I want to print the pattern using only i and j.

Advertisement

Answer

Since this problem is formulated as a learning exercise, I would not provide a complete solution, but rather a couple of hints:

  • Could you print the sequence if you knew the last number from the prior line? – the answer is trivial: you would need to print priorLine + j
  • Given i, how would you find the value of the last number printed on i-1 lines? – to find the answer, look up the formula for computing the sum of arithmetic sequence. In your case d=1 and a1=1.
Advertisement