Home  >  Article  >  Backend Development  >  What is the sum of the squares of the first n natural numbers in the C program?

What is the sum of the squares of the first n natural numbers in the C program?

WBOY
WBOYforward
2023-08-31 15:25:061296browse

What is the sum of the squares of the first n natural numbers in the C program?

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

Input- 5

Output- 55

Explanation- 12 22 32 42 52

There are two ways to find the first n natural numbers Sum of squares -

Using a loop -The code loops through the numbers until n and finds their squares, then adds it to the 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

Use formula- To reduce the load on your program, you can use mathematical formulas to calculate the squares of the first n natural numbers and. 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

The above is the detailed content of What is the sum of the squares of the first n natural numbers in the C program?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete