C/Function should return a value in function Digits
Expert: Narendra - 6/13/2004
QuestionWrite a recursive function called Digits that take in an integer parameter num and return the number of digits in it. For example Digits(12345) returns 5.
#include<stdio.h>
int Digits(int);
void main()
{
int num;
printf("\nEnter number :");
scanf("%d",num);
printf("\nThere are %d digits in %d", Digits(num), num);
}
int Digits(int num)
{
if ( num>0)
return 1+ Digits(num/10);
}
********Can you let me know what's wrong for me? When I enter 12345, the program return there are 10 digits in 2147348480 *******
Regards,
Sophian
AnswerThere were 2 mistakes in the code. I have corrected them and here is the correct code. Just compile and run it and let me know if you still face problems:
#include<stdio.h>
int Digits(int);
main()
{
int num;
printf("\nEnter number :");
scanf("%d", &num);
printf("\nThere are %d digits in %d", Digits(num), num);
}
int Digits(int num)
{
if ( num>0) return 1+ Digits(num/10);
else return 0;
}
-ssnkumar