Butterfly Pattern in C Programming of Numbers using for loop
Butterfly pattern in c programming of numbers using for loop. In this article, you will learn how to print the butterfly pattern in c programming of the numbers using for loop statement.
Example
-----Enter the height of the pattern-----
6
-----This the butterfly pattern-----
1 1
1 2 2 1
1 2 3 3 2 1
1 2 3 4 4 3 2 1
1 2 3 4 5 5 4 3 2 1
1 2 3 4 5 6 6 5 4 3 2 1
1 2 3 4 5 5 4 3 2 1
1 2 3 4 4 3 2 1
1 2 3 3 2 1
1 2 2 1
1 1
You should have knowledge of the following topics in c programming to understand this program:
- C
main()
function - C
printf()
function - C
for
loop statement - C
putchar()
function
In this program, we used normal functions and statements to print the butterfly pattern in C language.
Source Code
// Butterfly Pattern in C Programming of Numbers using for loop
#include <stdio.h>
int main() {
int r, h, d, s;
// r - denotes for pattern row
// h - denotes for pattern height
// d - denotes for digits
// s - denotes for space
printf("-----Enter the height of the pattern-----\n");
scanf("%d", &h);
printf("\n-----This the butterfly pattern-----\n\n\n");
for(r = 1; r <= h - 1; r++) {
printf("\t");
for(d = 1; d <= r; d++)
printf("%d ", d);
for(s = 1; s <= 2 * (h - r); s++)
printf(" ");
putchar('\b');
for(d = r; d >= 1; d--)
printf(" %d", d);
putchar('\n');
}
for(r = h; r >= 1; r--) {
printf("\t");
for(d = 1; d <= r; d++)
printf("%d ", d);
for(s = 1; s <= 2 * (h - r); s++)
printf(" ");
putchar('\b');
for(d = r; d >= 1; d--)
printf(" %d", d);
putchar('\n');
}
return 0;
}
Output
-----Enter the height of the pattern-----
6
-----This the butterfly pattern-----
1 1
1 2 2 1
1 2 3 3 2 1
1 2 3 4 4 3 2 1
1 2 3 4 5 5 4 3 2 1
1 2 3 4 5 6 6 5 4 3 2 1
1 2 3 4 5 5 4 3 2 1
1 2 3 4 4 3 2 1
1 2 3 3 2 1
1 2 2 1
1 1
nested-for
loop statement.
Explanation
In this program, we have taken input 6
size of the pattern then made the calculation using the for
loop statement and putchar()
function.