Home »
C++ programs »
C++ Most popular & searched programs
C++ program to print pattern of stars till N number of rows
This C++ program will read total number of rows from the user and print the star pattern till N rows.
Submitted by Abhishek Pathak, on May 25, 2017
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.
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.