Reputation: 69
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
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;
}
scanf
format specifier changed to " %c"
to consume the '\n'
left into stdin
by first scanf
5
times, so condition was changed to <=
due to the started value that is 1
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
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