Array Basic

Java Program to Find Largest Element of an array

In this program, you’ll learn to find the largest element in an array using a for loop in Java.

Example: Find largest element in an array

package com.programiz;

public class Largest {

    public static void main(String[] args) {
        double[] numArray = { 23.4, -34.5, 50.0, 33.5, 55.5, 43.7, 5.7, -66.5 };
        double largest = numArray[0];

        for (double num : numArray) {
            if(largest < num)
                largest = num;
        }

        System.out.format("Largest element = %.2f", largest);
    }
}

When you run the program, the output will be:

Largest element = 55.50

In the above program, we store the first element of the array in the variable largest.

Then, largest is used to compare other elements in the array. If any number is greater than largest, largest is assigned the number.

In this way, the largest number is stored in largest when it is printed.

Java Program to Calculate Average Using Arrays

In this program, you’ll learn to calculate the average of the given arrays in Java.

Example: Program to Calculate Average Using Arrays

package com.programiz;

public class Average {

    public static void main(String[] args) {
        double[] numArray = { 45.3, 67.5, -45.6, 20.34, 33.0, 45.6 };
        double sum = 0.0;

        for (double num: numArray) {
           sum += num;
        }

        double average = sum / numArray.length;
        System.out.format("The average is: %.2f", average);
    }
}

When you run the program, the output will be:

The average is: 27.69

In the above program, the numArray stores the floating point values whose average is to be found.

Then, to calculate the average, we need to first calculate the sum of all elements in the array. This is done using a for-each loop in Java.

Finally, we calculate the average by the formula:

average = sum of numbers / total count

In this case, the total count is given by numArray.length.

Finally, we print the average using format() function so that we limit the decimal points to only 2 using "%.2f"

Java Program to Print an Array

In this program, you’ll learn different techniques to print the elements of a given array in Java.

Example 1: Print an Array using For loop

package com.programiz;

public class Array {
    
    public static void main(String[] args) {
        int[] array = { 1, 2, 3, 4, 5 };
        
        for (int element : array) {
            System.out.println(element);
        }
    }
}

When you run the program, the output will be:

1
2
3
4
5

In the above program, the for-each loop is used to iterate over the given array, array.

It accesses each element in the array and prints using println().

Example 2: Print an Array using standard library Arrays

package com.programiz;

import java.util.Arrays;

public class Array {
    
    public static void main(String[] args) {
        int[] array = { 1, 2, 3, 4, 5 };
        
        System.out.println(Arrays.toString(array));
    }
}

When you run the program, the output will be:

[1, 2, 3, 4, 5]

In the above program, the for loop has been replaced by single line of code using Arrays.toString() function.

As you can see, this gives a clean output without any extra lines of code.

Example 3: Print a Multi-dimenstional Array

package com.programiz;

import java.util.Arrays;

public class Array {
    
    public static void main(String[] args) {
        int[][] array = {{1, 2}, {3, 4}, {5, 6, 7}};
        
        System.out.println(Arrays.deepToString(array));
    }
}

When you run the program, the output will be:

[[1, 2], [3, 4], [5, 6, 7]]

In the above program, since each element in array contains another array, just using Arrays.toString() prints the address of the elements (nested array).

在上面的程序中,由于数组中的每个元素都包含另一个数组,因此仅使用Arrays.toString()即可打印元素的地址(嵌套数组)

To get the numbers from the inner array, we just another function Arrays.deepToString(). This gets us the numbers 1, 2 and so on, we are looking for.

为了从内部数组中获取数字,我们只需要另一个函数Arrays.deepToString()。这使我们得到数字1、2,依此类推,寻找所有数字

This function works for 3-dimensional arrays as well.

Example 4: 使用数组进行进制转换-1

package com.programiz;

public class Array {
    
    public static void main(String[] args) {
        DecimalToHex(60);
    }
    
    public static void DecimalToHex(int number) {
        for (int i = 0; i < 8; i++) {
            int temp = number & 15;
            
            if (temp > 9) 
                System.out.print((char)(temp - 10 + 'A'));
            else 
                System.out.print(temp);
            number = number >>> 4;
        }
        
        /*
        int n1 = number & 15;
        System.out.println("n1 = " + n1);
        
        number = number >>> 4;
        int n2 = number & 15;
        System.out.println("n2 = " + n2);
        */
    }
}
// C3000000

Example 5: 查表法

package com.programiz;

public class Array {
    
    public static void main(String[] args) {
        DecimalToHex(60);
    }
    
    public static void DecimalToHex(int number) {
       
        char chs = { '0', '1', '2', '3',
                     '4', '5', '6', '7', 
                     '8', '9', 'A', 'B',
                     'C', 'D', 'E', 'F' };
        
        for (int i = 0; i < 8; i++) {
            int temp = number & 15;
            
            System.out.print(chs[temp]);
            
            number = number >>> 4;
        }
    }  
}
// c3000000

Example 6: 指针

package com.programiz;

public class Array {
    
    public static void main(String[] args) {
        DecimalToHex(60);
    }
    
