JavaScript
x
#1
#2 3
#4 5 6
#7 8 9 10
#11 12 13 14 15
this is the required pattern and the code which i used is
JavaScript
public class Test{
public static void main(String[] args) {
int k = 1;
for (int i = 0; i <= 5; i++){
for (int j = 1; j <= i; j++){
System.out.print(k + " ");
k++;
}
System.out.println();
}
}
}
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 oni-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.