Home > Blockchain >  Calling array method in main class
Calling array method in main class

Time:11-13

How can i call runningSum method in main with new array of intigers so it return result?

class Main {
   
    public static void main(String[] args) {
        
        
        
    }

    public int[] runningSum(int[] nums) {
        int[] result = new int[nums.length];
        result[0] = nums[0];

        for (int i = 1; i < nums.length; i  ) {
            result[i] = result[i - 1]   nums[i];
        }

        return result;
    }
}

I have no idea how to call it.

CodePudding user response:

Add static modifier to your runningSum method. example

public static void main(String[] args) {



int[] myNum = {10, 20, 30, 40};

    int[] result = runningSum(myNum);

    for (int item : result){
        System.out.println(item);
    }


}

public static int[] runningSum(int[] nums) {
    int[] result = new int[nums.length];
    result[0] = nums[0];

    for (int i = 1; i < nums.length; i  ) {
        result[i] = result[i - 1]   nums[i];
    }

    return result;
}
  • Related