Tuesday, 2 February 2021

Convert nested loops into recursion in C, patterns using recursion

 #include <stdio.h>

int main()
{
    int r,c, n,nr,nc,c1=1,c2=1;
    scanf("%d", &n);
    nr=2*n-1;
    nc=2*n-1;
    for(r=1;r<=nr;r++)
    {
        for(c=1;c<=nc;c++)
        {
            if(c<c1||c>c2)
                printf(" ");
            else
                printf("*");
        }
        if(r<n)
        {
            c1++;
            c2=c2+2;
        }
        else
        {
            c1--;
            c2=c2-2;
        }
        printf("\n");
    }
}

Consider a nested loop as shown above..
First i tried converting inner c loop into recursion and i got this code below

#include <stdio.h>

void loop(int c,int nc,int c1,int c2)
{
    if(c>nc)
        return;
    if(c<c1||c>c2)
        printf(" ");
    else
        printf("*");
    loop(c+1,nc,c1,c2);
}

int main()
{
    int r,c, n,nr,nc,c1=1,c2=1;
    scanf("%d", &n);
    nr=2*n-1;
    nc=2*n-1;
    for(r=1;r<=nr;r++)
    {
        loop(1,nc,c1,c2);
        if(r<n)
        {
            c1++;
            c2=c2+2;
        }
        else
        {
            c1--;
            c2=c2-2;
        }
        printf("\n");
    }
}

Now further converting outer r loop the program would like this as shown below

#include <stdio.h>

void loop(int c,int nc,int c1,int c2)
{
    if(c>nc)
        return;
    if(c<c1||c>c2)
        printf(" ");
    else
        printf("*");
    loop(c+1,nc,c1,c2);
}
void pattern(int r,int n,int c1,int c2)
{
    if(r>2*n-1)
        return;
    loop(1,2*n-1,c1,c2);
    if(r<n)
    {
        c1++;
        c2=c2+2;
    }
    else
    {
        c1--;
        c2=c2-2;
    }
    printf("\n");
    pattern(r+1,n,c1,c2);
    
}
int main()
{
    int r,c, n,nr,nc,c1=1,c2=1;
    scanf("%d", &n);
    nr=2*n-1;
    nc=2*n-1;
    pattern(1,n,c1,c2);
}

Further can be improved as
#include <stdio.h> void loop(int c,int nc,int c1,int c2) { if(c>nc) return; if(c<c1||c>c2) printf(" "); else printf("*"); loop(c+1,nc,c1,c2); } void pattern(int r,int n,int c1,int c2) { if(r>2*n-1) return; loop(1,2*n-1,c1,c2); if(r<n) { printf("\n"); pattern(r+1,n,c1+1,c2+2); } else { printf("\n"); pattern(r+1,n,c1-1,c2-2); } } int main() { int r,c, n,nr,nc,c1=1,c2=1; scanf("%d", &n); nr=2*n-1; nc=2*n-1; pattern(1,n,c1,c2); }

No comments:

Post a Comment