The given code is supposed to print the digits of the given number from left to right using recursion. Due to some errors, it fails to print the correct output. Fix the below code to print the desired output.
Sample Input:
428
Sample Output:
4
2
8
1
#include
2
void func(int n)
3
{
4
if(n <= 9){
5
std::cout<
6
}
7
func(n / 10);
8
std::cout<< n % 10<<"\n";
9
10
}
11
int main()
12
{
13
int n;
14
std::cin>>n;
15
func(n);
return 0;
}
Answers
Answered by
0
Answer:
You are mistaking at the line number 4 and 5 by writing the wrong base condition, rest of the code is fine.
Explanation:
See, for printing the digits of the given number, first you need to verify how long the given number is. For this the correct if condition should be,
if(n<10){
std::cout<<n;
}
This base condition will ensure if the given number is less than 10, it means it's a single digit number so there is no need to call the recursive function func anymore and terminate the program.
#SPJ3
Similar questions