Here we will see how to generate hollow pyramid and diamond patterns using C language. We can easily generate a solid pyramid pattern. To make it hollow, we need to add a few tricks.
For the pyramid in the first row, it will print one asterisk and n asterisks in the last row. For other lines, it will print two asterisks at the beginning and end of the line, with some space between the two asterisks.
#includeint main() { int n, i, j; printf("Enter number of lines: "); scanf("%d", &n); for(i = 1; i<=n; i++) { for(j = 1; j<=(n-i); j++){ //print the blank spaces before star printf(" "); } if(i == 1 || i == n){ //for the first and last line, print the stars continuously for(j = 1; j<=i; j++) { printf("* "); } } else { printf("*"); //in each line star at start and end position for(j = 1; j<=2*i-3; j++) { //print space to make hollow printf(" "); } printf("*"); } printf(" "); } }
Enter number of lines: 20 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
For the first and last row of diamonds, it will print a star. For other lines it will print two stars at the beginning and end of the line and there will be some space between the two beginnings. A diamond has two parts. Upper and lower halves. In the upper half we have to increase the number of spaces, and in the lower half we have to decrease the number of spaces. Here, you can use another variable called mid to split the line number into two parts.
#includeint main() { int n, i, j, mid; printf("Enter number of lines: "); scanf("%d", &n); if(n %2 == 1) { //when n is odd, increase it by 1 to make it even n++; } mid = (n/2); for(i = 1; i<= mid; i++) { for(j = 1; j<=(mid-i); j++){ //print the blank spaces before star printf(" "); } if(i == 1) { printf("*"); } else { printf("*"); //in each line star at start and end position for(j = 1; j<=2*i-3; j++){ //print space to make hollow printf(" "); } printf("*"); } printf(" "); } for(i = mid+1; i
"); }
Enter number of lines: 15 * * * * * * * * * * * * * * * * * * * * * * * * * * * *
The above is the detailed content of C program to print hollow pyramid and rhombus patterns. For more information, please follow other related articles on the PHP Chinese website!