Java program which sums numbers from 1 to 100

前端 未结 5 1576
别那么骄傲
别那么骄傲 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 16:58

    nmb++ is equal to nmb = nmb + 1. It only adds one till it's 101, which is when it stops.

    You should add a new variable, let's call it total, and sum nmb to it every iteration.

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

    This will do what you want.

提交回复
热议问题