Search code examples
javaarrayselementsubroutine

how to create a subprogram that finds the sum of the elements entered by a user


Here is the subprogram I wrote:

public static int profitCalc(int num[])
{
    int sum = 0;
    
    for (int i = 0; i < num.length; i = i + 1)
    {
        sum +=  num[i];
    }
    return sum;
}

But when I enter it (like the code below), it gives me an error.

System.out.println(profitCalc(profit[]));

Solution

  • You haven't declared the Integer array

    int[] profit = new int[]{1,2,3,4,5}; 
    System.out.println(profitCalc(profit));
    

    Whole code:

        class Main {
        public static int profitCalc(int num[])
        {
            int sum = 0;
    
            for (int i = 0; i < num.length; i = i + 1)
            {
                sum +=  num[i];
            }
            return sum;
        }
    
        public static void main(String args[]){
            Scanner input = new Scanner(System.in);
            System.out.println("Enter no of vechile:");
            int noOfVechile = input.nextInt();
            int[] profit = new int[noOfVechile];
            for(int i=0;i<profit.length;i++){
                System.out.println("Enter profit of vechile "+(i+1));
                int profitPerVechile = input.nextInt();
                profit[i]=profitPerVechile;
            }
    
            System.out.println(profitCalc(profit));
        }
    
    }