user3797489
user3797489

Reputation: 69

getting wrong answer in pattern printing program

I have written the code to print a pattern in C. My expected answer is very different from the one that I am getting .I am very new to C language. I have debugged the code but unable to find the error. Please help me in finding the error. My code is as follows.

#include <stdio.h>

int main() 
{
    //code
    int T,i,j;

    scanf("%d",&T);

    while(T--)
    {
        char str[5];
        for(i=0;i<5;i++)
        {
            scanf("%c",&str[i]);
        }
        printf("\n");

        for(j=1;j<=5;j++)
        {
            for(i=0;i<5-j;i++)
            {
                printf(".");
            }
            for(i=0;i<j;i++)
            {
                printf("%c",str[i]);
            }
        }
        printf("\n");
    }
    return 0;
}

The input to the program is as follows:
Input:

1
geeks

The expected output of the program is as follows:
Expected output:

....g
...ge
..gee
.geek
geeks

The actual output of the program is as follows:
Actual output:

....
...
g..
ge.
gee

Upvotes: 1

Views: 115

Answers (2)

LPs
LPs

Reputation: 16213

Correcting your bad code

#include <stdio.h>

int main()
{
    //code
    int T,i,j;

    scanf("%d",&T);

    while(T--)
    {
        char str[5];
        for(i=0;i<5;i++)
        {
            scanf(" %c",&str[i]);
        }
        printf("\n");

        for(j=1;j<=5;j++)
        {
            for(i=0;i<5-j;i++)
            {
                printf(".");
            }
            for(i=0;i<j;i++)
            {
                printf("%c",str[i]);
            }
            printf("\n");
        }
    }
    return 0;
}
  1. chars scanf format specifier changed to " %c" to consume the '\n' left into stdin by first scanf
  2. The outer for loop must loop 5 times, so condition was changed to <= due to the started value that is 1
  3. Moved printf("\n"); inside the outer for loop.

INPUT

1
geeks

OUTPUT

....g
...ge
..gee
.geek
geeks

other test

INPUT

2
1234567890

OUTPUT

....1
...12
..123
.1234
12345

....6
...67
..678
.6789
67890

Upvotes: 3

ReshaD
ReshaD

Reputation: 946

This can be solve your problem:

int main()
{
//code
int T,i,j;
scanf("%d",&T);
while(T--)
{
    char str[5];
    for(i=0; i<5; i++)
    {
        scanf(" %c",&str[i]);  //first modification
    }
    printf("\n");

    for(j=1; j<=5; j++)  //second modification
    {
        for(i=0; i<=5-j; i++)
        {
            printf(".");
        }
        for(i=0; i<j; i++)
        {
            printf("%c",str[i]);
        }
    }
    printf("\n");
}
return 0;
}

Upvotes: 0

Related Questions