Arsh Bhullar
Arsh Bhullar

Reputation: 63

Print a pattern using recursion in Swift

I want to print a pattern: first reduce 5 one by one until we reach 0 or negative and then we add 5 until we reach n.

I have tried this code but it stops at 10,5:

import Foundation

func printPattern(n : Int) {
    if n <= 0 {
        if n == n {
            return
        } else {
            print(n)
            printPattern(n: n + 5)
        }
    }

    if n > 0 {
        print(n)
        printPattern(n: n - 5)
    }
}

printPattern(n: 10)

I want the output to be 10,5,0,5,10.

Upvotes: 0

Views: 290

Answers (1)

vacawama
vacawama

Reputation: 154513

That would be:

func printPattern(n : Int) {

    if n <= 0 {
        print(n)
    }
    else {
        print(n)
        printPattern(n: n - 5)
        print(n)
    }

}

So with this call:

printPattern(n: 10)

The output is:

10
5
0
5
10

The first call to printPattern prints the two 10's.

The second call to printPattern prints the two 5's.

The third and final call to printPattern prints the 0.

The recursive call is nested between the two prints in each call which is how you get the pattern.

The calling sequence is like this:

printPattern(n: 10)
  print(10)
  printPattern(n: 5)
    print(5)
    printPattern(n: 0)
      print(0)  // base case
    print(5)  // upon return
  print(10) // upon return

What are you doing wrong in your function?

Your function appears to be attempting to judge the direction of adding/subtracting 5 based on whether the current value is positive or zero/negative. The problem with this is that you would get into a loop of printing 0 and 5 continuously switching directions. Since you pass 5 going both directions, you need some other way of indicating increasing vs. decreasing.

Your function is currently just outputting 10, 5 because when you get to 0, the check if n == n is always true. It is checking if 0 == 0, not if 0 == 10. If you want to check against the original value of n, you'll need to pass that as a separate input.

This is approximately what you were attempting:

func printPattern(n: Int, decreasing: Bool = true, start: Int? = nil) {
    // If there is no start value, use n
    let start = start ?? n

    // recursive base case
    if n > start {
        return
    }

    // if we're already increasing or we have reached zero/negative
    // time to increase
    if !decreasing || n <= 0 {
        print(n)
        printPattern(n: n + 5, decreasing: false, start: start)
    } else {
        // otherwise we are still decreasing
        print(n)
        printPattern(n: n - 5, decreasing: true, start: start)
    }

}

printPattern(n: 10)
10
5
0
5
10

Upvotes: 2

Related Questions