Several ways of finding the accumulation result of even numbers within 1-100 by using while loop

This article mainly discusses several ways of using the while loop to realize the accumulated results of even numbers within 1-100. You can also use the for loop and do-while loop to realize these ideas. If there are any shortcomings, you are welcome to correct and supplement

First of all, the first idea is a very conventional loop + judgment. We can split the requirement into two parts. First, the number must be less than or equal to 100, and then the number must be divisible by 2. The detailed code is as follows

  let i = 0
        let sum = 0 
        while(i<101){
    
    
            if(i % 2 === 0){
    
    
                sum = sum + i
            }
            i++
        }
        console.log(sum)

The second way of thinking is to use the ternary judge to realize the process of judgment

 let i = 0
        let sum = 0 
        while(i<101){
    
    
            i % 2 === 0 ? sum=sum+i :sum=sum+0
             i++
        }
        console.log(sum)

The third way of thinking is to take out the result based on the characteristics of even numbers. The even numbers between 1-100 are actually 1 * 2, 2 * 2, 3 * 2...50 * 2, and the code to achieve it is

 let i = 0
        let sum = 0 
        while(i<51){
    
    
            sum = sum + 2*i
            i++
        }
        console.log(sum)

The fourth way of thinking is to divide 1-100 into fifty groups, each group is 1 and 2, 3 and 4, 5 and 6, and so on. We can see that even numbers are always one more than odd numbers, that is, even numbers The sum is 50 more than the sum of odd numbers. We can first calculate the cumulative result of 1-100, and then calculate the sum of even numbers. It is implemented by code

   let i = 0
        let sum = 0 
        while(i<101){
    
    
            sum = sum + i
            i++
        }
        console.log((sum-50)/2+50)

Again, if you have enough knowledge reserves, you can also use other loops such as for loops, and you can also use more concise and interesting algorithms~

Guess you like

Origin blog.csdn.net/qq_41490563/article/details/125425269