一、本节算法的知识点都体现在以下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);
}
}