- Related Questions & Answers
- Average numbers in array in C Programming
- C Program for Tower of Hanoi
- C++ Program for Dijkstra’s shortest path algorithm?
- C/C++ Program for nth Catalan Number?
- C Program to Multiply two Floating Point Numbers?
- C program to find the length of a string?
- C Program to Check if all digits of a number divide it
- C Program to Check if a Given String is a Palindrome?
- Write a program to Delete a Tree in C programming
- Write a C program to print “ Tutorials Point ” without using a semicolon
- Sum of the numbers up to N that are divisible by 2 or 5 in c programming
- Sum of the nodes of a Singly Linked List in C Program
- Sum of first n natural numbers in C Program
- C Program for simple interest?
- Area of a n-sided regular polygon with given Radius in C Program?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

The sum of squares of the first n natural numbers is found by adding up all the squares.

**Input **- 5**Output **- 55**Explanation **- 1^{2} + 2^{2} + 3^{2} + 4^{2} + 5^{2}

There are two methods to find the Sum of squares of first n natural numbers −

**Using Loops −** the code loops through the digits until n and find their square, then add this to a sum variable that outputs the sum.

#include <iostream> using namespace std; int main() { int n = 5; int sum = 0; for (int i = 1; i >= n; i++) sum += (i * i); cout <<"The sum of squares of first "<<n<<" natural numbers is "<<sum; return 0; }

The sum of squares of first 5 natural numbers is 55

**Using Formula **− To decrease the load on the program you can use mathematical formula to find the sum of squares on first n natural numbers. The mathematical formula is : n(n+1)(2n+1)/6

#include <stdio.h> int main() { int n = 10; int sum = (n * (n + 1) * (2 * n + 1)) / 6; printf("The sum of squares of %d natural numbers is %d",n, sum); return 0; }

The sum of squares of 10 natural numbers is 385

Advertisements