59.4k views
2 votes
Write a recursive method called printNumPattern() to output the following number pattern. Given a positive integer as input (Ex: 12), subtract another positive integer (Ex: 3) continually until 0 or a negative value is reached, and then continually add the second integer until the first integer is again reached. Ex. If the input is:

2 Answers

1 vote

Answer:
def print_num_pattern(num1, num2):

if num1 <= 0:

print(num1, end=" ")

return

print(num1, end=" ")

print_num_pattern(num1 - num2, num2)

print(num1, end=" ")

if __name__ == "__main__":

num1 = int(input())

num2 = int(input())

print_num_pattern(num1, num2)

Step-by-step explanation:
define the function print_num_pattern
- ensure to set the first print function to print the num1 to ensure the proper function of the code

User Brandonhilkert
by
7.6k points
3 votes

Answer:

See Explanation Below

Step-by-step explanation:

// C++ printNumPattern() recursive method

// Comments are used for explanatory purpose

// Only the recursive is submitted

// Method starts here

void printPattern(int num1, int num2, bool dec)

{

// Print num2.

cout << num2 << " ";

//Printing to num1

if (dec == false && num1 ==num2) {

return; }

// Printing to 0 or negative.

if (dec)

{

// If num2 is greater than num2

if (num2-num1 > 0)

printPattern(num1, num2-num1, true);

else // recur with false dec

printPattern(num1, num2-num1, false);

}

else // If dec is false.

printPattern(num1, num2+num1, false);

}

//End of recursive

User Alex Bender
by
6.9k points