Function printNto1 – CTS PATTERN
Print numbers from N down to 1 using recursion without modifying the original function signature
Understand the Problem
Problem Statement
You are required to fix all the logical errors in the given code. You can click on Run anytime to check the compilation/execution status of the program. You can use printf to debug your code. The submitted code should be logically/syntactically correct and pass all test cases. Do not write the main() function as it is not required.
Code Approach: For this question, you will need to correct the given implementation. We do not expect you to modify the approach or incorporate any additional library methods.
The function printNto1(int num) accepts an integer num as the input. It is supposed to print the numbers from N to 1.
Your task is to fill in the missing lines of code so that the program passes all test cases.
Constraints
- Input number must be a positive integer
- Function should handle base case when num becomes 0 or negative
- Output should print numbers separated by spaces
- Function signature must remain exactly as: void printNto1(int num)
- No additional library functions should be used
- Recursion depth is limited by system stack size (typically safe up to thousands)
Examples
55 4 3 2 1Starting from 5, the function prints each number in descending order until reaching 1.
33 2 1Starting from 3, the function prints each number in descending order until reaching 1.
11When starting from 1, only the number 1 is printed since it's the base case.
Solution
void printNto1(int num)
{
if(num >= 1){
printf("%d ", num);
printNto1(num - 1);
}
}The C solution uses recursion with a simple base case check. The function first checks if num >= 1. If true, it prints the current number using printf with a space, then makes a recursive call with num - 1. This continues until num becomes 0 or negative, at which point the recursion stops. This approach ensures numbers are printed in descending order from N to 1.