+ 20
// First, initializing an int array with 4 elements int [ ] myArr = {6, 57, 3, 7}; // sum is a variable which will store the array sum, initializing it with 0. // why 0? because 0 will not affect the actual total sum int sum=0; // The main part /* Think about the sum calculation without a loop. What should you do then? You'll have to add all the array elements with initial sum, right? Calculating without loop: sum = sum+ myArr[0] // sum = 0+6 = 6 sum = sum+ myArr[1] // sum = 6+57 = 63 sum = sum+ myArr[2] // sum = 63+3 = 66 sum = sum+ myArr[3] // sum = 66+7 = 73 Note, for array of size 4, the valid indices are 0,1,2,3. (Not 4, it's a common mistake) Now, come back to loop. From the above calculation we can see that we are getting a common pattern each time: sum = sum + myArr[index which differs]; So we can write a loop which will iterate over the index value. What should be the starting index? 0 What should be the end-condition? upto index 3 or upto myArr.length-1 The index changes like 0,1,2,3... so it should be incremented after each iteration We are expressing the common index as x inside the loop */ for(int x=0; x<myArr.length; x++) { sum += myArr[x]; // sum += myArr[x] is same as sum=sum+myArr[x] } // done with loop, now print the final sum System.out.println(sum); // DONE!! :)
19th May 2017, 12:29 PM
Shamima Yasmin
Shamima Yasmin - avatar