Home >Java >JavaBase >Use the while statement to find the sum of odd numbers from 1 to 100 in java

Use the while statement to find the sum of odd numbers from 1 to 100 in java

王林
王林Original
2020-02-05 09:50:3920531browse

Use the while statement to find the sum of odd numbers from 1 to 100 in java

Use the while statement to find the sum of odd numbers and even numbers from 1 to 100.

Specific examples are as follows:

(Free learning video tutorial sharing: java video tutorial)

public class TestWhile{
    
    public static void main(String[] args){
        
        int i = 1;
        int sum = 0;
        while(i<100){
            sum+=i;
            i+=2;
        }
        
        System.out.println("1-100的奇数和为sum = "+sum);
        System.out.println("--------------------------------------- ");
        int j = 1;
        sum = 0;
        while(j <= 100){
            
            if(j%2 == 0){    
                sum+=j;
            }
             j++;      
        }        
        System.out.print("1-100的偶数数和为sum = "+sum);
    }
    
}

Related article tutorial sharing: Getting Started with Java Tutorial

The above is the detailed content of Use the while statement to find the sum of odd numbers from 1 to 100 in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn