using recursion

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • w041bxc
    New Member
    • Oct 2013
    • 1

    using recursion

    Write a program that will print a figure, like the following, recursively. Prompt the user to enter n, the number of asterisks in the first (and last) row. In the example, n = 4.
    ****
    ***
    **
    *
    **
    ***
    ****

    ------------------------------------
    THIS IS WHAT i HAVE SO FAR:

    Code:
    #include<stdlib.h>
    #include<stdio.h>
    #include <math.h>
    
    void print(int n);
    
    int main(void)
    {
    
        int n;
    
        printf("Enter n with the keyboard>> ");
        scanf("%d",&n);
        //n = n-1;
    
        print(n);
        printf("\n");
        printf("*\n");//print one star
    
    
        int i;
    
        for (i = 0; i <n; i++ )
        {
          printf("*");
        }
    
    
    }
    void print(int n)
    {
        int i = 0;
        if (n ==1)
        {
            printf("\n*\n");
        }
        else {
            for (i = 0; i <n; i++ )
            {
                printf("*");
            }
           printf("\n");
    
        }
    
        n = n-1;
        //
       // print(n);
    
        for (i = 0; i < n; i++ )
            {
                printf("*");
            }
            //n = n-1;
    
        //printf(n); <-----------------------HAVE NO IDEA TO DO RECURSION HERE!!!
    any help will be appreciated!!!
    Last edited by Banfa; Nov 12 '13, 09:34 AM.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    The general pattern for a recursive function is

    Code:
    void recursiveFunction(<parameters>) // Note the reutrn value is not necessarily void
                                         // But it makes sense in this case
    {
      if (EndCondition Is True)
      {
        return;
      }
    
      // Do some stuff here
    
      recursiveFunction(<Altered Parameters for next recursion>);
    }
    Also note that because of the pattern you are outputting knowing the line number in the pattern is not enough to know what to output, you will need to know the total number of lines or the number of asterisks on the first and last row (which are basically the same thing) so your recursive function will need at least 2 parameters, one of which wont change.

    You could implement this with 2 recursive functions, 1 to recurs through the lines and another which it calls to print each individual line.

    Comment

    Working...