
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to calculate 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 −
Example
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.
- Related Questions & Answers
- C++ Program for Sum of squares of first n natural numbers?
- Sum of squares of first n natural numbers in C Program?
- Python Program for Sum of squares of first n natural numbers
- PHP program to calculate the sum of square of first n natural numbers
- Java Program to cube sum of first n natural numbers
- Difference between sum of the squares of and square of sum first n natural numbers.
- Sum of first n natural numbers in C Program
- Java Program to Calculate the Sum of Natural Numbers
- Average of Squares of n Natural Numbers?
- Sum of sum of first n natural numbers in C++
- C++ Program to Calculate Sum of Natural Numbers
- C Program for cube sum of first n natural numbers?
- C++ Program for cube sum of first n natural numbers?
- Python Program for cube sum of first n natural numbers
- Sum of square-sums of first n natural numbers
Advertisements