The value displayed in the for loop calculation results is different than expected.

Asked 2 years ago, Updated 2 years ago, 33 views

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); 
    } 
}  

java

2022-09-30 17:54

1 Answers

,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.


2022-09-30 17:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.