- 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

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 −

begin sum := 0 for i in range 1 to n, do sum := sum + i^2 done return sum end

#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); }

Enter N: 4 Result is: 30

Advertisements