Notice: Undefined offset: 13242321 in /var/www/html/qa-external/qa-external-users.php on line 744
The output for this program is showing wrong, but in turbo C it shows correct output. - OnlineGDB Q&A
Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

The output for this program is showing wrong, but in turbo C it shows correct output.

+9 votes
asked Dec 17, 2021 by SEENU M (210 points)
#include <stdio.h>

int main()
{
    int num,i,j;
    scanf("%d",&num);
    for(i=1;i<=num;i++)
    {
        for(j=1;i<=num;j++)
        {
            if(i==1 || j==1 || i==num || j==num)
            printf("*");
            else
            printf(" ");
        }
        printf("\n");
    }

    return 0;
}

4 Answers

+2 votes
answered Dec 17, 2021 by Areeb Sherjil (2,050 points)
Perhaps you made a typo at the second for loop, it should be 'for(j=1;j<=num;j++)' I think.

Have a look below:

https://onlinegdb.com/DvNwva24H

This works fine for me after fixing the issue.
0 votes
answered Dec 22, 2021 by Amogh Gupta (140 points)

your second loop of j is wrong, it should be

for(j=1;j<=num;j++)

0 votes
answered Oct 23, 2024 by (200 points)

#include <stdio.h>

int main()
{
    int num,i,j;
    scanf("%d",&num);
    for(i=1;i<=num;i++)
    {
        for(j=1;i<=num;j++)
        {
            if(i==1 || j==1 || i==num || j==num)
            printf("*");
            else
            printf(" ");
        }
        printf("\n");
    }

    return 0;
}

0 votes
answered Dec 2, 2024 by ???? ???? (220 points)
The issue in the nested for loop for variable j. You are using the condition i <= num instead of j <= num. This causes the inner loop to behave incorrectly, leading to unexpected output.

the corrected version:

#include <stdio.h>

int main()
{
    int num, i, j;
    scanf("%d", &num);
    for (i = 1; i <= num; i++)
    {
        for (j = 1; j <= num; j++)  // Corrected condition here
        {
            if (i == 1  j == 1  i == num || j == num)
                printf("*");
            else
                printf(" ");
        }
        printf("\n");
    }

    return 0;
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...