How do I make a pattern of numbers in java using only two variables?
#1
#2 3
#4 5 6
#7 8 9 10
#11 12 13 14 15
this is the required template and the code 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 k variable to print numbers. My question is, is there a way to print the same pattern without using the third variable k ? I want to print a template using only i and j .
+3
source to share
3 answers
Since this problem is formulated as a learning exercise, I would not suggest a complete solution, but a few tips:
- Couldn't you print the sequence if you knew the last number from the previous line? - the answer is trivial: you need to print
priorLine + j
- Given
i
, how would you find the value of the last number printed on thei-1
lines? - to find the answer, find the formula for calculating the sum of an arithmetic sequence . In your case d = 1 and a 1= 1.
+6
source to share
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 find the nth term and subtract it every 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(" ");
}
}
0
source to share