Home >Backend Development >C++ >C programming code to sum the sequence 2, 22, 222,...

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

WBOY
WBOYforward
2023-09-11 10:25:02915browse

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]

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

Output

sum is 879

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!

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