Home > Backend Development > C++ > body text

C programming code to sum the sequence 2, 22, 222,...

WBOY
Release: 2023-09-11 10:25:02
forward
816 people have browsed it

C programming code to sum the sequence 2, 22, 222,...

Given a sequence: 2,22,222,2222..., we need to find the sum of this sequence. Therefore, we have to find the mathematical formula for finding the sum of a series,

The explanation of the formula is like this-

sum =[2+22+222+2222….]
sum= 2*[1+11+111+1111….]
Sum = 2/9[9+99+999+9999….]
sum= 2/9 [10+100+1000+10000+.....]
sum = 2/9[10+10<sup>2</sup>+10<sup>3</sup>+10<sup>4</sup>+.....]
sum=2/9*[(10<sup>n</sup>-1-9n)/9]
Copy after login

Example

#include <stdio.h>
#include <math.h>
int main() {
   int n = 3;
   float sum = 2*(pow(10, n) - 1 - (9 * n))/81;
   printf("sum is %d", sum);
   return 0;
}
Copy after login

Output

sum is 879
Copy after login

The above is the detailed content of C programming code to sum the sequence 2, 22, 222,.... For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!