Printing Matrix Spiral in C++

Printing Matrix Spiral in C

Before coding the example of a matrix spiral, we need to see how to create a matrix in C++. To create a matrix in C++, we use a 2D array, and we can declare it as the following.

int mat[M][N] ={
{ 1, 2, 3, 4, 5},
{16, 17, 18, 19, 6},
{15, 24, 25, 20, 7},
{14, 23, 22, 21, 8},
{13, 12, 11, 10, 9}};

So here, we declare a matrix of M rows and N columns and fill in the values row by row. The numbers in 2 curly braces, separated by a comma, depict a row. The numbers in the matrix will be of integer type because the matrix is an integer 2d array. Before we start with the code, let’s first talk about the algorithm to understand it better.

  • The algorithm starts from the top left corner of the array and traverses the first row from left to right, and increments the value of the top corner index
  • Then it traverses the rightmost column top to bottom. Once this completes, it decrements the right corner index.
  • The algorithm traverses the last row and decrements the bottom corner index.
  • Lastly, the algorithm traverses the leftmost column, incrementing the left corner index.
  • These steps work in continuation until the left index is greater than the right index and the bottom index is greater than the top index. 
Now let’s begin with the real deal and write the code to print a spiral matrix of the above-shown matrix. The code is written below:

#include <iostream>
using namespace std;

#define M 5
#define N 5

void printSpiralOrder(int mat[M][N])
{
int top = 0, bottom = M - 1;
int left = 0, right = N - 1;

while (1)
{
if (left > right) {
break;
}
// print top row
for (int i = left; i <= right; i++) {
cout << mat[top][i] << " ";
}
top++;

if (top > bottom) {
break;
}

 
// Since we have traversed the whole first
// row, move down to the next row.
// print right column
for (int i = top; i <= bottom; i++) {
cout << mat[i][right] << " ";
}
right--;

if (left > right) {
break;
}
// print bottom row
for (int i = right; i >= left; i--) {
cout << mat[bottom][i] << " ";
}
bottom--;

if (top > bottom) {
break;
}
// print left column
for (int i = bottom; i >= top; i--) {
cout << mat[i][left] << " ";
}
left++;
}
}

int main()
{
int mat[M][N] =
{
{ 1, 2, 3, 4, 5},
{16, 17, 18, 19, 6},
{15, 24, 25, 20, 7},
{14, 23, 22, 21, 8},
{13, 12, 11, 10, 9}
};

printSpiralOrder(mat);

return 0;
}

So in the code, above we have first written the function to print the matrix in spiral order. In the main function, we have declared a matrix passed to the printSpiralOrder() function. The function first declares the variables (left, right, top, bottom) for easy traversal in the matrix. Then it has an infinite while loop and breaks conditions were necessary to jump to other loops.

So, we start with the first row where we are looping until the row reaches the maximum index, i.e., 4, and print the whole row. Then we move forward and then do the same thing for the bottom row and so on until we are finished printing the matrix in a spiral form. When the matrix reaches the spiral form, one of the if meets the condition, and the loop breaks. ConclusionThe above solution is just one way of printing a spiral matrix. However, there can be other ways of doing the same thing using stack data structures or vectors.

Similar Posts

  • Arrays in C++ with examples

    Arrays are a widespread concept in many programming languages. Before heading into the concepts, let’s understand what Arrays are and why they are so important? Suppose we need to make a program to store the names of five fruits, namely orange, mango, banana, apple, and grapes. All the fruits would have the same type, i.e., a string but stored in different 5 variables. We use an array to solve this problem, so an array is a data structure that holds fixed-size elements of the same data type.

  • Calculating Factorial in C++

    We will use C++ to write programs to calculate the factorial of a number. We will take the number as an input from the user and then print the factorial of that number in the console. We will use two methods to calculate the factorial of the number, the first is by performing iteration with the help of loops, and the second is by using recursion.

  • Working with C++ Arrays

    Arrays in C++ are one of the most important user-defined data types in C++. They can be used to store a large amount of data of the same data type sequentially. C++ also supports N-Dimensional arrays that can be used for problem-solving in scientific computing. For example, we can use the 2-Dimensional array of C++ to create a matrix, and they have wide usage in NLP, Machine Learning, and Artificial Intelligence. If you want to know more about the basics of c++ arrays, you can follow our step-by-step beginner guide on arrays in C++.

  • Linked List in C++

    It’s always never too late to learn new skills. Let’s take some time and look at this fundamental and useful data structure in our daily lives. What is a linked list in C++? It’s a type of data structure that uses pointers for its implementation. It will be very wise for you to also look at pointers if you have not yet since they will give you a deeper understanding of the Linked List. Nevertheless, I will try as much as possible to make this simple and understandable.

  • Getline in C++ with examples

    Before we dive into the tutorial, there is a fundamental question that must be answered. Why take user input? In the real world, many applications give results based on user input. Let’s consider YouTube as an example. A person X visits YouTube and searches for his favorite song. Simultaneously, a person Y visits YouTube and searches for his favorite movie.

Leave a Reply

Your email address will not be published. Required fields are marked *