+ 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?
7 Respostas
+ 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);
}
}
+ 7
arpan[x] refers to the x'th element of the array named arpan.
+ 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. 😊
+ 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.
+ 2
Can u please explain why x is written in the brackets of Array in increment statement
+ 2
THANKS A LOT EVERYONE TO HELP ME OUT. Glad to have you all as partners in this program Field.
+ 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]