﻿ C exercises: Count the digits of a given number - w3resource

# C Exercises: Count the digits of a given number

## C Recursion : Exercise-5 with Solution

Write a program in C to count the digits of a given number using recursion.

Sample Solution:

C Code:

``````#include<stdio.h>

int noOfDigits(int n1);
int main()
{
int n1,ctr;
printf("\n\n count the digits of a given number :\n");
printf("-----------------------------------------\n");
printf(" Input  a number : ");
scanf("%d",&n1);

ctr = noOfDigits(n1);

printf(" The number of digits in the number is :  %d \n\n",ctr);
return 0;
}

int noOfDigits(int n1)
{
static int ctr=0;

if(n1!=0)
{
ctr++;
noOfDigits(n1/10);
}

return ctr;
}
```
```

Sample Output:

``` count the digits of a given number :
-----------------------------------------
Input  a number : 50
The number of digits in the number is :  2
```

Flowchart:

C Programming Code Editor:

```#include<stdio.h>

int noOfDigits(int n1);
int main()
{
int n1,ctr;
printf("\n\n count the digits of a given number :\n");
printf("-----------------------------------------\n");
printf(" Input  a number : ");
scanf("%d",&n1);

ctr = noOfDigits(n1);

printf(" The number of digits in the number is :  %d \n\n",ctr);
return 0;
}

int noOfDigits(int n1)
{
static int ctr=0;

if(n1!=0)
{
ctr++;
noOfDigits(n1/10);
}

return ctr;
}```

Improve this sample solution and post your code through Disqus.