Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Java program to calculate sum of squares of first n natural numbers
In this article, you will learn to write a program in Java to calculate the sum of squares of first n natural numbers. This program efficiently computes the sum using a mathematical formula ?
(val * (val + 1) / 2) * (2 * val + 1) / 3
Problem Statement
Write a program in Java to calculate the sum of squares of first n natural numbers, where n is a user-defined value.
Input
val = 8
Output
The sum of squares of first 8 natural numbers is<br>204
Steps to calculate sum of squares of first n natural numbers
Following are the steps to calculate the sum of squares of first n natural numbers ?
- First we will import the necessary class from java.io and java.util package.
- Create a method called sum_of_squares() within a class to calculate the sum of squares using the formula.
- In the main method, define the value of n (e.g., 8).
- Use the sum_of_squares() method to compute the sum and display the result.
Java program to calculate the sum of squares of first n natural numbers
To calculate the sum of squares of first n natural numbers, the Java code is as follows ?
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
Code Explanation
In the above program, we will learn to calculate the sum of squares of first n natural numbers. 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.
