Saksham
Saksham

Reputation: 15

How would I go about tracing this java arrays code snippet

public static void addBonus(double[] array, double bonus)
{
    for (int k = 0; k < array.length; k++)
   {
        array[k] = array[k] + bonus;
   }
}

public static void main(String[] args)
{ 
    double[] scores = { 45.6, 67.8, 89.4 };
    addBonus(scores, 3.0);
    System.out.print(scores[2]);
}

I see that this is an execution of a method that changes the array contents, and I start off by running through the loop and am fine until I get to the + bonus part, I know array[k] would be 45.6 for [0] and so on but I'm not sure if 3.0 is what I should be adding. I guess what my issue is, is not understanding the line addBonus(scores, 3.0). Thank you for your time, I'm relatively new to java

Upvotes: 0

Views: 383

Answers (2)

Rajeev Singh
Rajeev Singh

Reputation: 3332

In line addBonus(scores, 3.0) you are calling the method addBonus with arguments scores & 3.0. So these will be copied to their respective parameters of the method addBonus(double[] array, double bonus). So bonus will have the value 3.0.

Here array[k] = array[k] + bonus; you are adding 3.0 to all array elements.

Upvotes: 0

Abhi Andhariya
Abhi Andhariya

Reputation: 560

Yes each of your array element will be increment by 3.0 bonus which your are passing in addBonus(scores, 3.0);

Upvotes: 1

Related Questions