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
Registered users can post here. Sign in or register to post.
  • 452471514 2018-02-18
  • 5299351513 2018-02-18
  • 3036511512 2018-02-18
  • 4224301511 2018-02-18
  • 6975481510 2018-02-18
  • 8259761509 2018-02-18
  • 7007851508 2018-02-18
  • 7796301507 2018-02-18
  • 567811506 2018-02-18
  • 2107511505 2018-02-18
  • 8923811504 2018-02-17
  • 6039601503 2018-02-17
  • 8788931502 2018-02-17
  • 4539021501 2018-02-17
  • 661851500 2018-02-17
  • 9152461499 2018-02-17
  • 4757661498 2018-02-17
  • 981131497 2018-02-17
  • 4385321496 2018-02-17
  • 5046771495 2018-02-17