Posted on by Kalkicode
Code Recursion

# Print numbers from 1 to n using recursion

Recursion is a programming technique where a function calls itself to solve a smaller subproblem until a base case is reached. In this article, we will explore how to print numbers from 1 to N using recursion in Java.

## Problem Statement

Given a positive integer N, we need to print all the numbers from 1 to N using recursion.

## Example

Let's take N = 5 as an example. The expected output should be: 1 2 3 4 5

Similarly

``````Example N = 10
(1 to 10) :  1 2 3 4 5 6 7 8 9 10
Example N = 20
(1 to 20) :  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20``````

## Pseudocode

The recursive approach to print numbers from 1 to N can be represented using the following pseudocode:

``````function printNumber(num)
if num is greater than or equal to 1
Call printNumber(num - 1)  // Recursive call with a smaller problem
Print num  // Display the current number``````

## Algorithm Explanation

1. The `printNumber` function takes an integer `num` as its argument.
2. It checks if `num` is greater than or equal to 1, which is the base case for recursion.
3. If the base case is not reached, it calls the `printNumber` function recursively with `num - 1`.
4. The recursive call ensures that the numbers are printed in ascending order from 1 to `num`.
5. After the recursive call, the current value of `num` is printed on the console.

## Programming Solution

Recursion is a technique in programming where a function calls itself repeatedly until a specific condition is met. In this case, the function would call itself with decreasing values of n until it reaches 1, printing each value as it goes.

## Resultant Output Explanation

The code provided in the example prints the numbers from 1 to N (10 and 20 in this case) using the `printNumber` function. The `main` function initializes an instance of the `Numbers` class and calls the `printNumber` function with different values of `num`.

For `num = 10`, the output is "1 2 3 4 5 6 7 8 9 10". This output demonstrates that the recursive function is working correctly and printing the numbers in the expected order.

For `num = 20`, the output is "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20". Similarly, this output confirms that the function can handle larger values of `num` and still print the numbers from 1 to `num` correctly.

## Time Complexity

The time complexity of this recursive approach to print numbers from 1 to N is O(N). The function makes N recursive calls, and each call performs constant time operations (printing the number). As a result, the time complexity is linear with respect to N.

## Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

Categories
Relative Post