Butterfly Pattern in C++ language of Numbers using For loop
Butterfly pattern in c++ language of numbers using for loop. In this article, you will learn how to print the butterfly pattern in c++ language of numbers using for loop.
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++
cin
object - C++
cout
object - 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++ language of Numbers using For loop
#include <iostream>
using namespace std;
int main() {
int r, h, d, s;
// r - Value of pattern row
// h - Value of pattern height
// d - Value of digits
// s - Value of space
cout << "-----Enter the height of the pattern-----\n";
cin >> h;
cout << "\n-----This the butterfly pattern-----\n\n\n";
for(r = 1; r <= h - 1; r++) {
cout << "\t";
for(d = 1; d <= r; d++)
cout << d;
for(s = 1; s <= 2 * (h - r); s++)
cout << " ";
putchar('\b');
for(d = r; d >= 1; d--)
cout << d;
putchar('\n');
}
for(r = h; r >= 1; r--) {
cout << "\t";
for(d = 1; d <= r; d++)
cout << d;
for(s = 1; s <= 2 * (h - r); s++)
cout << " ";
putchar('\b');
for(d = r; d >= 1; d--)
cout << 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 statements.
Explanation
In this program, we have taken input 6
size of the pattern then made the calculation using the for
loop statement & putchar()
function.