1. Introduction
The butterfly pattern is an interesting figure in pattern programming that visually represents a butterfly using stars (*). This pattern is symmetrical about its center line and combines simple programming concepts like loops and conditionals in a creative way. In this blog post, we'll explore how to create a butterfly pattern of stars in C programming, demonstrating the use of nested loops to achieve complex patterns.
2. Program Steps
1. Request the number of rows from the user, which will determine the size of the butterfly.
2. Use nested loops to print the top half of the butterfly, consisting of stars and spaces.
3. Implement similar logic to print the bottom half of the butterfly, ensuring symmetry with the top half.
4. Manage spaces and star printing carefully to achieve the desired pattern.
3. Code Program
#include <stdio.h>
int main() {
int i, j, n;
// User input for the number of rows
printf("Enter the number of rows: ");
scanf("%d", &n);
// Printing the top half of the butterfly
for(i = 1; i <= n; i++) {
// Print left wing
for(j = 1; j <= i; j++) {
printf("*");
}
// Print spaces in the middle
for(j = 1; j <= 2*(n-i); j++) {
printf(" ");
}
// Print right wing
for(j = 1; j <= i; j++) {
printf("*");
}
printf("\n");
}
// Printing the bottom half of the butterfly
for(i = n; i >= 1; i--) {
// Print left wing
for(j = 1; j <= i; j++) {
printf("*");
}
// Print spaces in the middle
for(j = 1; j <= 2*(n-i); j++) {
printf(" ");
}
// Print right wing
for(j = 1; j <= i; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
Output:
Enter the number of rows: 4 * * ** ** *** *** ******** ******** *** *** ** ** * *
Explanation:
1. The program starts by including the stdio.h header file for input and output functions.
2. The main function begins by declaring integer variables i, j, and n. n is used to store the number of rows, which determines the size of the butterfly.
3. The user is prompted to enter the number of rows for the butterfly pattern.
4. The first for loop iterates from 1 to n, printing the top half of the butterfly. For each row, it prints stars for the left wing, spaces to create the gap between the wings, and stars for the right wing.
5. The second for loop iterates from n to 1, printing the bottom half of the butterfly. It follows a similar pattern as the top half but in reverse order to create the symmetrical bottom half.
6. The inner loops for printing stars and spaces are carefully managed to ensure the correct number of each is printed, creating the butterfly's wings and the gap between them.
7. The program ends with return 0;, signaling successful execution.
Comments
Post a Comment