
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
Sum of squares of first n natural numbers in C Program?
The sum of squares of the first n natural numbers is found by adding up all the squares.
Input - 5
Output - 55
Explanation - 12 + 22 + 32 + 42 + 52
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.
Example
#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; }
Output
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
Example
#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; }
Output
The sum of squares of 10 natural numbers is 385
- Related Articles
- C++ Program for Sum of squares of first n natural numbers?
- Python Program for Sum of squares of first n natural numbers
- Java Program to calculate Sum of squares of first n natural numbers
- Sum of first n natural numbers in C Program
- Sum of squares of the first n even numbers in C Program
- Sum of sum of first n natural numbers in C++
- C++ Program for cube sum of first n natural numbers?
- C Program for cube sum of first n natural numbers?
- Difference between sum of the squares of and square of sum first n natural numbers.
- Program for cube sum of first n natural numbers in C++
- Program to find sum of first n natural numbers in C++
- C Program for the cube sum of first n natural numbers?
- Python Program for cube sum of first n natural numbers
- Java Program to cube sum of first n natural numbers
- Java Program to Display Numbers and Sum of First N Natural Numbers

Advertisements