public class Program { public static void main(String[] args) { int [ ] myArr = {6, 42, 3, 7}; int sum=0; for(int x=0; x<myArr.length; x++) { sum += myArr[x]; } System.out.println(sum); } } | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

public class Program { public static void main(String[] args) { int [ ] myArr = {6, 42, 3, 7}; int sum=0; for(int x=0; x<myArr.length; x++) { sum += myArr[x]; } System.out.println(sum); } }

Can you people explain this program

14th Oct 2016, 6:14 AM
Gopal Varma Gottimukhala
Gopal Varma Gottimukhala - avatar
7 Answers
+ 5
in this program array concept has been used. array will initialise like below mentioned myArr[0]=6; myArr[1]=42;myArr[2]=3;myArr[3]=7; myArr.length gives the length of the array which is 4. for loop will be executed till x=3. when x exceeds 3 it'll be terminated. when x=0,sum=6;x=1,sum=6+42=48;x=2,sum=48+3=51,x=3,sum=51+7=58. now output will be displayed as 58
14th Oct 2016, 6:34 AM
Murugavel Maheswaran
Murugavel Maheswaran - avatar
+ 3
@Raymond: "x += y" is an alternative synthax for "x = x + y". Similarly, you have -=, *=, /=, etc.
19th Oct 2016, 12:07 PM
Zen
Zen - avatar
+ 1
58
14th Oct 2016, 6:36 AM
GOKUL KRISHNA YADAVA P
GOKUL KRISHNA YADAVA P - avatar
+ 1
This program sums the elements of the array MyArr and prints this sum. The output is 6 + 42 + 3 + 7 = 58.
14th Oct 2016, 10:20 AM
Zen
Zen - avatar
0
thank you Murugavel Maheswaren, didn't quite understand this too and you just did justice to it. but please can you explain why we use '+=' rather than '+' in executing the for statement?
19th Oct 2016, 3:10 AM
Raymond Crump Rukevwe
Raymond Crump Rukevwe - avatar
0
public class Cop public static void main(String[] args) { int mat[][]={{12,-23,45,-44),(13,-10,15,11)); int sum=0; for(int i[]:mat) for (int :1) { if(j<0) continue; sum+=j%2==0?0:1; } System.out.println(sum);
29th Mar 2024, 9:52 PM
Dawit Ermias
Dawit Ermias - avatar
0
public class Cop public static void main(String[] args) { int mat[][]={{12,-23,45,-44),(13,-10,15,11)); int sum=0; for(int i[]:mat) for (int :1) { if(j<0) continue; sum+=j%2==0?0:1; } System.out.println(sum);
29th Mar 2024, 9:52 PM
Dawit Ermias
Dawit Ermias - avatar