OiciTrap
4
Q:

how to array in subarrays in java

import java.util.Arrays;
 
class Main
{
    // Generic function to get sub-array of a non-primitive array
    // between specified indices
    public static<T> T[] subArray(T[] array, int beg, int end) {
        return Arrays.copyOfRange(array, beg, end + 1);
    }
 
    public static void main(String[] args)
    {
        String[] arr = { "A", "B", "C", "D", "E", "F", "G", "H" };
        int beg = 1, end = 4;
 
        String[] subarray = subArray(arr, beg, end);
        System.out.println(Arrays.toString(subarray));
    }
}
0
// Simple Java program to compute sum of 
// subarray elements 
class GFG { 
      
    // Computes sum all sub-array 
    public static long SubArraySum(int arr[], int n) 
    { 
        long result = 0,temp=0; 
       
        // Pick starting point 
        for (int i = 0; i < n; i ++) 
        { 
            // Pick ending point 
            temp=0; 
            for (int j = i; j < n; j ++) 
            { 
                // sum subarray between current 
                // starting and ending points 
                temp+=arr[j]; 
                result += temp ; 
            } 
        } 
        return result ; 
    } 
      
    /* Driver program to test above function */
    public static void main(String[] args)  
    { 
        int arr[] = {1, 2, 3} ; 
        int n = arr.length; 
        System.out.println("Sum of SubArray : " +  
                          SubArraySum(arr, n)); 
    } 
} 
// This code is contributed by Arnav Kr. Mandal. 
0

New to Communities?

Join the community