wanted:
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
my code
//THIS CODE IS NOT WORKABLE
#include<stdio.h>
int main() {
char arr[] = "* * * * *";
printf("%s\n", arr);
for (int i=1; i<5; i ) {
char sp[] = " "*i;
printf("%s\n", sp[i] arr);
}
return 0;
}
i do this in python:
aa = '* * * * *'
print(aa)
for i in range(1,5):
print(' '*i aa)
--> how to fix this in c? looking forward some python-like style code in c(as simple as possible)
CodePudding user response:
There is no an equivalent binary operator * in C as in Python that allows to propagate a string.
But in any case your approach even in Python is not flexible because it deals with the fixed string "* * * * *".
To output the pattern in C you should use loops as for example shown in the demonstration program below.
#include <stdio.h>
int main( void )
{
while ( 1 )
{
const char c = '*';
printf( "Enter a non-negative number (0 - exit ): " );
int n = 0;
if ( scanf( "%d", &n ) != 1 || n <= 0 ) break;
putchar( '\n' );
for ( int i = 0; i < n; i )
{
printf( "%*c", 2 * i 1, c );
for ( int j = 1; j < n; j ) printf( " %c", c );
putchar( '\n' );
}
putchar( '\n' );
}
}
The program output might look like
Enter a non-negative number (0 - exit ): 1
*
Enter a non-negative number (0 - exit ): 2
* *
* *
Enter a non-negative number (0 - exit ): 3
* * *
* * *
* * *
Enter a non-negative number (0 - exit ): 4
* * * *
* * * *
* * * *
* * * *
Enter a non-negative number (0 - exit ): 5
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
Enter a non-negative number (0 - exit ): 0
