Q:

C++ program to print pattern of stars till N number of rows

0

C++ program to print pattern of stars till N number of rows

While pattern programs are just based on a couple of logic statements, with a repeating pattern on every iteration, they are quite tricky to code. You must have heard about the triangular pyramid pattern, which prints a character in a pyramid fashion.

Generally these patterns are represented with "*" symbol. However, you can always use the character of your choice.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Consider the program:

#include <iostream>
using namespace std;

int main()
{

	int i, space, rows, k=0;

	cout<<"Enter the number of rows: ";
	cin>>rows;
	
	for(i=1; i<=rows; i++)
	{
		for(space=1; space<=rows-i; space++)
		{
			cout<<"  ";
		}
		while(k!=(2*i-1))
		{
			cout<<"* ";
			k++;
		}
		k=0;
		cout<<"\n";
	}

	return 0;
}

Output

Enter the number of rows: 5
        *
      * * *
    * * * * *
  * * * * * * *
* * * * * * * * *

Starting with the variables, we have used a space variable that will count the space, rows variable that will hold the number of rows. The i and k variables are loop counters.

After taking rows input from the user, we start a loop to traverse all the rows. Inside it, we use another for loop with space variable in it. This is to ensure that on every row, there are i characters and (row-i) spaces. Next, we check while k is not equal to twice the rows minus 1, we put a star symbol and increment the k.

After the loop we reset k=0 and print a new line.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Most popular and Searched C++ solved programs with Explanation and Output

Similar questions


need a help?


find thousands of online teachers now
C++ program to generate random alphabets and store... >>
<< C++ Program to print a chessboard pattern...