Reputation: 80
I am an absolute beginner to C.
Can you please explain me this problem correctly.
I am trying to print this pattern in C language using Iterative Approach
*
***
*****
So, I have to print this pattern but my code dont work.
And my code is printing this:
*****
*****
*****
My code:
#include <stdio.h>
int stars(int n) {
if(n==1){
printf("*");
return;
}
// i = 0 ; i<3; i++//
// 2*3-1 = 5
for(int i=0; i<n; i++){
for(int z=0; z<((2*n)-1) ; z++){
printf("*");
}
printf("\n");
}
}
int main() {
stars(3);
return 0;
}
Can you please explain me, why this is happening and what is the correct code for this pattern?
*
***
*****
Upvotes: 1
Views: 199
Reputation: 8318
Your problem is that in the second loop you always iterate for 2*n-1
you should iterate based on the iteration variable i
for(int z=0; z<((2*i)+1) ; z++)
The first loop that you wrote iterate on the number of lines, for each line you want a different amount of printf(“*”)
but if the number of iterations is constant (because n
Doesn’t change) the amount of printing will also be constant. This is the reason you printed the same amount of “*” for each line.
Upvotes: 2