trying to make 2 recursive functions

im having trouble with the code trying to get it to do what i want it to do
basically i want to input a number for example 123456 and get back how many 7's are in the input number and also to print out that same number with stars in between like this *1*2*3*4*5*6*


here is what i have so far
#include <iostream>
using namespace std;

int countSeven(int x){
if(x == 7)return 1;
int c = 0;
while(x/10 > 9)c++;
return countSeven(x/10)+1;
}

void printStarDigit(int x){
int a = 0;
while(x/10 > 0)a++;
cout << "*:"; << a << "*:";
}

int main(){
int input1 = 123456, input2 = 7, input3 = 171;
cout << countSeven(input1); //should output: 0
printStarDigit(input1); //should output: *1*2*3*4*5*6*
cout << countSeven(input2); //should output: 1
printStarDigit(input2); //should output: *7*
cout << countSeven(input3); //should output: 1
printStarDigit(input3); //should output: *1*7*1*
return 0;
}

when i compile it does not do what i tell it it just tells me there are 0 7's in the input number no matter how many there really are i would just like some help in the right direction thanks again
1
2
3
4
5
6
int countSeven(int x){
    if(x == 7)return 1;
    int c = 0;
    while(x/10 > 9)c++; //if x/10 is <= 9 this is an infinite loop
    return countSeven(x/10)+1;
}
Additionally, the function makes no logical sense - its name suggests that is should count the number of sevens, but it does nothing of the sort.

You have similar problems with your other functions.
ok so which specific part is wrong all of it or is it a specific line?
Last edited on
You're using recursion right, but you're not properly checking if the digit is a 7 or not. Do you know how to get just the right-most digit of a number?
yes i believe its x/10 to remove a digit
Indeed, x / 10 is how you remove the last digit.

But x % 10 is how you retrieve it, and you need to do that in order to check it... before you remove it.
ok ill try now and see what happens thanks
See this thread for the star problem: http://cplusplus.com/forum/beginner/99131/#msg532851

and check this one out looking for sevens: http://cplusplus.com/forum/general/99232/
is this correct now thanks again

#include <iostream>
using namespace std;
int countSeven(int x){
int c = 0;
int n = 0;
if(x == 7)return 1;
while(x/10 >= 9)n++;{
while(x%10 == 7)c++;{
return countSeven(c);
}
}
}
void printStarDigit(int x){
int a = 0;
while(x/10> 0)a++;
cout << "*"; << a << "*";
}


Please use the code tags correctly. And please edit your current posts in order to do so.
http://cplusplus.com/articles/jEywvCM9/

is this correct now thanks again

You're asking us? You can't run the program yourself and see if it works as expected or not?

I can see, however, that the printStarDigit() function shouldn't compile because it contains a stray semicolon ;.

Also, you may want to consult the links in booradley60's post.
Topic archived. No new replies allowed.