    public static void DecimalToHex(int number) {
       
        char chs = { '0', '1', '2', '3',
                     '4', '5', '6', '7', 
                     '8', '9', 'A', 'B',
                     'C', 'D', 'E', 'F' };
        
        char[] arr = new char[8];
        
        int pos = 0;
        
        while (number != 0) {
            int temp = number & 15;
           	arr[pos++] = chs[temp];
            number = number >>> 4;
        }
        
        System.out.println("pos = " + pos);
        
        for (int i = 0; i < pos; i++) {
            System.out.print(arr[i]);
        }
    }
}
// C3

Example 7: 优化

package com.programiz;

public class Array {
    
    public static void main(String[] args) {
        DecimalToHex(60);
    }
    
    public static void DecimalToHex(int number) {
        char chs = { '0', '1', '2', '3',
                     '4', '5', '6', '7', 
                     '8', '9', 'A', 'B',
                     'C', 'D', 'E', 'F' };
        
        char[] arr = new char[8];
        int pos = arr.length;
        
        while (num != 0) {
            int temp = number & 15;
            arr[--pos] = chs[temp];
            number = number >>> 4;
        }
        
        System.out.println("pos = " + pos);
        for (int i = pos; i < arr.length; i++) {
            System.out.print(arr[i]);
        }
    }
}
// 3C

Java Array: Exercises, Practice, Solution Section01

Java Array Exercises [74 exercises with solution]

1. Write a Java program to sort a numeric array and a string array

package com.w3resource;

import java.util.Arrays;

public class ArraySortExample {

    public static void main(String[] args) {

        int[] my_array1 = {1789, 2035, 1899, 1456, 2013};
        String[] my_array2 = {"Java", "Python", "PHP", "C#", "C Programming", "C++"};

        System.out.println("Original numeric array : " + Arrays.toString(my_array1));
        Arrays.sort(my_array1);
        System.out.println("Sorted numeric array : " + Arrays.toString(my_array1));

        System.out.println("Original string array : " + Arrays.toString(my_array2));
        Arrays.sort(my_array2);
        System.out.println("Sorted string array : " + Arrays.toString(my_array2));
    }
}

Output

Original numeric array : [1789, 2035, 1899, 1456, 2013]
Sorted numeric array : [1456, 1789, 1899, 2013, 2035]
Original string array : [Java, Python, PHP, C#, C Programming, C++]
Sorted string array : [C Programming, C#, C++, Java, PHP, Python]

2. Write a Java program to sum values of an array.

package com.w3resource;

public class SumValues {
    
    public static void main(String[] args) {
        int my_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
		int sum = 0;
        
        for (int i : my_array) {
            sum += i;
        }
        
        System.out.println("The sum is " + sum);
    }
}

Output

The sum is 55

3. Write a Java program to print the following grid.

// Print the specified grid
package com.w3resource;

public class SpecifiedGrid {
    
    public static void main(String[] args) {
        
        int[][] arr = new int[5][7];
        
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 7; j++) {
                System.out.printf("%2d", arr[i][j]);
            }
            System.out.println();
        }
    }
}

Output

 0 0 0 0 0 0 0
 0 0 0 0 0 0 0
 0 0 0 0 0 0 0
 0 0 0 0 0 0 0
 0 0 0 0 0 0 0

4. Write a Java program to calculate the average value of array elements.

package com.w3resource;

public class CalculateAverage {
    
    public static void main(String[] args) {
        
        int[] numbers = new int[]{20, 30, 25, 35, -16, 60, -100};
        
        // calculate sum of all array elements
        int sum = 0;
        for (int i = 0; i < numbers.length; i++) {
            sum += numbers[i];
        }
        
        // calculate average value
        double average = sum / numbers.length;
        System.out.println("Average value of the array elements is: " + average);
    }
}

Output

Average value of the array elements is: 7.0 

5. Write a Java program to test if an array contains a specific value.

package com.w3resource;
    
public class SpecificValue {

    public static boolean contains(int[] arr, int item) {
        for (int n : arr) {
            if (item == n) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int[] my_array = {1789, 2035, 1899, 1456, 2020};

        System.out.println(contains(my_array, 2020));
        System.out.println(contains(my_array, 2036));
    }
}

Output

true
false

6. Write a Java program to find the index of an array element.

package com.w3resource;

public class FindArrayIndex {

    public static int findIndex(int[] my_array, int num) {
        if (my_array == null)
            return -1;

        int len = my_array.length;
        int i = 0;
        while (i < len) {
            if (my_array[i] == num) {
                return i;
            } else {
                i += 1;
            }
        }

        return -1;
    }

    public static void main(String[] args) {

        int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};

        System.out.println("Index position of 25 is: " + findIndex(my_array, 25));
        System.out.println("Index position of 77 is: " + findIndex(my_array, 77));
    }
}

Output

Index position of 25 is: 0
Index position of 77 is: 6

7. Write a Java program to remove a specific element from an array.

package com.w3resource;

import java.util.Arrays;

public class RemoveSpecificElement {

    public static void main(String[] args) {

        int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};

        System.out.println("Original Array: " + Arrays.toString(my_array));

