Reputation: 1278
#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
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.
Upvotes: 2
Views: 809
Reputation: 3511
You can use this:
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 0; j < i; j++) {
System.out.print((i * (i - 1)) / 2 + j + 1 + " ");
}
}
}
Or you can the find the nth term and subtract it each time:
public static void main(String[] args) {
for (int i = 0; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(((i * (i + 1)) / 2) - (i - j) + " ");
// k++;
}
System.out.println(" ");
}
}
Upvotes: 0
Reputation: 5712
You can use
System.out.println((i+j) + " ");
e.g.
i j (i+j)
0 1 1
1 1 2
2 1 3
2 2 4
..........
Upvotes: -5
Reputation: 726849
Since this problem is formulated as a learning exercise, I would not provide a complete solution, but rather a couple of hints:
priorLine + j
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.Upvotes: 6