+ 4

I am not able to understand that the code that i have posed here line number 6 is sum+=arpan[x];. What is the role of x here?

https://code.sololearn.com/cZEgM9bVPK40/?ref=app

9th Feb 2019, 3:32 AM
Arpan Bhattacharya
Arpan Bhattacharya - avatar
7 Answers
+ 8
Arpan Bhattacharya the code for reference: public class Arpan { public static void main(String[] args) { int [ ] arpan = {6, 42, 3, 7}; int sum=0; for(int x=0; x<arpan.length; x++) { sum += arpan[x]; } System.out.println(sum); } }
9th Feb 2019, 3:41 AM
Tony
Tony - avatar
+ 7
arpan[x] refers to the x'th element of the array named arpan.
9th Feb 2019, 7:16 AM
Sonic
Sonic - avatar
+ 5
"x" is a placeholder for an integer. It's a lot more too, but that might be the easiest way to think of it. 😊
9th Feb 2019, 3:37 AM
Tony
Tony - avatar
+ 5
Now notice: int [ ] arpan ... Sum += arpan [x] Int is blank because it is a range, so when we come to the end of the function, instead of putting the range of numbers {6, 42, 3, 7}, we can just use "x", as it is a placeholder.
9th Feb 2019, 3:44 AM
Tony
Tony - avatar
+ 2
Can u please explain why x is written in the brackets of Array in increment statement
9th Feb 2019, 3:40 AM
Arpan Bhattacharya
Arpan Bhattacharya - avatar
+ 2
THANKS A LOT EVERYONE TO HELP ME OUT. Glad to have you all as partners in this program Field.
9th Feb 2019, 7:56 AM
Arpan Bhattacharya
Arpan Bhattacharya - avatar
+ 1
Arpan Bhattacharya An Array starts at 0. In your case it ends at 3. arpan [0] = 6 arpan [1] = 42 arpan [2] = 3 arpan [3] = 7 You could also write sum = arpan [0] + arpan [1] + ... But it is not effektive. You use a for loop. (Initialization, Condition, Decrement/Increment) You want to loop through the array, knowing that it starts at 0 --> int x = 0 (Initialization) your last index = arpan.length - 1 --> x < arpan.length (Condition) --> x++ (Increment) x runs from 0 to 3 --> you can use x as a place holder for each index of your array. x = 0 --> sum+=arpan [0] ... x = 3 --> sum+=arpan [3]
9th Feb 2019, 7:11 AM
Denise Roßberg
Denise Roßberg - avatar