1.知识框图
2.代码部分
1.一维数组和二维数组的遍历
package com.xibukaiyuan.da;
public class array {
public static void main(String[] args) {
//一维数组的遍历
int[] a=new int[]{1,2,3,5,6};
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println();
System.out.println("-----------------");
//二维数组的遍历
int sum=0;
int[][] b=new int[][]{{1,2,4},{2,3,4},{3,2,2}};
for (int i = 0; i < b.length; i++) {
for (int i1 = 0; i1 < b[i].length; i1++) {
System.out.print(b[i][i1]+" ");
sum+=b[i][i1];
}
}
}
}
2.输出杨辉三角形
package com.xibukaiyuan.da;
import java.util.Scanner;
public class triange {
public static void main(String[] args) {
//输入杨辉三角形的行数
System.out.println("数入杨辉三角形的行数:");
Scanner as=new Scanner(System.in);
final int n=as.nextInt();
int [][]a=new int[n][n];
a[0][0]=1;
for (int i = 1; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if(j==i||j==0)
{
a[i][j] = a[0][0];
}
else
a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
}
}
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < i+1; j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}
在上述代码中,若创建二维数组的格式为:int[][] a=new int[m][];则不能给a[0][0]赋初值,因为此时并没有给任何一个一维数组开辟内存,所以需要:
1.for (int i = 0; i < n; i++) {
a[i]=new int[i+1];
}
2.int[] [] a=new int[m][n];
//m,n为常量
3.求5的阶乘
public class factorial {
public static void main(String[] args) {
int a=5;
System.out.println(jie(5));
}
public static int jie(int a) {
if (a == 1)
return 1;
else
return a * jie(a - 1);
}
}
4.不死神兔问题
<textarea readonly=“readonly” name=“code” class"java">
import java.util.Scanner;
public class no_death_rabbit {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("输入月数");
int a=sc.nextInt();
System.out.println("兔子总数变为:"+rabbit(a));
}
public static int rabbit(int n)
{
if(n==1||n==0)
{
return 1;
}
else
return rabbit(n-1)+rabbit(n-2);
}
}