打印乘法表的幾種方式

 

//打印乘法表
//雙重循環打印,單循環打印,遞歸
class MultiTable {
 public static void main(String[] args){
  test1(9);
  test2(9);
  test3(1);
 }
 
 //雙重循環打印. 這是最多見的作法。
 public static void test1(int n){
  for(int i=1; i<=n; i++){
   for(int j=1; j<=i; j++){
    System.out.print(j+"*"+i+"="+i*j+"\t");
   }
   System.out.println();
  }
 }
 
 //單循環打印
 public static void test2(int n){
  
  for(int row=1,col=1; row<n ;col++){
   System.out.print(col+"*"+row+"="+col*row+"\t");
   if(row==col){
    System.out.println();
    col = 0;
    row++;   
   }
  }
  遞歸

 }
 
 //遞歸
 public static void test3(int row){
  
  for(int i=1; i<=row ;i++){
   System.out.print(i+"*"+row+"="+i*row+"\t");   
  }
  if(row<9){
    System.out.println();
    test3(++row);
   } class

 }
} test

相關文章
相關標籤/搜索