Tag: java array program

  • Reverse an Array in Java using Recursion

    In this java program tutorial, we will write a java program to reverse an array using recursion. Before that, you may go through the following topic in java.

    Explanation: In this java program we will take user input for the size of an array and array elements. The elements are reversed using a recursive function in the program below.


    Reverse an Array in Java using Recursion

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int size, i;
        int arr[] = new int[50];
        Scanner scan = new Scanner(System.in);
    
        System.out.print("Enter the size of a first array: ");
        size = scan.nextInt();
    
        System.out.println("Enter " + size + " elements in first Array:");
        for (i = 0; i < size; i++)
          arr[i] = scan.nextInt();
    
        System.out.print("Original array: ");
        for (i = 0; i < size; i++)
          System.out.print(arr[i] + " ");
    
        //calling a function
        reverseFunc(arr, 0, size - 1);
    
        System.out.print("\nReversed array: ");
        for (i = 0; i < size; i++)
          System.out.print(arr[i] + " ");
      }
    
      static void reverseFunc(int arr[], int start, int end)
      {
        int temp;
        if (start >= end)	//base condition
          return;
    
        temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        reverseFunc(arr, start + 1, end - 1);
      }
    }

    Enter the size of a first array: 5
    Enter 5 elements in first Array:
    1
    2
    3
    4
    5
    Original array: 1 2 3 4 5
    Reversed array: 5 4 3 2 1


  • Reverse an Array in Java

    In this java program tutorial, we will write a java program to reverse an array. Before that, you may go through the following topic in java.

    Explanation: In this java program we will take user input for the size of an array and array elements. The elements are reversed using for loop and while loop.

    We will write two programs:

    1. Using for loop
    2. Using while loop

    Java program to reverse an array without using another array

    Source Code: reverse the array using for loop.

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int size, i;
        int arr[] = new int[50];
        Scanner scan = new Scanner(System.in);
    
        System.out.print("Enter the size of a first array: ");
        size = scan.nextInt();
    
        System.out.println("Enter " + size + " elements in first Array:");
        for (i = 0; i < size; i++)
          arr[i] = scan.nextInt();
    
        System.out.println("Original array: ");
        for (i = 0; i < size; i++)
        {
          System.out.print(arr[i] + " ");
        }
    
        System.out.println("\nArray in reverse order: ");
        for (i = size - 1; i >= 0; i--)
        {
          System.out.print(arr[i] + " ");
        }
      }
    }

    Output:

    Enter the size of a first array: 5
    Enter 5 elements in first Array:
    10
    20
    30
    40
    50
    Original array:
    10 20 30 40 50
    Array in reverse order:
    50 40 30 20 10


    Reverse the Array using while loop

    In this program, we will create a separate user-defined function to reverse the array, and then we will print the reversed array.

    Source Code: reverse an array using a while loop.

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int size, i;
        int arr[] = new int[50];
        Scanner scan = new Scanner(System.in);
    
        System.out.print("Enter the size of a first array: ");
        size = scan.nextInt();
    
        System.out.println("Enter " + size + " elements in first Array:");
        for (i = 0; i < size; i++)
          arr[i] = scan.nextInt();
    
        System.out.print("Original array: ");
        for (i = 0; i < size; i++)
          System.out.print(arr[i] + " ");
    
        //calling a function
        reverseFunc(arr, 0, size - 1);
    
        System.out.print("\nReversed array: ");
        for (i = 0; i < size; i++)
          System.out.print(arr[i] + " ");
      }
    
      static void reverseFunc(int arr[], int start, int end)
      {
        int temp;
        while (start < end)
        {
          temp = arr[start];
          arr[start] = arr[end];
          arr[end] = temp;
          start++;
          end--;
        }
      }
    }

    Output:

    Enter the size of a first array: 5
    Enter 5 elements in first Array:
    1
    2
    3
    4
    5
    Original array: 1 2 3 4 5
    Reversed array: 5 4 3 2 1


  • Java Program to Merge Two Arrays

    In this java program tutorial, we will write a program to merge two arrays in java. Before that, you may go through the following topic in java.

    Explanation: In merge programming in C, we will take two arrays and merge them in a third array. We will take user input for the size of an array and elements of an array for both arrays. The final element is stored in a mergeArray[].


    Java Program to Merge Two Arrays

    Source Code: Program to merge arrays in java.

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int size1, size2, size, i, j, k;
        int arr1[] = new int[50];
        int arr2[] = new int[50];
        int mergeArray[] = new int[100];
        Scanner scan = new Scanner(System.in);
    
        System.out.print("Enter the size of a first array: ");
        size1 = scan.nextInt();
    
        System.out.println("Enter " + size1 + " elements in first Array:");
        for (i = 0; i < size1; i++)
          arr1[i] = scan.nextInt();
    
        System.out.print("Enter the size of a second array: ");
        size2 = scan.nextInt();
    
        System.out.println("Enter " + size2 + " elements in Second Array:");
        for (i = 0; i < size2; i++)
          arr2[i] = scan.nextInt();
    
        //merging...
        for (i = 0; i < size1; i++)
          mergeArray[i] = arr1[i];
    
        size = size1 + size2;
    
        for (i = 0, k = size1; k < size && i < size2; i++, k++)
          mergeArray[k] = arr2[i];
    
        System.out.println("After Merging, the array becomes:");
        for (i = 0; i < size; i++)
          System.out.print(mergeArray[i] + "  ");
      }
    }

    Output:

    Enter the size of a first array: 4
    Enter 4 elements in first Array:
    10
    20
    30
    40
    Enter the size of a second array: 3
    Enter 3 elements in Second Array:
    70
    80
    90
    After Merging, the array becomes:
    10 20 30 40 70 80 90


  • Java Program to Copy one Array to another

    In this java program tutorial, we will write a program to copy the array in java. Before that, you may go through the following topic in java.

    We will look at two programs:

    • Using loop
    • Using System.arraycopy()

    Explanation: In this program, we will copy the elements of one array to another and display the copied array. We will iterate the array using one of the lops in java and copy each element at every iteration.

    Array 1  
    1  2  3  4  

    Copied Array
    1  2  3  4

    Deep Copy Array Java

    public class Main
    {
      public static void main(String[] args)
      {
        int[] arr1 = new int[]
        { 10, 20, 30, 40, 50 };
        int arr2[] = new int[arr1.length];
    
        for (int i = 0; i < arr1.length; i++)
          arr2[i] = arr1[i];
    
        System.out.print("Original Array: ");
        for (int i = 0; i < arr1.length; i++)
        {
          System.out.print(arr1[i] + " ");
        }
    
        System.out.print("\nCopied Array: ");
        for (int i = 0; i < arr2.length; i++)
        {
          System.out.print(arr2[i] + " ");
        }
      }
    }

    Output:

    Original Array: 10 20 30 40 50
    Copied Array: 10 20 30 40 50


    Copy Array to another array in java using System.arraycopy()

    Syntax of the arraycopy() method:

    System.arraycopy(Object src, int srcPos, Object dest, int destPos,int length);

    • src: Source of copying array.
    • srcPos: Starting position of the source array.
    • dest: Destination, where the array is to copied.
    • destPos: Position of the destination array.
    • length: Number of elements to be copied.

    Program source:

    import java.util.Arrays;
    
    public class Main
    {
      public static void main(String[] args)
      {
        int[] arr1 = new int[]
        { 10, 20, 30, 40, 50 };
        int arr2[] = new int[arr1.length];
    
        System.arraycopy(arr1, 0, arr2, 0, arr1.length);
    
        System.out.println("Original Array = " + Arrays.toString(arr1));
        System.out.println("Copied Array = " + Arrays.toString(arr2));
    
      }
    }

    Output: It will produce the same output as the above program.


  • Three Dimensional Array Program in Java

    Let us go through a three dimensional array in java language. Before that, you may go through the following topic in java.

    Three Dimensional (3D) Array program

    3D arrays are the multidimensional array in java. They are quite complicated as they run on three loops. In order to initialize or display the array, we need three loops. The inner loop is for one dimensional array, the second one is for the two dimensions and the outer loop makes the third dimensional array.

    The program below is an example of 3d array in java. We will initialize the 3D array and display the output on the screen.


    Three Dimensional Array Program in Java

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int i, j, k, index_1, index_2, index_3;
        Scanner sc = new Scanner(System.in);
    
        System.out.print("Enter the Index 1 for Array: ");
        index_1 = sc.nextInt();
        System.out.print("Enter the Index 2 for Array: ");
        index_2 = sc.nextInt();
        System.out.print("Enter the Index 3 for Array: ");
        index_3 = sc.nextInt();
    
        int arr[][][] = new int[index_1][index_2][index_3];
    
        System.out.print("\nEnter the elements: \n");
        for (i = 0; i < index_1; i++)
        {
          for (j = 0; j < index_2; j++)
          {
            for (k = 0; k < index_3; k++)
            {
              System.out.print("arr[" + i + "][" + j + "][" + k + "]: ");
              arr[i][j][k] = sc.nextInt();
            }
          }
        }
    
        //Display the elements
        System.out.print("\nThe enetered elements are: \n");
        for (i = 0; i < index_1; i++)
        {
          for (j = 0; j < index_2; j++)
          {
            for (k = 0; k < index_3; k++)
              System.out.print("arr[" + i + "][" + j + "][" + k + "]: " + arr[i][j][k] + "\n");
          }
        }
      }
    }

    Output:

    Enter the Index 1 for Array: 2
    Enter the Index 2 for Array: 2
    Enter the Index 3 for Array:

    Enter the elements:
    arr[0][0][0]: 1
    arr[0][0][1]: 2
    arr[0][1][0]: 3
    arr[0][1][1]: 4
    arr[1][0][0]: 5
    arr[1][0][1]: 6
    arr[1][1][0]: 7
    arr[1][1][1]: 8

    The enetered elements are:
    arr[0][0][0]: 1
    arr[0][0][1]: 2
    arr[0][1][0]: 3
    arr[0][1][1]: 4
    arr[1][0][0]: 5
    arr[1][0][1]: 6
    arr[1][1][0]: 7
    arr[1][1][1]: 8


  • Java Program to Find the Sum of all the Elements in an Array

    In this tutorial, we will write a java program to calculate the sum of all the elements present in an array. Although it is quite simple, you still need to have an idea of the proper function of following in java:

    The for loop in the program runs starting from 0 (array index starts from 0) to the total length of an array (i.e. till the last index). An inbuilt function is used to find the length of an array (array.length).


    Java Program to Find the Sum of all the Elements in an Array

      //find the sum of an array in java
    
     public class SumOfAnArray
     {  
        public static void main(String[] args) 
        {  
          int sum = 0; 
          //Initializing array  
          int [] arr = new int [] {5, 4, 6, 1, 9};  
            
          //sum of array 
          for (int i = 0; i < arr.length; i++) 
          {  
            sum = sum + arr[i];  
          }  
            
          System.out.println("Sum of all the elements of an array: " + sum);  
        }  
     }

    Output:

    Sum of all the elements of an array: 25


  • Get Subarray between Specified Indexes in Java

    Before getting into the programming on subarray between specified indexes, let us first learn about the subarray.

    What is a subarray?

    For example, consider an array = [2,3,4], then the subarrays are [2], [3], [4], [2,3], [3,4], and [2,3,4]. But something like [2,4] would not be considered as subarray.

    For an array of size n, we can calculate non-empty subarrays by n*(n+1)/2.


    Get a subarray of an array between specified indexes in Java

    The various methods to get java array subarray between specified indices is as follows:

    1. Arrays.copyOfRange()

    It is the standard way to get a subarray of an array that returns a subarray from the specified range of an original array. Following is the example:

    int[] copyOfRange(int[] original, int from index number, int to index number)

    import java.util.Arrays;
    
    public class Main 
      {
        public static void main (String[] args) 
        {
            int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
            int[] arrayResult = Arrays.copyOfRange(arr, 3, 9);
            System.out.println(Arrays.toString(arrayResult));
        }
      }

    Output:

    [4, 5, 6, 7, 8, 9]


    2. System.arraycopy()

    This is also one of the methods that are used to copy from the specified position of the source array to the destination array.

    public static vois arraycopy(Object source, srcPpos, Object destination, destPos, int length)

    Example of System.arraycopy():

    import java.util.Arrays;
    
    public class Main 
     {
        public static void main (String[] args) 
        {
            int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
            int[] arrayResult = new int[3];
            System.arraycopy(arr, 3, arrayResult, 0, 3);
            System.out.println(Arrays.toString(arrayResult));
        }
    }

    Output:

    [4, 5, 6]

    3. Arrays.copyOf()

    This is also another way of copying the specified array to a specified type of array. But if the sub-array is not at the first index but is at some intermediate index, this method won’t work.

    Example of Arrays.copyOf():

    import java.util.Arrays;
    
    class Main
    {
       public static void main(String[] args)
       {
          String[] array = new String [] {"A", "B", "C", "D", "E", "F", "G", "H", "I"};
    		
          System.out.println("The sub_array:");
           //Here startingPosition is 0
          String[] sub_array = Arrays.copyOf(array, 6, String[].class);
          System.out.println(Arrays.toString(sub_array));
       }
    }

    Output:

    The sub_array:
    [A, B, C, D, E, F]


    4. Custom Method

    This is a method where we can write our own custom method to copy the specified elements from an array to the new array.

    Example to demonstrate the Custom method:

    import java.util.Arrays;
    
    class Main
    {
     public static void main(String[] args)
     {
      String[] array = new String[] { "A", "B", "C", "D", "E", "F", "G", "H" };
      int startPos = 3, endPos = 6;
      int finalPos = (endPos - startPos) + 1;
    
       System.out.println("The sub_array:");
       String[] sub_array = new String[finalPos];
       for (int i = 0; i < sub_array.length; i++) 
       {
        sub_array[i] = array[startPos + i];
       }
    
      System.out.println(Arrays.toString(sub_array));
     }
    }

    Output:

    The sub_array:
    [D, E, F, G]


    5. Subarray: without copying

    Sometimes it may cause a problem in performance while copying the large part of an array. And in such cases, instead of locating a new array, we can use the instance of the same array.

    Example of subarray through callback

    import java.util.function.Consumer;
    
    public class Main 
    {
     public static void main (String[] args) 
     {
      int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
      System.out.println("The result:");
      arrayResult(array, 3, 9, System.out::println);
     }
    
     public static void arrayResult (int[] ts, int from, int to,Consumer<Object> rangeConsumer) 
     {
      for (int i = from; i < to; i++) 
            rangeConsumer.accept(ts[i]);
          
     }
    }

    Output:

    The result:
    4
    5
    6
    7
    8
    9


  • Java Program to Calculate Average of Elements in an Array

    The program shows how to Calculate the Average in an Array element in java. The program uses a scanner class to take the input from the user. It takes the size of an array and the array elements and adds those elements and displays them accordingly.

    If you do not know the working process of for loop then click the link below.


    Java Program to Calculate Average of Elements in an Array

     //calculate the average in an array element using for loop
    
     import java.util.Scanner;
    
     public class AverageForLoop
     {
        public static void main(String args[])
        {
          int num, sum = 0;
          float average;
          Scanner s = new Scanner(System.in);
          
          System.out.print("Enter the number of elements for an array: ");
          num = s.nextInt();
          
          int a[] = new int[num];
          
          System.out.println("Enter elements of array:");
          for(int i = 0; i < num; i++)
          {
              a[i] = s.nextInt();
          }
             
         
         for(int i=0; i < a.length ; i++)
           sum = sum + a[i];
         
         //calculate average value
         average = sum / num;
         
         System.out.println("Average value of array elements is : " +average);
            
        }
     }

    Output:

    Enter the number of elements for an array: 5
    Enter elements of array:
    1
    2
    3
    4
    5
    Average value of array elements is : 3.0


  • Java Program to Find the Transpose of a Matrix

    In this tutorial, we will write a program to calculate the Transpose of a matrix in Java. As this program is based on Array and uses of for loop so you may go through the following first.

    Transpose of a matrix refers to converting the rows of a matrix into columns and columns of a matrix into rows. Consider a matrix A of 2 * 3 dimension, after transpose of A, the A matrix becomes 3 * 2 dimension.

    The Program takes the input for both the column and row elements from the user using the scanner class and transposes for that matrix is calculated. And lastly displays the final result with altered rows and columns.


    Java Program to Find the Transpose of a Matrix

      //transpose of a matrix in java
      
     import java.util.Scanner;
    
     public class TransposeOfMatrix
     {
        public static void main(String args[])
        {
            int row, col, i, j;
        
            Scanner in = new Scanner(System.in);
            System.out.println("Enter the rows and columns of the matrix");
            row = in.nextInt();
            col = in.nextInt();
        
            int matrix[][] = new int[row][col];
            
            System.out.println("Enter the elements of matrix");
        
            for (i = 0; i < row; i++)
            {
             for (j = 0; j < col; j++)
             {
              matrix[i][j] = in.nextInt();
             }
            }
            int transpose[][] = new int[col][row];
            
            for (i = 0; i < row; i++)
            {
             for (j = 0; j < col; j++)  
             {            
                transpose[j][i] = matrix[i][j];
             }
            }
                
        
            System.out.println("Transpose of a entered matrix are:");
        
            for (i = 0; i < col; i++)
            {
             for (j = 0; j < row; j++)
             {
               System.out.print(transpose[i][j]+"\t");
             }
            System.out.print("\n");
            }
        }
     }

    Output:

     Enter the rows and columns of the matrix
     2
     3
     Enter the elements of matrix
     1
     2
     3
     4
     5
     6
     Transpose of a entered matrix are:
     1	 4	
     2	 5	
     3	 6

  • Java Program for the Multiplication of Two Matrices

    In this tutorial, we will write a java program to calculate the multiplication of two matrices. As this program is based on Array and uses of for loop so you may go through the following first.

    Matrices mean having two-dimension that is there are columns and rows in the following java example.

    The Program takes the input for both the column and row elements from the user using the scanner class and a third two-dimensional array is created to store the multiplication result of two matrices. And lastly displays the final result.


    Java Program to Multiply Two Matrices

     //multiplication of a matrix
      
     import java.util.Scanner;
    
     public class MultilicationMatrix
     {
        public static void main(String args[])
        {
        int r1, r2,c1,c2,i,j,k,sum;
        Scanner in = new Scanner(System.in);
        
        //first matrix
        System.out.println("Enter the number of rows of matrix1");
        r1 = in.nextInt();
        System.out.println("Enter the number columns of matrix 1");
        c1 = in.nextInt();
        
        //second matrix
        System.out.println("Enter the number of rows of matrix2");
        r2 = in.nextInt();
        System.out.println("Enter the number of columns of matrix 2");
        c2 = in.nextInt();
        
        //condition for multiplication
       if(c1==r2)
       {
        
        int mat1[][] = new int[r1][c1]; 
        int mat2[][] = new int[r2][c2]; 
        int result[][] = new int[r1][c2];
        
        System.out.println("Enter the elements of matrix1");
        for ( i= 0 ; i < r1 ; i++ )
        { 
         for ( j= 0 ; j < c1 ;j++ )
         {
          mat1[i][j] = in.nextInt();
         }
        }
        
        System.out.println("Enter the elements of matrix2");
        for ( i= 0 ; i < r2 ; i++ )
        { 
         for ( j= 0 ; j < c2 ;j++ )
         {
          mat2[i][j] = in.nextInt();
         }
        }
        
        System.out.println("Result of multiplication:-");
        for ( i= 0 ; i < r1 ; i++ )
        {
        
         for ( j = 0 ; j < c2; j++)
         {
            sum = 0;
            for ( k = 0 ; k < r2; k++ )
            {
             sum += mat1[i][k] * mat2[k][j] ;
            }
            result[i][j] = sum;
         }
        } 
        for ( i= 0 ; i < r1; i++ )
        {
         for ( j=0 ; j < c2; j++ )
         {
          System.out.print(result[i][j]+" ");
         }
          System.out.println();
         }
      }
      else
        System.out.print("Multiplication cannot be processed");
      }
        
     }

    Output:

     Enter the number of rows of matrix1
     2
     Enter the number columns of matrix 1
     3
     Enter the number of rows of matrix2
     3
     Enter the number of columns of matrix 2
     2
     Enter the elements of matrix1
     2
     3
     4 
     2
     1
     4
     Enter the elements of matrix2
     5
     4
     2 
     3
     5
     3
     Result of multiplication:
     36  29
     32  23