Printing Perfect Squares in C++

Beginner

Introduction

In this lab, we will learn how to print a perfect square of numbers using the sleep and delay functions in C++. These functions are useful for showing the user multiple outputs for a given period. We will implement this program in the ~/project/main.cpp file.

Include the Required Libraries

We need to include the required C++ libraries for our program.

#include<iostream>
#include <chrono>
#include <thread>

using namespace std;

Declare and Initialize Variables

We need to declare and initialize the required variables like a matrix, i, j, low, top, and n.

int main()
{
    int a[10][10]={0},i,j,low=0,top=9,n=1;

Construct the Perfect Square Matrix

We construct the perfect square matrix using loops.

    for(i=0;i<5;i++,low++,top--)
    {
        for(j=low;j<=top;j++,n++)
            a[i][j]=n;
        for(j=low+1;j<=top;j++,n++)
            a[j][top]=n;
        for(j=top-1;j>=low;j--,n++)
            a[top][j]=n;
        for(j=top-1;j>low;j--,n++)
            a[j][low]=n;
    }

Display the Perfect Square Matrix with Sleep Function

Display the perfect square matrix with the sleep function.

    cout<<("\t\t\t\tPerfect Square\n");
    for(i=0;i<10;i++)
    {
        cout<<("\n\n\t");
        for(j=0;j<10;j++)
        {
            cout<<("%6d",a[i][j]);
            sleep(1); // Pause the program for one second
        }
    }
    return 0;
}

Compile and Run the Program

Compile and run the program using the following command in the terminal:

g++ ~/project/main.cpp -o main && ./main

Summary

In this lab, we learned how to display a perfect square of numbers using a sleep function and delay method in C++. We constructed the matrix using loops and displayed the matrix using the sleep function.

Other Tutorials you may like