C++ Programs To Create Pyramid and Pattern

C++ProgrammingServer Side Programming

There are many different pyramid patterns that can be created in C++. These are mostly created using nested for loops. Some of the pyramids that can be created are as follows.

Basic Pyramid Pattern

The code to create a basic pyramid is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int n = 6, i, j;
   for (i=1; i<=n; i++) {
      for(j=1; j<=i; j++ ) {
         cout << "* ";
      }
      cout << endl;
   }
   return 0;
}

Output

*
* *
* * *
* * * *
* * * * *
* * * * * *

In the above program, there are 2 for loops with loop variables i and j. The outer for loop counts the number of pyramid rows and the inner for loop counts the number of stars that are displayed in each row. This is demonstrated using the following code snippet.

for (i=1; i<=n; i++) {
   for(j=1; j<=i; j++ ) {
      cout << "* ";
   }
   cout << endl;
}

Rotated Pyramid Pattern

The code to create a rotated pyramid is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int n = 6, k = 2*n - 2;
   for (int i=0; i<n; i++) {
      for (int j=0; j<k; j++)
      cout <<" ";
      for (int j=0; j<=i; j++ )
      cout << "* ";
      k = k - 2;
      cout << endl;
   }
   return 0;
}

Output

*
* *
* * *
* * * *
* * * * *
* * * * * *

In the above program, there are two nested loops with loop variables i and j respectively. The value of k is set to 2*n -2. The outer for loop counts the number of pyramid rows. The first inner loop specifies the number of spaces before the stars. The next inner loop specifies the numbers of stars in each row.

This is demonstrated using the following code snippet.

for (int i=0; i<n; i++) {
   for (int j=0; j<k; j++)
   cout <<" ";
   for (int j=0; j<=i; j++ )
   cout << "* ";
   k = k - 2;
   cout << endl;
}
raja
Published on 27-Sep-2018 16:27:52
Advertisements