4.9上机练习

1.编写一个简单程序,要求数组长度为5,静态赋值10,20,30,40,50,在控制台输出该数组的值。

package chap1;

public class Main
{
    public static void main(String[] args)
    {
       int a[] = {10, 20, 30, 40 ,50};
       for (int i = 0; i < 5; i++)
       {
           System.out.println(a[i]);
       }
    }
}

  4.9上机练习_第1张图片

 

 

 2.编写一个简单程序,要求数组长度为5,动态赋值10,20,30,40,50,在控制台输出该数组的值。

package chap1;

public class Main
{
    public static void main(String[] args)
    {
        int a[] = new int[5];
        for (int i = 0; i < 5; i++)
        {
            a[i] = 10 * i + 10;
            System.out.println(a[i]);
        }
    }
}

  4.9上机练习_第2张图片

 

 

 3.编写一个简单程序,定义整型数组,里面的元素是{23,45,22,33,56},求数组元素的和、平均值

package chap1;

public class Main
{
    public static void main(String[] args)
    {
        int a[] = new int[]{23,45,22,33,56};
        int sum = 0, avg = 0;
        for (int i = 0; i < 5; i++)
        {
            sum += a[i];
        }
        System.out.println("数组元素和为" + sum + " 平均值为" + sum / 5.0);
    }
}

  4.9上机练习_第3张图片

 

 

 4.在一个有8个整数(18,25,7,36,13,2,89,63)的数组中找出其中最大的数及其下标。

package chap1;

public class Main
{
    public static void main(String[] args)
    {
        int a[] = new int[]{18, 25, 7, 36, 13, 2, 89, 63};
        for (int i = 0; i < a.length - 1; i++)
        {
            for (int j = i + 1; j < a.length; j++)
            {
                if (a[i] < a[j])
                {
                    int tmp = a[j];
                    a[j] = a[i];
                    a[i] = tmp;
                }
            }
        }
        System.out.println("最大数为:" + a[0]);
        int b = a[0];
        a = new int[]{18, 25, 7, 36, 13, 2, 89, 63};
        for (int i = 0; i < a.length; i++)
        {
            if (b == a[i])
            {
                System.out.println("下标为:" + i);
            }
        }
    }
}

  4.9上机练习_第4张图片

 

 

5. 将一个数组中的元素逆序存放(知识点:数组遍历、数组元素访问)

package chap1;

public class Main
{
    public static void main(String[] args)
    {
        int a[] = new int[]{18, 25, 7, 36, 13, 2, 89, 63};
        for (int i = 0; i < a.length / 2; i++)
        {
            int b = a[i];
            a[i] = a[a.length - i - 1];
            a[a.length - i - 1] = b;
        }
        for (int i = 0; i < a.length; i++)
        {
            System.out.println(a[i]);
        }
    }
}

  4.9上机练习_第5张图片

 

你可能感兴趣的:(4.9上机练习)