You are here:

C/Function should return a value in function Digits

Advertisement


Question
Write 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

Answer
There 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

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.