Isn't the number displayed for this program 5050?
public class Sum{
static int sum = 0;
public static void main(String[]args) {
for(inti=1,sum=0;i<=100;i++){
sum = sum + i;
}
System.out.println("sum="+sum);
}
}
,sum=0
in the for loop is unnecessary.
for(inti=1;i<=100;i++){
sum = sum + i;
}
Then, it's just as you imagine.
In its original state, sum is defined as the local variable in the for loop block and is treated differently from the sum in static int sum
.Therefore, as you exit the loop, the local variable sum is irrelevant and the println prints the value of static int sum, which remains the initial value of 0.
© 2024 OneMinuteCode. All rights reserved.