+ 2
What will be output of this code guys? And can you explain step by step why?
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); } }
3 Antworten
+ 3
The for loop runs 4 Times going through all of the Arrays elements.
x ist the current Position of the Loop and by running that Loop the int at the current Position gets added to the variable sum.
all values of sum while going through the loop
x sum myArr[x]
0. 0 + 6 = 6
1. 6 + 42 = 48
2. 48 + 3 = 51
3. 51 + 7 = 58
The Output will be "58"
+ 1
Output: 58
1. You initialize an array with 'integers' as elements.
2. You initialize a variable 'sum', which will hold a sum - the output in that case.
3. Using for loop which will increase an index 'x' (needed to get the elements in the array), which start from 0, and ends at 3 (1st to last element in that case).
Note: 'myArray.length' gives the elements count (4), but the array indexes starts from 0, so to get 4 elements, we need 0 to 3 (x < myArray.length).
How it works:
1) int x = 0; // Our counter is initialized
2) x < myArray.length; // 0 < 3 (true)
3) If the condition in step 2 is true - execute code in the block (between the curly braces)
If the condition is false, break the loop.
4) In the block (or body, if you want):
sum += myArray[x]; // sum = sum + myArray[x] (current element)
if x = 0, myArray[x] = 6
if x = 1, myArray[x] = 42
and so on...
5) x++; // x = x + 1 and go to step 2.
When x = 4, the loop breaks on step 2 and the program continue with the next statement out of the loop block.
4. System.out.println(sum); // Here we calling the method 'println', which will print a value to the console. In our case - the sum of all numbers from the array.
0
Thanks a lot guys