Easy Tutorial
❮ C Exercise Example53 C Pointer Arithmetic ❯

C Exercise Example 18

C Language Classic 100 Examples

Title: Calculate the value of s=a+aa+aaa+aaaa+aa...a, where a is a digit. For example, 2+22+222+2222+22222 (in this case, there are 5 numbers being added), and the number of terms to be added is controlled by the keyboard.

Program Analysis: The key is to calculate the value of each term.

Example

//  Created by www.tutorialpro.org on 15/11/9.
//  Copyright © 2015 tutorialpro.org. All rights reserved.
//

#include<stdio.h>
int main()
{
    int s=0,a,n,t;
    printf("Please enter a and n:\n");
    scanf("%d%d",&a,&n);
    t=a;
    while(n>0)
    {
        s+=t;
        a=a*10;
        t+=a;
        n--;
    }
    printf("a+aa+...=%d\n",s);
    return 0;
}

The output of the above example is:

Please enter a and n:
2 5
a+aa+...=24690

C Language Classic 100 Examples

❮ C Exercise Example53 C Pointer Arithmetic ❯