Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why star pattern work with one code and doesn't work with another code? Logic is same

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading