I’m trying to solve Star problem. And I always thought it’s good practice not to declare empty variable in the beginning.
when I declare variables and assign some value at the beginning it doesn’t work
here is the code where i=1,j=1,space=1
#include<stdio.h>
int main()
{
int i=1,space=1,j=1,rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i;i<=rows;i++)
{
for(space;space<=rows-i;space++)
{
printf(" ");
}
for(j;j<=2*i-1;j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
BUT when I only declare variables and assign value in for loop it does work
#include<stdio.h>
int main()
{
int i,space,j,rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1;i<=rows;i++)
{
for(space=1;space<=rows-i;space++)
{
printf(" ");
}
for(j=1;j<=2*i-1;j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Why it’s happening? I always thought it’s a good practice to declare variables and assign some value to them
>Solution :
In first case space and j doesn’t reinit in parent for loop, while in the second example every parent loop iteration you reassign j = 1 and space = 1
So, on start of second iteration j and space will be the same as were on the finish of first iteration, so nested loops won’t work