×

Star pattern in C++ using For Loops

Star patterns are one of the most extensively utilized patterns in any programming language since they help to increase logical thinking and flow control understanding.
In the C++ programming language, you need two or three loops to generate a pattern. The number of loops you require depends on the pattern you want to make. A minimum of two patterns are used, first for each row and the second for each column. The first loop, known as an outer loop which display rows, while the second loop, known as an inner loop which display columns.

What is For Loop?

A for loop is a repetitive control structure that allows you to create a loop for executing a specific number of times.

The syntax of For Loop

In C++, a for loop is written as

for ( initialize; condition; incrementation ) 
 {
 statement(x);
 }

The programmer or user inserts the number of rows according to how many stars he wants to print.

1st pattern:  Program in C++ to print half star pyramid pattern:

#include <iostream>
using namespace std;
int main()
{
int  i, j, n;
cout << "Enter number of rows:  ";
cin >> n;
for(i = 1; i <= n; i++)     // outer loop(to print rows)
        {
            for(j = 1; j <= i; j++)      //inner loop(to print columns)
                  {
                       cout << "* ";
                  }
//Ending line after each row //
           cout << "\n";
          }
return 0;
}

Output:

Enter number of rows:  4
*
*  *
*  *  *
*  *  *  *

2nd pattern: Program in C++ to print inverted half star pyramid pattern

#include <iostream>
using namespace std;
int main()
{
int  i, j, n;
cout << "Enter number of rows:  ";
cin >> n;
for(i = n; i >= 1; i--)
      {
             for(j = 1; j <= i; j++)
                   {
                         cout << "* ";
                   }
// ending line after each row
      cout << "\n";
        }
return 0;
}


Output:

*   *   *   *
*   *   *
*   *
*

3rd pattern: Program in C++ to print star pyramid pattern:

#include<iostream>
using namespace std;
int main()
{
int n, s, i, j;
cout << "Enter number of rows: ";
cin >> n;
for(i = 1; i <= n; i++)
       {
             //for loop for displaying space
             for(s = i; s < n; s++)
                    {
                         cout << " ";
                     }
              //for loop to display star equal to the row number
           for(j = 1; j <= (2 * i - 1); j++)
                   {
                       cout << "*";
                   }
// ending line after each row
cout << "\n";
}
}

Output:

Enter the number of rows: 4
              *
            * * *
          * * * * *
        * * * * * * *

4th pattern: Program in C++ to print inverted star pyramid pattern:

#include<iostream>
using namespace std;
int main()
{
int n, s, i, j;
cout << "Enter number of rows: ";
cin >> n;
for( i=n; i>= 1; i-- )
{
//for loop to put space
     for(s = i; s < n; s++)
          {
               cout << " ";
          }
        //for loop for displaying star
     for(j = 1; j <= i; j++)
          {
                cout << "* ";
            }
// ending line after each row
cout << "\n";
}
return 0;
}

Output:

Enter number of rows: 4


*   *   *   *
  *  *   *
    *  *
      *

5th  pattern: Program to print full star diamond pattern in C++:

#include<iostream>
using namespace std;
int main()
{
int n, s, i, j;
cout << "Enter number of rows: ";
cin >> n;
  //loop to print the upper diamond pattern //
for(i = 0; i <= n; i++)
{
for(s = n; s > i; s--)
cout << " ";
for(j=0; j<i; j++)
cout << "* ";
cout << "\n";
}
// for loop to print the inverted diamond pattern //
for(i = 1; i < n; i++)
{
for(s = 0; s < i; s++)
cout << " ";
for(j = n; j > i; j--)
cout << "* ";
// ending line after each row
cout << "\n";
}
return 0;
}

Output:

Enter number of rows: 7             
              *
            *  *
         *   *    *
      *    *    *    *
         *    *    *
            *     *
               * 

Related Topics

Returning Multiple Values from a Function using Tuple and Pair in C++

We may come across many situations where after the driver code's execution is performed in a code block, the return should be either multiple values or a single value possibly...

4 minutes read.

C++ Signal Handling

Signals are interruptions sent by the operating system to a process to cause it to cease doing its current job and focus on the task for which the interrupt was...

4 minutes read.

Principles of Object-Oriented Programming in C++

