+ 1

what is explanation of sum+= buck [counter]

public class GOICHI{ public static void main(String [] args){ int buck []= {1,2,3,4,5}; int sum = 0; for (int counter =0;counter<buck.Length;counter++){ sum +=buck [counter]; } System.out.println(sum) } }

12th May 2018, 12:59 PM
ilia
ilia - avatar
7 Respostas
+ 17
ilia in the above code int buck [] = {1,2,3,4,5}; is an array containing 5 elements having index values from 0 to 4 1 will have index 0 2 will have index 1 and so on... index means position it starts from 0 Now counter is a local variable having scope only in the for loop... u can take any other variable name ... inside for loop... for(int counter=0; counter<buck.length; counter++) 👆 here when for loop will run the value of counter will change from 0 to 4... buck[counter] will be changing from buck[0] to buck[4] b[0] = 1st element = 1 b[4] = last element = 5 buck[counter] is used to access the elements of array according to their index position...
12th May 2018, 1:26 PM
🌛DT🌜
🌛DT🌜 - avatar
+ 15
sum+=buck[counter] is same as sum = sum + buck[counter] the given code will give the sum of all the values in buck array
12th May 2018, 1:10 PM
🌛DT🌜
🌛DT🌜 - avatar
+ 15
counter behaves as the index here each time the for loop runs... 1st time for counter=0 buck[counter] = buck[0] = 1 2nd time for counter=1 buck[counter] = buck[1] = 2 until....... 5th time for counter=4 buck[counter] = buck[4] = 5 it will be added to sum... resulting in sum = 15
12th May 2018, 1:13 PM
🌛DT🌜
🌛DT🌜 - avatar
+ 3
bum[counter] = b[0] b[1] until b[4]
12th May 2018, 1:14 PM
Muhd Khairul Amirin
Muhd Khairul Amirin - avatar
+ 1
i know but i mean what is buck[counter]
12th May 2018, 1:11 PM
ilia
ilia - avatar
+ 1
thaanks very much i understand thanks
12th May 2018, 5:48 PM
ilia
ilia - avatar
0
DT sorry i didnt understand how it works please explain easyer
12th May 2018, 1:17 PM
ilia
ilia - avatar