0

Why do I need to put result = 0; in order to get correct result!

Problem: Find the sum of an array Solution (Code): class Abshihek { public static void main(String[] args) { int result; int[] arr1 = {1, 2, 3, 4, 5}; for(int i = 0; i < arr1.length; i++) { result += arr1[i]; } System.out.println(result); } }

20th Aug 2021, 1:16 AM
Abhishek Kumar
1 Answer
+ 4
because you declared result as an integer variable. THEN you try and add something to it. Once you declare a variable, it doesn't mean it has value, you need to give it one before trying to preform operations on it
20th Aug 2021, 2:08 AM
Slick
Slick - avatar