public class MultiplicationTable {
public static void main (String[]a){
int[] x;
x = new int[10];
int i;
int n=0;
for (i=0;i
Yes you can! You can use String.format
to add zero padding to your output.
Example:
String.format("%05d", 2)
would produce 00002
.
Some improvement on the current code:
I'm not sure why you intend to store the numbers inside an array (for practice purpose maybe), but that is not necessary as it goes from 1 to 10 anyway. Though if you want to do that, you don't need both i
and n
.
for (i=0; i<x.length; i++){
x[i] = i+1;
System.out.print(x[i] + " ");
}
Secondly, I'm sure you realize that you have a lot of duplicate code, and it's quite sequential. You can do that using 2 nested for loops, instead of having 10 single loops:
for (int row = 1; row <= 10; row++) {
for (int col = 1; col <= 10; col++)
System.out.print(String.format("%03d", row * col));
System.out.println();
}
Yes:
String.format("%01d", x[i]*x[j]); is what you want.
If you're familiar with printf
in C then this will be familiar. If not, read the java reference on String.format format strings.
Also, rather than 10 System.out.println
statements, you can use a doubly nested loop with two counters. One to count which row you're in j
and one for each column i
.