I need to get this result : input I wanted to have
I am very close but the final step is killing me:
public static void printMultiplicationTable(int size) {
System.out.print("\t");
for (int i = 0; i <= size; i++) {
for (int j = 0; j <= size; j++) {
if (j == 0) System.out.print( i );
else if (i == 0) System.out.print("\t" + j);
else System.out.print("\t" + i * j);
}
System.out.println();
}
}
How do I get empty space at first line and start from 1 instead of 0 ?
You were indeed close. your first System.out.print("\t");
was causing extra tab. Also, I have added the output for the condition when i==0 && j==0
. Given below is the program that prints the desired result:
public class TestMyClass {
public static void main(String[] args) {
printMultiplicationTable(4);
}
public static void printMultiplicationTable(int size) {
for (int i = 0; i <= size; i++) {
for (int j = 0; j <= size; j++) {
if (i==0 && j==0)
System.out.print("");
else if (j == 0)
System.out.print(i);
else if (i == 0)
System.out.print("\t" + j);
else
System.out.print("\t" + i * j);
}
System.out.println();
}
}
}
Output:
1 2 3 4
1 1 2 3 4
2 2 4 6 8
3 3 6 9 12
4 4 8 12 16