Home > Backend Development > C++ > 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
Release: 2023-08-31 15:25:06
forward
1386 people have browsed it

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;
}
Copy after login

Output

The sum of squares of first 5 natural numbers is 55
Copy after login

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;
}
Copy after login

Output

The sum of squares of 10 natural numbers is 385
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template