c program recursion function count digit

C program to count digits of a number using recursion  :


Given an integer number and we have to count the digits using recursion using C program.

In this program, we are reading an integer number and counting the total digits, here countDigits()is a recursion function which is taking number as an argument and returning the count after recursion process.
Example:
    Input number: 1235
    Output:
    Total digits are: 4


Program to count digits in C using recursion code :

#include<stdio.h> int count(int n) { int cou,i; for(i=0;n!=0;i++){ cou=n%10; n=n/10; } return i; } int main() { int m; printf("Enter the number "); scanf("%d",&m); int bb=count(m); printf("count %d = %d",m,bb); }
OR code:
#include<stdio.h> int count(int n) { int cou,i; int con=0; for(i=0;n!=0;i++){ cou=n%10; con++; n=n/10; } return con; } int main() { int m; printf("Enter the number "); scanf("%d",&m); int bb=count(m); printf("count %d = %d",m,bb); }
OR code :

#include <stdio.h>
 
//function to count digits
int countDigits(int num)
{
    static int count=0;
     
    if(num>0)
    {
        count++;
        countDigits(num/10);
    }
    else
    {
        return count;
    }
}
int main()
{
    int number;
    int count=0;
     
    printf("Enter a positive integer number: ");
    scanf("%d",&number);
     
    count=countDigits(number);
     
    printf("Total digits in number %d is: %d\n",number,count);
     
    return 0;
}

output : 








No comments

Powered by Blogger.