Print Number Pattern

Printing Number Pattern

In this program we’re going to code a c program for the number pattern program. We will be using the approach of Basic incrementing Squared Number-Star Pattern + Basic incrementing inverted Squared Number-Star Pattern (alternate)

For any input Number N print the following code – for below code N=5.

Then output –

1 * 2 * 3 * 4 * 5 
11 * 12 * 13 * 14 * 15 
21 * 22 * 23 * 24 * 25 
16 * 17 * 18 * 19 * 20 
6 * 7 * 8 * 9 * 10

Algorithm:

  • Start the program.
  • Take number of rows input from the user and store it in any variable (‘n’ in this case).
  • Check if ‘n’ is within the range of 1 to 100 (inclusive).
  • Iterate over the rows from 1 to ‘n’ with a step of 2 (odd rows)
  • Calculate the value of ‘k’ using the formula: (i-1)*n + 1.
  • Print the numbers in the row, followed by an asterisk and a space.
  • If ‘n’ is odd, If it is, Update ‘p’ to ‘n-1’.
  • Iterate over the rows from ‘p’ to 1 with a step of 2 (even rows).
  • Calculate the value of ‘k’ using the formula: (i-1)*n + 1.
  • Print the numbers in the row, followed by an asterisk and a space.
  • End the program.

Code in C++:

Run
#include<iostream>
using namespace std;
int main()
{
    int n;
    cout<<"Enter the Number of Rows : ";
    cin >> n;
    cout << endl << endl;
    int p = n;
    if(n >= 1 && n <= 100)
    {
        for(int i = 1; i <= n; i += 2)
        {
            cout<<"\t";
            int k=(i-1)*n+1;
            for(int j = 0; j < n-1; j++)
            {
                cout << k << " * ";
                k++;
            }
            cout << k << " ";
            cout << endl;
        }
        if(n % 2 != 0)
        {
            p = n-1;
        }
        for(int i = p; i > 0; i -= 2)
        {
            cout << "\t";
            int k = (i-1) * n + 1;
            for(int j = 0; j < n-1; j++)
            {
                cout << k << " * ";
                k++;
            }
            cout << k << " ";
            cout << endl;
        }
    }
    else
    {
        cout << "Enter a Valid Input(1-100)!";
    }
    return 0;
}

One comment on “Print Number Pattern”


  • singhji012002

    Simple c++;
    #include
    using namespace std;

    int main()
    {
    int n;
    cin>>n;
    int cnt = 1;
    for(int i=1; i<=n; i++)
    {
    if(i%2 != 0)
    {
    for(int j=1; j<=n; j++)
    {
    if(j != n)
    {
    cout<<cnt<<"*";
    cnt++;
    }
    else
    {
    cout<<cnt;
    cnt++;
    }
    }
    }
    else
    {
    int temp = cnt+n;
    for(int j=1; j<=n; j++)
    {
    if(j != n)
    {
    cout<<temp<<"*";
    temp++;
    }
    else
    {
    cout<<temp;
    temp++;
    }
    }
    }
    cout<<endl;
    }
    }