VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-a-pattern-without-using-any-loop/

⇱ Print a pattern without using any loop - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print a pattern without using any loop

Last Updated : 24 Feb, 2025

Given a number n, print the following pattern without using any loop.

n, n-5, n-10, ..., 0, 5, 10, ..., n+5, n

Examples :

Input: n = 16
Output: 16, 11, 6, 1, -4, 1, 6, 11, 16

Input: n = 10
Output: 10, 5, 0, 5, 10

We strongly recommend that you click here and practice it, before moving on to the solution.

Follow the given steps to solve the problem:

  • Create a recursive function with parameters as n and m and flag variable set as true
  • Print m and if the flag is false and the value of m is equal to n then return from the function
  • If the flag is true then check
    • If m-5 is greater than zero then recur for m-5
    • Else recur for m-5 and set the flag to false, as now we will be moving backward
  • Else recur for m+5

Below is the implementation of the above approach:


Output
16
11
6
1
-4
1
6
11
16

Time Complexity: O(N)
Auxiliary Space: O(N), stack space for the recursion

To solve the problem follow the below idea:

The above program works fine and prints the desired out but uses extra variables. We can use two print statements. The first one before the recursive call prints all decreasing sequences. The second one after the recursive call to print the increasing sequence

Below is the implementation of the above approach:


Output
16 11 6 1 -4 1 6 11 16 

Time Complexity: O(N)
Auxiliary Space: O(N), stack space for the recursion

Thanks to AKSHAY RATHORE for suggesting the above solution.

Comment
Article Tags: