0

Somebody explain this piece of code?

int arr [ ] = new int [3] ; (for int i = 0; i < 3; i++) { arr [i] = i; } int res = arr [0] + arr [2] ; system.out.println (res) ;

27th Nov 2017, 6:58 AM
Rizan
Rizan - avatar
3 Answers
+ 12
I guess you need the explanation for the loop block of code, here you go: ‱ You've created a for loop which iterates from 0 to 2 (i.e. 3 times). ‱ arr[i] = i; executes like: --> when i = 0, arr[0] = 0; --> when i = 1, arr[1] = 1; --> when i = 2, arr[2] = 2; And hence when you add arr[0] to arr[2], it adds (0 + 2) and stores the result (2) in variable res.
27th Nov 2017, 7:38 AM
Dev
Dev - avatar
0
Thanks a ton:) I didn't think about syntax, hence the errors.... thanks:)
27th Nov 2017, 9:59 AM
Rizan
Rizan - avatar