Videos
Don't print anything from the outer loop, only new line
for (int i = 1; i <= number; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
Output
1
1 2
1 2 3
1 2 3 4
To avoid the trailing spaces of the other answers,
rather than printing i at the start of the loop, print 1.
Then start the inner loop from 2 and print a space before each value. And print a new line after the inner loop.
for (int i = 1; i <= number; i++) {
System.out.print("1");
for (int j = 2; j <= i; j++) {
System.out.print(" " + j);
}
System.out.println();
}
Prints:
1
1 2
1 2 3
1 2 3 4
In short:
public static void main(String[] args) {
for (int i = 0; i < 6; i++) {
char c = (char) (i + 65);
for (int j = 1; j <= 6; j++) {
System.out.println("" + c + j);
}
}
}
In Long:
You should practice skill in problem solving. Comprehension those small problems will support you much in programming career.
The most important skill when solving problem is breaking apart small problem. Firstly, you see that the output is: A1 A2 A3 ... B1 B2 B3 .. It looks like you can break apart each string (ie: A1) to 2 part: the first part from A to F and the second part from 1 to 6. This is the well-known pattern for applying two nested loop. Here is the pseudocode:
public static void main(String[] args) {
for (char c = A to F) {
for (int j = 1; j <= 6; j++) {
System.out.println("" + c + j);
}
}
}
You see that. the first loop is not true (grammar syntax). So we should learn new thing: char in Java is just an integer. (this is true in most languages such as C#, javascript ...) but not all. So I lookup at ascii table here. I see that A to F start from 65, 66, 67, ... So I can start the loop with 6 elements. Each element I add into 65. For example:
0 -> 65 -> A
1 -> 66 -> B
2 -> 67 -> C
And as you guess, it become my final code I have posted above. Hope this help you :)
Change your code like this:
int numList = 36 / 6;
char letter = 'A';
for (int i = 1; i <= numList; ++i) {
for (int j = 1; j <= numList; j++) {
System.out.println(letter + "" + j);
}
letter++;
}