
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ Program for Sum of squares of first n natural numbers?
In this problem we will see how we can get the sum of squares of first n natural numbers. Here we are using one for loop, that runs from 1 to n. In each step we are calculating square of the term and then add it to the sum. This program takes O(n) time to complete. But if we want to solve this in O(1) or constant time, we can use this series formula −
Algorithm
squareNNatural(n)
begin sum := 0 for i in range 1 to n, do sum := sum + i^2 done return sum end
Example
#include<iostream> using namespace std; long square_sum_n_natural(int n) { long sum = 0; for (int i = 1; i <= n; i++) { sum += i * i; //square i and add it with sum } return sum; } main() { int n; cout << "Enter N: "; cin >> n; cout << "Result is: " << square_sum_n_natural(n); }
Output
Enter N: 4 Result is: 30
- Related Articles
- Python Program for Sum of squares of first n natural numbers
- Sum of squares of first n natural numbers in C Program?
- Java Program to calculate Sum of squares of first n natural numbers
- Python Program for cube sum of first n natural numbers
- 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.
- C Program for the cube sum of first n natural numbers?
- Program for cube sum of first n natural numbers in C++
- Sum of first n natural numbers in C Program
- Sum of squares of the first n even numbers in C Program
- Java Program to cube sum of first n natural numbers
- Java Program to Display Numbers and Sum of First N Natural Numbers
- Sum of sum of first n natural numbers in C++
- 8085 program to find the sum of first n natural numbers

Advertisements