Recursion- counting numbers- homework

hi guys!
its supposed to do this:
4. Recursion. Write a recursive function called digits that will return the number of digits in its parameter of type long. Your function should work for arguments that are negative or zero as well as positive.

but only returns 0!
i have no clue why its doing this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  #include <iostream>
using namespace std;

long digits (long);

int main(){
	long number, count;
	 
	 cout << "Enter an integer number (negative or zero is ok): ";
	 cin >> number;
	
	count = digits (number);
	 
	cout << "The number of digits in number "<<number<<" is " << count;
	
	return 0;
}

long digits (long number){
	
	int count; 
	
	if (number > 0){
		count+=1;
		digits(number/10);
	}
	
	else {
		return count;
	}
}
}
You need to think about the logic.
What will happen when number is -10 or 0 ?
What value will be returned ?
Maybe do this first with pen and paper.
the problem is each time digits gets called it sets count to a garbage value in most cases it seems to be 0,but you should always initialise variables,the logic is correct apart from entering 0 or a minus number then the if statement will never execute and the function will just return so changed it to enter a number greater than 0

what you want to do is put count outside the digits function so it won't be re-initialised each time the function is called

this should work

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

#include <iostream>
using namespace std;

int digits (int);

int main(){
	int number, coun; // changed count to coun probably better to pick a more suitable name but just named it that for demonstration 

	 cout << "Enter an integer number (negative or zero is ok): ";
	 cin >> number;

	coun = digits(number);

	cout << "The number of digits in number "<<number<<" is " << coun;

	return 0;
}

int count = 0;

int digits(int number){

	if (number > 0){
        count++;
		digits(number/10);
	}
		return count;
}



but to be honest you have the right idea
Last edited on
Topic archived. No new replies allowed.