- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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.
Advertisements