×

Diamond Pattern using While-loop in C++

What is while Loop?

A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the condition no longer met.

The syntax that can be used for the “while” loop in the C++ programming language is following:

while(condition)
    {
     statement(x);
    }

Before we move on the diamond star pattern, first we have to know the code of star pyramid and inverted star pyramid.

1. Right Triangle Star Pyramid:

Algorithm:

  1. Assume that the number of rows in a right triangle is n.
  2. In the Nth row, the number of stars is always K. The first row has one star, the second row has two stars, and the third row has three stars. The Kth row, on average, has K stars.
  3. To print the proper triangle star design, we'll utilize two loops.
    1. The outer while loop will iterate n times for a right triangular star design with "n" rows. The pattern will be printed one row at a time in each outer loop iteration.
    2. The inner loop will also run n times for the Nth row of the right triangle pattern. One star (*) will be printed for each inner loop iteration.

In the code, programmer/user enters the number of rows he wants display the stars on the screen.

Program in C++ to print right triangle star pyramid pattern

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

Output

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

Inverted Right Triangle Star pyramid

Algorithm:

The right triangular star pattern is inverted vertically in this algorithm. As the row number goes from top to bottom, so the number of stars in a row reduces.

NOTE: The row and column indexes always start at 0.

  1. Take the inverted right triangle's number of rows (n) as input. In an inverted right triangle (n - k + 1) is the number of stars in the kth row. Let, n be 4 in the pattern. As a result, the first row has four stars, the second row has three stars, the third row has two stars, and the fourth row has only one star.
  2. To print an inverted right triangular star design, we'll use two while loops.
  3. The outer while loop will iterate n times (from I = 0 to n-1) for an inverted right triangular star design with M rows. The code will be printed one row at a time in each iteration of this loop.
  4.  The inner loop will iterate M-j times (from j = 0 to n-j) for the jth row of the inverted right triangle pattern. The inner loop will print one star character for each iteration.

Program to print Inverted right triangle star pyramid pattern

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

Output:

*   *   *   *
*   *   *
*   *
*

Pyramid star pattern:

Algorithm:

In this program, we print a pyramid star pattern with (2*i + 1) space-separated stars in the ith row.

The row and column indexes begin at 0.

The number of rows (N) in the pattern is the input taken by the user.

The outer loop will print a row of the pyramid (from I = 0 to N - 1) after one iteration.

The inner while loop prints (N - i - 1) spaces for every line in the jth row of the pyramid, then nested while loop prints (2*j + 1) stars.

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;
i=1;
while(i<=n)
           {
             //while loop for displaying space
            s=1;
          while(s<n) 
                       {
                         cout << " ";
                          s++;
                     }
              //while loop to display star equal to the row number
            j=1;
           while(j<=(2*i-1))
                    {
                       cout << "*";
                       j++;
                   }
// ending line after each row
cout << "\n";
i++;
}
}

Output

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

Inverted star pyramid:

Algorithm:

In this algorithm, the rows are printed in reverse order, which is comparable to the pyramid star pattern.

  1. The number of rows (n) in the pattern is the first input.
  2. a) In one iteration, the outer while loop (from I = 0 to n-1) will print a row of inverted pyramids.
    b) The inner while loops print "S" spaces followed by (2*(n-i) - 1) star character in the jth row.

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;
i=n;
while(i>=1)
{
      // loop to put space
     s=i;
  while(s<n)
            {
               cout << " ";
               s++;
           }
        //loop for displaying star
          j=1;
        While(j<=i)
             {
                cout << "* ";
            j++;
             }
// ending line after each row
 cout << "\n";
i--;
}
return 0;
}

Output

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

Diamond star pattern:

The diamond star pattern is the combination of the pyramid and inverted pyramid pattern. The following c++ program combines the code of simple pyramid and the code of reverse pyramid star.

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 //
i=0;
while(i<=n){
      s=n;
      while(s>i){
               cout << " ";
               s--;
               }
     j=0;
    while(j<i){
             cout << "* ";
             j++;
             }
cout << "\n";
i++;
}
           // loop to print the inverted diamond pattern //


