ADVERTISEMENT
ADVERTISEMENT

C program to count digits of a number using recursion

In this C program, we are going to learn how to count total number of 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: 123
    Output:
    Total digits are: 3

Program to count digits in C using recursion

/*C program to count digits using recursion.*/
 
#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

Enter a positive integer number: 123
Total digits in number 123 is: 3 

C Recursion Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.