So, the output should come out with a incrementing triangle of looped numbers (1,2,3,...) combined with a decrementing triangle of stars. Like this:
1********
12*******
123******
1234*****
12345****
123456***
1234567**
12345678*
123456789
So far I have this but just can't figure out how to decrement the stars.
#include <stdio.h>
int main()
{
int i, j;
for(i=1; i<=9; i )
{
for (j=1; j<=i; j )
{
printf ("%d",j);
}
int k;
for(k=8; k>0; k--) {
printf("*");
}
printf("\n");
}
}
And it prints out this:
1*******
12*******
123*******
1234*******
12345*******
123456*******
1234567*******
12345678*******
123456789*******
CodePudding user response:
You have:
- For k in 8 down to 0 (exclusive),
- Print
*
.
- Print
This always prints 8 stars, but you want 9-i of them.
- For k in i 1 to 9 (inclusive),
- Print
*
.
- Print
CodePudding user response:
Note that all you need to do is subtract the amount of numbers printed per line from the expected (in this case) 9 expected characters. for(k=9 - i; k>0; k--)
#include <stdio.h>
int main()
{
int i, j;
for(i=1; i<=9; i ){
for (j=1; j<=i; j ){
printf ("%d",j);
}
int k;
for(k=9 - i; k>0; k--) {
printf("*");
}
printf("\n");
}
}
Outputs:
1********
12*******
123******
1234*****
12345****
123456***
1234567**
12345678*
123456789
CodePudding user response:
printf
has the built in ability to print only limited portions of a string.
That comes in EXTREMELY handy for problems like this:
#include <stdio.h>
int main(void) {
int i=9;
while(i --> 0)
{
printf("%.*s%.*s\n", 9-i, "123456789", i, "********");
}
return 0;
}
Output
1********
12*******
123******
1234*****
12345****
123456***
1234567**
12345678*
123456789