i=1;
while(i<n){
       s = 0;
        while(s<i){
               cout << " ";
                s++;
                }
       j = n; 
         while(j<i)
         {
           cout << "* ";
            j--;
               }
// ending line after each row
      cout << "\n";
  i++;
}
return 0;
}

Output

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

Related Topics

How to calculate size of string in C++

What is string in C++? In C++, a string is a sequence of characters. The string data type is part of the Standard Template Library (STL) and is defined in the...

4 minutes read.

Pthreads or POSIX Threads in C++

The thread API for C/C++ is implemented by pthreads or POSIX threads. It enables the multithreading system, which enables parallel and distributed processing, and the creation of new concurrent process...

3 minutes read.

C++ operator

In this article, we will discuss about the operators in C++ with their types and examples. An operator is specially a symbol that tells compiler to perform specific manipulation. C++ contains...

5 minutes read.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

4 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.

Print Table Using For-loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

3 minutes read.

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.

Array program in C++

What is an Array? An array is a set of identically typed elements that are organized into contiguous memory locations and each element can be independently accessed using an index. We can...

16 minutes read.

C++ Forward Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

C++ Enumeration

C++ Enumeration In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets...

3 minutes read.

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

Dynamic Memory Allocation in C++

In some programming situations, the number of data items changes as the program is running, which is known as dynamic data or input. Consider a real-world situation where a program...

3 minutes read.

C++ Prime number program

In this lesson, you'll learn how to verify whether a given number is a prime number or not in C++, and you'll obtain code to do it. What is the definition...

3 minutes read.

Constructor Vs Destructor in C++

C++ Constructor A function Object () { [native code] } is a member function that shares the same name as the class. It is called automatically whenever a class object is...

3 minutes read.

Hierarchical Inheritance

C++ Hierarchical Inheritance Hierarchical inheritance inherits the property of one base class in more than one derived class.   C++ Hierarchical Inheritance Example #include <iostream>   using namespace std;   class Person {       char gender[10];       int age;   public:       void getPerson()       {           cout << "Age: "; cin >> age;           cout << "Gender: "; cin >> gender;       }       void dispPerson()       {           cout << "Age: " << age << endl;           cout << "Gender: " << gender << endl;       }   };   class Employee : public Person {       float salary;   public:       void getEmployee()       {           Person::getPerson();           cout << "Salary: Rs."; cin >> salary;       }       void dispEmployee()       {           Person::dispPerson();           cout << "Salary: Rs." << salary << endl;       }   };   class Student : public Person {       char level[20];   public:       void getStudent()       {           Person::getPerson();           cout << "Class: "; cin >> level;       }       void dispStudent()       {           Person::dispPerson();           cout << "Level: " << level << endl;       }   };   int main()   {       Person per;       Employee emp;       Student stu;       cout << "Student data" << endl;       cout << "Enter data" << endl;       stu.getStudent();       cout << endl << "Displaying data" << endl;       stu.dispPerson();       cout << endl << "Staff Data" << endl;       cout << "Enter data" << endl;       emp.getEmployee();       cout << endl << "Displaying data" << endl;       emp.dispPerson();   } Output: Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age:...

1 minute read.

Hello World Program in C++

The steps for “Hello World” C++ program are as follows: Write a C++ code given below in an editor. Save the file with .cpp Compile the code using C++ compiler or using online...

3 minutes read.

Use of Inheritance in C++

What is inheritance in c++? Inheritance is fundamental in object-oriented programming (OOP) languages like C++. It allows a programmer to create a new class (called a derived class) that inherits the...

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.

C++ Continue

In C++, the continue statement is a useful tool for avoiding specific scenarios without breaking the loop. It is employed inside loops to move directly to the following iteration and...

4 minutes read.