user14384773
user14384773

Reputation:

Printing star patterns using recursion is showing an extra line

#include<stdio.h>

void printPattern(int n);

int main() {
    int n =4;    
    printPattern(n);
    return 0;
}

void printPattern(int n){
    if (n=1){
        printf("*\n");
        return;
    }

    printPattern(n-1);

    for(int i=0;i< (2*n-1);i++){
        printf("*");
    }
    printf("\n");
}

Here, the value of n is 4 so in void function if statement shouldn't work because n is not equal to 1 and it will not print *, but if you run the code it will print * and I don't know why. The n value is 4 so it should skip that if statement and then n value will become 3 because of printPattern(n-1) and then it will print 1-3-5 stars in 1-2-3rd lines

*   
*** 
*****

But if you run the code it will print 1-3-5-7 stars in 1-2-3-4th lines

*  
***  
*****  
*******

The loop occurs after the recursion so it should print 3 lines (1-3-5 stars) instead of 4 lines (1-3-5-7 stars) also here in this code, if statement is used without else.

I was learning to print odd number of star per line in increasing order using recursion from Youtube, can anybody explain this to me.

Upvotes: 1

Views: 2792

Answers (1)

Chandra Sekhar Bala
Chandra Sekhar Bala

Reputation: 241

if(n=1) or ( n==1) your program is all okay! just a tiny mistake :p

Upvotes: 1

Related Questions