Note that for an integer x, x % 10 gives you the ones digit and x / 10 gives you everything but the ones digit.
ie, 1234 % 10 == 4, 1234 / 10 = 123. Perhaps you could repeatedly divide by 10 until... and count something...
FYI, nobody's going to write your code for you. jsmith gave some very good information.
Think about it some, attempt a function on your own, post it here for us to look at, and we'll be glad to help you tweak it some to get it right...but you have to try first. :-)
Just include <cmath> and then use the log function and add 1 and truncate.
For example:
log(1234)~=3.0913151596972228772592050619999
add 1: 4.0913151596972228772592050619999
truncate: 4
So long as you do not have numbers greater than zero and they are integers this trick will work. Including decimal places can get a little bit trickier.
HAHA, that's priceless. Especially since tifa is obviously using this site to do his homework for him. Too bad that solution doesn't utilize recursion. His teacher would freak out.
Every invocation of digit() gets its own local variable count, so every invocation returns 2 (you increment
count [to 1], then return the value of count plus 1.
When does digit() stop recursing?
You call digit with 584. That digit() then calls digit() with 584/10 = 58. THAT digit() then calls digit() with 58/10 = 5.
THAT digit() then calls digit() with 5/10 = 0. THAT digit() then calls digit() with 0/10 = 0. THAT digit() then calls
digit() with 0/10 = 0. ... etc...
Ooops... didn't notice "recursive" so I guess if he could recursively define log I guess.... but thats just too much work, oh well. Maybe he should ask the teacher for help if he is doing his homework.
#include<iostream>
#include<conio.h>
using namespace std;
int digit(int);//function proto type.
int main()
{
int num;
cout<<"Enter any number";
cin>>num;
cout<<"The number contain "<<digit(num)<<"digits"<<endl;
cin>>num;
cout<<digit(num)<<endl;
cin>>num;
cout<<digit(num)<<endl;
getch();
return 0;
}
int digit(int n)
{
static int count=0;
if((n/10)==0)
count=0;
else
{