Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
GreenGeeks Web Hosting - Faster, Scalable & Eco-Friendly

BlueHost Web Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

getflywheel wordpress hosting


Distribute your Resume to 500+ Job Boards & Recruiters


7,917 questions

11,028 answers

573 users

How to calculate the sum of first N natural numbers in Java

2 Answers

0 votes
package javaapplication1;

// 1 + 2 + 3 + 4 + ... + N

public class JavaApplication1 {
  
    public static void main(String[] args) {
         
        int n = 10, sum = 0;

        while (n > 0)
        {
            sum += n;
            n--;
        }
        
        System.out.format("The sum is: %d\n", sum);
    }
}
    
/*
run:
   
The sum is: 55
    
*/

 




answered May 26, 2017 by avibootz
edited May 26, 2017 by avibootz
0 votes
package javaapplication1;

// 1 + 2 + 3 + 4 + ... + N

public class JavaApplication1 {
  
    public static void main(String[] args) {
         
        int n = 10;
        float sum = 0;

        sum = n / 2 * (n + 1);
        
        System.out.format("The sum is: %.2f\n", sum);
    }
}
    
/*
run:
   
The sum is: 55.00
    
*/

 




answered May 26, 2017 by avibootz
...