        // Remove the second element (index->1, value->14) of the array
        int removeIndex = 1;

        for (int i = removeIndex; i < my_array.length - 1; i++) {
            my_array[i] = my_array[i + 1];
        }

        // We cannot alter the size of an array, after the removal,
        // the last and second last element in the array will exist twice
        System.out.println("After removing the second element: " + Arrays.toString(my_array));
    }
}

Output

Original Array: [25, 14, 56, 15, 36, 56, 77, 18, 29, 49]
After removing the second element: [25, 56, 15, 36, 56, 77, 18, 29, 49, 49]

8. Write a Java program to copy an array by iterating the array.

package com.w3resource;

import java.util.Arrays;

public class CopyArrayByIterating {

    public static void main(String[] args) {
        int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
        int[] new_array = new int[10];

        System.out.println("Source Array: " + Arrays.toString(my_array));

        for (int i = 0; i < my_array.length; i++) {
            new_array[i]=my_array[i];
        }

        System.out.println("New Array: " + Arrays.toString(new_array));
    }
}

Output

Source Array: [25, 14, 56, 15, 36, 56, 77, 18, 29, 49]
New Array: [25, 14, 56, 15, 36, 56, 77, 18, 29, 49]

9. Write a Java program to insert an element (specific position) into an array.

package com.w3resource;

import java.util.Arrays;

public class InsertElement {

    public static void main(String[] args) {

        int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};

        // Insert an element in 3rd position of the array (index->2, value->5)

        int Index_position = 2;
        int newValue = 5;

        System.out.println("Original Array: " + Arrays.toString(my_array));

        for (int i = my_array.length - 1; i > Index_position; i--) {
            my_array[i] = my_array[i - 1];
        }
        my_array[Index_position] = newValue;
        System.out.println("New Array: " + Arrays.toString(my_array));
    }
}

Output

Original Array: [25, 14, 56, 15, 36, 56, 77, 18, 29, 49]
New Array: [25, 14, 5, 56, 15, 36, 56, 77, 18, 29]

10. Write a Java program to find the maximum and minimum value of an array.

package com.w3resource;

import java.util.Arrays; 

public class FindValue {
    static int max;
  	static int min;

    public static void max_min(int my_array[]) {
    
        max = my_array[0];
        min = my_array[0];
        int len = my_array.length;
        for (int i = 1; i < len - 1; i = i + 2) {
            if (i + 1 > len) {
                if (my_array[i] > max) 
                    max = my_array[i];
                if (my_array[i] < min) 
                    min = my_array[i];
            }
            if (my_array[i] > my_array[i + 1]) {
                if (my_array[i] > max) 
                    max = my_array[i];
                if (my_array[i + 1] < min) 
                    min = my_array[i + 1];
            }
            if (my_array[i] < my_array[i + 1]) {
                if (my_array[i] < min) 
                    min = my_array[i];
                if (my_array[i + 1] > max) 
                    max = my_array[i + 1];
            }
        }
    }

    public static void main(String[] args) {
        
        int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
        max_min(my_array);
        System.out.println(" Original Array: "+Arrays.toString(my_array));
        System.out.println(" Maximum value for the above array = " + max);
        System.out.println(" Minimum value for the above array = " + min);
    }
}

Output

Original Array: [25, 14, 56, 15, 36, 56, 77, 18, 29, 49]                       
Maximum value for the above array = 77                                         
Minimum value for the above array = 14
基本动态数组是一种能够根据需要自动调整大小的数组,在编程中被广泛使用。与静态数组不同的是,动态数组的长度可根据程序的执行情况进行增加或缩减。 使用函数实现基本的动态数组操作可以增加程序的模块性和可读性。以下是一个使用函数实现基本动态数组的示例: 1. 创建动态数组:可以编写一个函数来创建动态数组。该函数会接受一个整数参数,表示数组的长度,并返回一个指向动态数组的指针。函数内部会使用内存分配函数(如malloc)分配一块大小合适的内存空间,并返回指向此内存空间的指针。 2. 添加元素:编写一个函数来添加元素到动态数组中。此函数应接受动态数组的指针和要添加的元素作为参数。函数内部会重新分配内存空间,将原有元素复制到新的内存位置,并添加新元素。 3. 删除元素:编写一个函数来删除动态数组中的元素。此函数应接受动态数组的指针和要删除的元素的索引作为参数。函数内部会重新分配内存空间,将指定索引前后的元素复制到新的内存位置,从而删除指定索引处的元素。 4. 访问元素:编写一个函数来访问动态数组中的元素。此函数应接受动态数组的指针和要访问的元素的索引作为参数,并返回对应索引处的元素。 5. 释放内存:编写一个函数来释放动态数组占用的内存空间。此函数应接受动态数组的指针作为参数,并使用内存释放函数(如free)释放该内存空间。 通过将这些功能封装到函数中,可以更方便地使用和管理动态数组。这不仅提高了程序的可读性和可维护性,还可以减少代码重复和错误。同时,使用函数还可以轻松地修改和扩展动态数组的功能,以满足不同的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值