java基础2.(算法的8个实例)

一、本节算法的知识点都体现在以下8个例子中

1. 题目是:1 + 2 + 3 + … + 100  用java编程实现。

   public class Jaa {
   public static void main(String[] args) {
      int a = 0;
      for(int b = 1; b <= 100; b++){
       a = a + b;
      }
      System.out.println(a);
   }
}

2. 题目是:1 + 1 + 2 + 3 + 5 + ……

public class Jab {
   public static void main(String[] args) {
      int a = 1;
      int b = 1;
      for(int i = 1; i <= 19 ; i++){
       int c = 0;
       c = a;
       a = b;
       b = c + b;
      }
      System.out.println(b);
   }
}

3. 输出直角三角形。

public class Jac {
   public static void main(String[] args) {
      for(int i=1; i<=9; i++) {
       for(int j=1; j<=i; j++) {
        System.out.print("*");
       }
       System.out.println();
      }
   }
}

4. 倒着输出上面的直角三角形。

public class Jad {
   public static void main(String[] args) {
      for(int i=9; i>=1; i--) {
       for(int j=1; j<=i; j++) {
        System.out.print("*");
       }
       System.out.println();
      }
   }
}

5. 输出正三角形。

public class Jae {
   public static void main(String[] args) {
      int a = 1;
      for(int i=4; i>=0; i--) {
       for(int j=1; j<=i; j++) {
        System.out.print(" ");
       }
       for(int k=1; k<=a; k++){
         System.out.print("*"); 
       }
       System.out.println();
       a = a + 2;
      }
   }
}

6. 输出九九乘法表。

public class Jaf {
   public static void main(String[] args) {
      for(int i=1; i<=9; i++) {
       for(int j=1; j<=i; j++) {
        System.out.print(j+"*"+i +"="+(j*i)+" ");
       }
       System.out.println();
      }
   }
}

7. 输出100到200间的质数。

public class Jag {
   public static void main(String[] args) {
      for(int i=101; i<200; i++){
       for(int j=2; j<i; j++){
         if(i%j==0){
           break; 
         }        
           else if( j==(i-1) )
         {   System.out.println(i) ;   }  
       }  
       
      }
   }
}

8. 用递归法做第2题。

public class Jah {
  public static void main (String[] args) { 

                               
     System.out.println(m(i)); 

     
  }


  public static int m(int n){


     if(n==1||n==2)
           return 1; 
     else
           return m(n-1) + m(n-2);
  }
}

转载于:https://www.cnblogs.com/qaz-song/archive/2012/07/04/2576651.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值