Java Program to calculate Sum of squares of first n natural numbers

JavaServer Side ProgrammingProgramming

To calculate the sum of squares of first n natural numbers, the Java code is as follows −

Example

 Live Demo

import java.io.*;
import java.util.*;
public class Demo{
   public static int sum_of_squares(int val){
      return (val * (val + 1) / 2) * (2 * val + 1) / 3;
   }
   public static void main(String[] args){
      int val = 8;
      System.out.println("The sum of squares of first 8 natural numbers is ");
      System.out.println(sum_of_squares(val));
   }
}

Output

The sum of squares of first 8 natural numbers is
204

A class named Demo contains a function named ‘sum_of_squares’. This function is used to add up the first ‘n’ natural numbers. This returns the sum of the numbers. In the main function, a value for ‘n’ is defined and the function is called with this ‘n’ value. Relevant output is displayed on the console.

raja
Published on 08-Jul-2020 14:56:45
Advertisements