Write the program to print the pattern G

we will learn how to print the pattern G: using stars and white-spaces. Given a number N. we will write a program to print the pattern G over n lines or rows.

 we will learn how to print the pattern G with stars and white spaces. We’ll create a program to display the pattern G over n lines or rows. We will create the pattern G using the simple logic of iteration over lines in this program.

Diagram of the program to print the pattern ‘G

Example input & output of the program to print the pattern ‘G

In this program, we have used the simple logic of iteration over lines to create the pattern G. Please look at the image below which represents the pattern G in the form of a 2-d matrix, where mat[i][j] = ‘ij’:

Input : 
Output :
  ***  
 *     
 *     
 * *** 
 *   * 
 *   * 
  ***  

Input : 
Output :
  *****  
 *       
 *       
 *       
 *   *** 
 *     * 
 *     * 
 *     * 
  *****  

structure of the G program

If we try to analyze this picture with a (row, column) matrix and the circles represent the position of stars in the pattern G, we will learn the steps. Here we are performing the operations column-wise. The other steps are self-explanatory and can be understood from the position of rows and columns in the diagram.
Below is the implementation of above idea:

G

C++ program to print the pattern G

#include <iostream>
using namespace std;

void pattern(int line)
{
	int i, j;
	for(i = 0; i < line; i++)
	{
		for(j = 0; j < line; j++)
		{
			if((j == 1 && i != 0 && i != line - 1) ||
			((i == 0 || i == line - 1) && j > 1 &&
			j < line - 2) || (i == ((line - 1) / 2) &&
			j > 2 && j < line - 1) || (j == line - 2 &&
			i != 0 && i >= ((line - 1) / 2) && i != line - 1))
				printf("*");
			else
				printf( " ");

		}
		printf("\n");
	}
}

// Driver code
int main()
{
	int line = 7;
	pattern(line);
	return 0;
}

// This code is contributed
// by vt_m.

Output: 
 

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

Leave a Reply