Pattern Program Using Star

  • November 7, 2022
  • C++
Accessing Elements

 C++ implementation for pattern printing.

Pattern 1:

Program code:

#include <iostream>
using namespace std;
void pattern(int n)
{
	// Outer loop to handle number of rows
	for (int i = 0; i < n; i++) {

		// Inner loop to handle number of columns
	
		for (int j = 0; j <= i; j++) {

			// Printing stars
			cout << "* ";
		}

		// Ending line after each row
		cout << endl;
	}
}

// Driver Function
int main()
{
	int n = 5;
	pattern(n);
	return 0;
}
Output:
* 
* * 
* * * 
* * * * 
* * * * * 
Pattern 2:

Program code:


#include <iostream>
using namespace std;
void pattern(int n)
{
	// Outer loop to handle number of rows
	for (int i = n; i > 0; i--) {

		// Inner loop to handle number of columns
	
		for (int j = 0; j <= i; j++) {

			// Printing stars
			cout << "* ";
		}

		// Ending line after each row
		cout << endl;
	}
}

// Driver Function
int main()
{
	int n = 5;
	pattern(n);
	return 0;
}
Output:
* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
*
Pattern 3:

Program code:


#include <iostream>
using namespace std;
void pattern(int n)
{
	int i = 0, j = 0, k = 0;
    while (i < n) {
 
        // for number of spaces
        while (k < (n - i - 1)) {
            cout << "  ";
            k++;
        }
 
        // resetting k because we want to run k from
        // beginning.
        k = 0;
        while (j <= i) {
            cout << "* ";
            j++;
        }
 
        // resetting k so as it can start from 0.
        j = 0;
        i++;
        cout << endl;
    }
}

// Driver Function
int main()
{
	int n = 5;
	pattern(n);
	return 0;
}
Output:
        * 
      * * 
    * * * 
  * * * * 
* * * * * 
Pattern 4:

Program code:


#include <iostream>
using namespace std;
void pattern(int n)
{
	// number of spaces
    int k = 2 * n - 2;
 
    // Outer loop to handle number of rows
    
    for (int i = n; i > 0; i--) {
 
        // Inner loop to handle number spaces
        for (int j = 0; j < n - i; j++)
            cout << "  ";
 
        // Decrementing k after each loop
        k = k - 2;
 
        // Inner loop to handle number of columns
        
        for (int j = 0; j < i; j++) {
            // Printing stars
            cout << "* ";
        }
 
        // Ending line after each row
        cout << endl;
    }
}

// Driver Function
int main()
{
	int n = 5;
	pattern(n);
	return 0;
}
Output:
* * * * * 
  * * * * 
    * * * 
      * * 
        * 

Note: also read about Sum Of Series 1 + 2 + 4 + 8 + 16 + 32 + . . n

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

Your email address will not be published. Required fields are marked *