Java program which sums numbers from 1 to 100

前端 未结 5 1535
别那么骄傲
别那么骄傲 2021-01-29 16:50

I have been recently started learning Java and would want to make code that sums the numbers from 1 to 100 (result would be 5050)

The code should go like 1+2+3+4+5+6+7+8+

5条回答
  •  轮回少年
    2021-01-29 17:16

    You output the value of nmb that is the numeric value that you iterate on, you don't increment the actual value with the current sum.

    You should introduce a local variable before the loop to compute and maintain the actual sum.
    Besides, int nmb; could be declared directly in the loop.
    Narrowing the scope of variables makes the code more robust.

    public class T35{
    
        public static void main(String[] args) {
            int sum = 0;
    
            for(int i= 1; i<= 100; i++){    
                sum += i;
                System.out.println(sum);    
            }    
        }
    
    }
    

提交回复
热议问题