I want to print the following sequence. __* _*** ***** _*** __* Here _ denotes space. I have written half program to print upto 5 stars and not able to get for down. Code: #include <stdio.h> void main() { for(int i=1;i<=3;i++) { for(int j=1;j<=3-i;j++) printf(" "); for(int k=1;k<=(2*i-1);k++) printf("*"); printf("\n"); } } I can print below 5 stars by using two more for loops but I don't want to do it as it will include many loops which is not presentable.
One way to do it is to have a "command sequence" stored in a string, where each character instructs the program what to do next. So it displays 2 spaces, one star, CR, 1 space, 3 stars, CR and so on; you could represent this as Code: char seq[]="2113051321"; then have the program loop over that: the first character indicates the number of spaces, the second the number of stars, then display a CR, then repeat for the next two characters until you hit the end of the string. The nice thing about this is that when you get a new exercise all you have to do is change seq, so if for instance the next task is to display Code: ....* ...** ..*** .**** ***** you can implement this simply by specifying Code: char seq[]="4132231405"; Use this as a starting point: Code: int main() { char seq[]="2113051321"; int max=strlen(seq); for (int i=0; i<max; i+=2) { printf("Display %d spaces\n",seq[i]-'0'); printf("Display %d stars\n",seq[i+1]-'0'); printf("Display a CR\n"); } return EXIT_SUCCESS; } then all you need to do with this is to change each printf to do what the printf says, which you already know how to do.
you can do it like this stars--->1,3,.....,2*k+1 Code: #include <stdio.h> int main(){ int i,j,k,ii=0; for(i=0;i<5;i++){//5 lines to output if ((2*i+1)>5)//if we have more than 5 stars which is the maximum then ii--;//we decrease value by 1 in order to start backwards else ii=i; for (j=1;j<5-(ii+1);j++) printf(" "); for (k=1;k<=2*ii+1;k++) printf("*"); printf("\n"); } getchar(); }