+ 2

I am not able to understand it please help https://www.sololearn.com/learn/Java/2208/

I am at beginning of java learning and I am stuck here please help me tell me what is it please help https://www.sololearn.com/learn/Java/2208/

14th Apr 2018, 8:00 AM
Pramod Kumar
Pramod Kumar - avatar
4 Respuestas
+ 2
The for-loop iterates over all the array elements. So the first time it takes intArr[0], which is the first element (6). The sum variable is initialised at 0 and every time the loop runs sum is updated. sum += intArr[x] means sum = sum + intArr[x]. In this case the x starts at 0 and ends at 3. Because 4 is equal to intArr.length and not smaller. So for the sum you get the following steps: initialize: sum = 0 first loop: sum = 0 + 6 = 6 second loop: sum = 6 + 42 = 48 third loop: sum = 48 + 3 = 51 fourth loop: sum = 51 + 7 = 58 Then loop terminates and thus is the value of sum 58.
14th Apr 2018, 8:19 AM
Bram
+ 6
Hi, I added some comments to explain what's happening: // create an array which contains // the integers 6, 42, 3, 7 int [ ] myArr = {6, 42, 3, 7}; int sum=0; // loop through the array, starting // from index 0 (first element in // the array) for(int x=0; x<myArr.length; x++) { // each element of the array is // accessed by it's index: index // 0 points to 6, index 1 points // to 42 and so on. // sum += 6 does the same as // sum=sum+6 sum += myArr[x]; } System.out.println(sum); If you have any further questions, just ask :)
14th Apr 2018, 8:14 AM
Tashi N
Tashi N - avatar
+ 1
thanks to all
14th Apr 2018, 8:30 AM
Pramod Kumar
Pramod Kumar - avatar