11.11 LAB: Number pattern Write a recursive function 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. For this lab, do not end output with a newline. Ex. If the input is:

Respuesta :

Answer:

The function in C++ is as follows:

int itr, kount;

void printNumPattern(int num1,int num2){

   if (num1 > 0 && itr == 0) {

       cout<<num1<<" ";

       kount++;

       printNumPattern(num1 - num2, num2);

   } else {

       itr = 1;

       if (kount >= 0) {

           cout<<num1<<" ";

           kount--;

           if (kount < 0) {

               exit(0);}

               printNumPattern(num1 + num2, num2);}}

}

Explanation:

We start by declaring global variables itr and kount

int itr, kount;

The function is defined here

void printNumPattern(int num1,int num2){

If num1 and itr are greater than 0 , then

   if (num1 > 0 && itr == 0) {

Output num1, followed by a space

       cout<<num1<<" ";

Increment counter by 1

       kount++;

Call the recursion

       printNumPattern(num1 - num2, num2);

If otherwise

   } else {

Set itr to 1

       itr = 1;

If counter is 0 or positive

       if (kount >= 0) {

Output num1, followed by a space

           cout<<num1<<" ";

Decrease counter by 1

           kount--;

If counter is negative

           if (kount < 0) {

Exit function

               exit(0);}

Call the recursion

              printNumPattern(num1 + num2, num2);}}

}

tonb

Answer:

void PrintNumPattern(int start, int delta) {

cout << start << " ";

if (start > 0) {

 PrintNumPattern(start - delta, delta);

 cout << start << " ";

}

}

void main()  

{  

PrintNumPattern(12, 3);

}

Explanation:

Looking at the "palindrome" symmetry of the output, you want one nesting level of the function to print the output twice. Then you also don't need global variables.