Print the given pattern recursively


Here, as per the given problem pattern needs to be displayed using recursive approach.

Recursive function is the one that calls itself n number of times. There can be ‘n’ number of recursive function in a program. The problem working with recursive function is their complexity.

Algorithm

START
Step 1 -> function int printpattern(int n)
   If n>0
      Printpattern(n-1)
      Print *
   End IF
End
Step 2 -> function int pattern(int n)
   If n>0
      pattern(n-1)
   End IF
   Printpattern(n)
   Print \n
End
STOP

Example

#include <stdio.h>
int printpattern(int n) {
   if(n>0) {
      printpattern(n-1);
      printf("*");
   }
}
int pattern(int n) {
   if(n>0) {
      pattern(n-1); //will recursively print the pattern
   }
   printpattern(n); //will reduce the n recursively.
   printf("\n"); //for new line
}
int main(int argc, char const *argv[]) {
   int n = 7;
   pattern(n);
   return 0;
}

Output

if we run above program then it will generate following output.

*
**
***
****
*****
******
*******
raja
Published on 30-Jul-2019 08:51:13
Advertisements