Program to find number of character

Program to find number of character

Question

Write a program to find number of character. Given a number n, write all the numbers from 1 to n in a paper. We have to find the number of characters written on the paper. For example, if n=13, the output should be 17 if n=101, the output should be 195.

Logic

  • No. of character of each integer is one till 9, after that till 99 it is two.
  • So we are assigning ‘constant’=10.
  • If we reach 10, multiply by 10(‘constant’ =100), then make the add two( ‘add’= 2)
  • Else add the ‘add’ to the sum.
  • Repeat the same process till the limit.

 

#include<stdio.h>
int main()
{
    int limit,i,sum=0,add=1,constant=10;			  // add->no.of characters sum->total no.of chracters in paper
     printf("enter limit");
     scanf("%d",&limit);
     for(i=1;i<=limit;i++)
     {
         if(i==constant)
        {   /*for ex: till 9 add is 1
              when i=10
              no.of character in integer becomes 2
              so increment no. of characters for each integer(add)*/
            add =add+1;

            /*change the constant
              for ex: 10->100*/
            constant =constant*10;

         }

         sum+= add;                         			//adding 'add' for each integer within limit

     }

    printf("%d",sum);

    return 0;
}

You might also like…

Count of each character in a string

C program to find count of specific character

Follow For Instant Updates

Join WhatsApp Group: link
Join our Telegram Channel: link
Like our Facebook Page:  link
Subscribe to our Youtube channel: link

Sree Hari Sanjeev

The founder of Wisdom Overflow. Software Developer at Zoho Corporation.
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x