What is Object-Oriented Programming? Object-oriented programming is about creating obejcts that represent the real-world entity . In object-oriented programming, objects are created for the class. One of the main objectives of...

5 minutes read.

Loops in C++

A loop statement in most programming languages allows us to execute a statement or a collection of statements numerous times. Control structures of programming languages vary, allowing for more complex...

6 minutes read.

C++ Structs

We frequently encounter scenarios in which we must store a bunch of data, whether of comparable or dissimilar data kinds. Arrays are used to hold a group of data of...

6 minutes read.

C++ Goto

In this article, we will discuss the C++ goto statement with its syntax, use, key features, key points, pseudo code, and examples. What is the goto statement in C++? In C++, the...

4 minutes read.

Timsort Implementation Using C++

Timsort Implementation Using C++ The Timsort is a stable sorting algorithm that uses the idea of merge sort and insertion sort. It can also be called a hybrid algorithm of insertion...

3 minutes read.

Reverse function in C++

The function std::reverse() is included in the standard template library of C++. It takes in a beginning and ending iterator, reversing the order. To use the reverse statement, we need...

2 minutes read.

Hybrid Inheritance

C++ Hybrid Inheritance When more than one type of inheritance is combined in single inheritance is called as hybrid inheritance. C++ Hybrid Inheritance Example #include<iostream>   using namespace std;   class Student{       protected:           int rollno;       public:           void getRoll(int a){               rollno=a;           }           void putRoll(void){               cout <<"Roll No: "<< rollno<<endl;           }   };   class Test : public Student{       protected:           float subject1, subject2;       public:           void getMarks(float x, float y){               subject1=x;               subject2=y;           }           void putMarks(void){               cout<< "Marks gain: "<<endl <<"Subject1 =  "<<subject1<<endl<<"Subject2 = "<<subject2 <<endl;           }   };   class Sport{       protected:           float score;       public:           void getScore(float s){               score=s;           }           void putScore(void){               cout<<"Sports score: "<<score<<endl;           }   };   class Result : public Test, public Sport{       float total;       public:           void display(void);   };   void Result:: display(void){       total=subject1+subject2+score;       putRoll();       putMarks();       putScore();       cout<<"Total Score: "<<total<<endl;   }   int main(){       Result stu;       stu.getRoll(10);       stu.getMarks(40,50);       stu.getScore(60);       stu.display();       return 0;   } Output: Roll No: 10 Marks gain: Subject1 = 40 Subject2 = 50 Sports score: 60 Total...

1 minute read.

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

3 minutes read.

Advantage and disadvantage friend function C++

Friend Function: - A friend function in C++ is a function that can access the private, protected, and public members of a class. In C++, a friend function is a function that...

2 minutes read.

Naming Convention in C++

The first and most fundamental step a programmer takes to produce clean code is to name a file or a variable. This naming must be acceptable so that it serves...

5 minutes read.

getline() Function and Character Array in C++

In this article, we will explore about some concepts on getline() function and character array in the most useful language C++. The getline() method in C++ is simply a standard library...

6 minutes read.

Roadmap to C++ Programming

Introduction There are so many programming languages available in the market, but among them, C++ is something that never lost its charm. It has a powerful impact on the programming world....

4 minutes read.

Copy elision in C++

The Copy Omission is another name for the Copy Elision. One of the several compiler optimization techniques is copy elision. It prevents items from being copied inadvertently. This Copy Elision approach...

3 minutes read.

Scope Resolution Operator vs this Pointer in C++

In this tutorial, we will compare the Scope Resolution operation to this Pointer in C++ language. Scope Resolution Operator The Scope Resolution Operator in C++ programming language is usually denoted by (::)....

3 minutes read.

How to create the Processes with Fork in C++

 In this article, we are going to explain the different methods that help us to create processes with a fork(). There are two methods to do so. These methods are...

2 minutes read.

Add two numbers represented by two arrays in C++

The array stores a number in such a way that each digit of the number is represented by an array element. As an example, The array number 147 is 1,4,7. To add...

3 minutes read.

Abstract class in C++

In this article, you will get exposure to an abstract class in C++. We will discuss this topic using some practical examples too. To understand the abstract classes, you should...

6 minutes read.

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left,...

4 minutes read.