
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Print a given matrix in reverse spiral form in C++
In this problem, we are given a 2-dimensional matrix. Our task is to print all the elements of the matrix in reverse spiral form.
Let’s take an example to understand the problem
Input: 12 23 54 67 76 90 01 51 43 18 49 5 31 91 75 9 Output: 18 49 1 90 76 43 31 91 75 9 5 51 67 54 23 12
We will start from the center of the matrix and print elements in reverse spiral direction taking four loops for printing elements in reverse direction.
Example
Program to show the implementation of our solution
#include <iostream> #define R 3 #define C 6 using namespace std; void printReverseSpiral(int m, int n, int a[R][C]) { long int b[100]; int i, k = 0, l = 0; int z = 0; int size = m*n; while (k < m && l < n) { int val; for (i = l; i < n; ++i){ val = a[k][i]; b[z] = val; ++z; } k++; for (i = k; i < m; ++i){ val = a[i][n-1]; b[z] = val; ++z; } n--; if ( k < m){ for (i = n-1; i >= l; --i){ val = a[m-1][i]; b[z] = val; ++z; } m--; } if (l < n){ for (i = m-1; i >= k; --i){ val = a[i][l]; b[z] = val; ++z; } l++; } } for (int i=size-1 ; i>=0 ; --i){ cout<<b[i]<<" "; } } int main() { int mat[R][C] = { {34, 5, 6, 98, 12, 23}, {9, 12, 56, 87, 99, 1}, {13, 91, 50, 8, 21, 2} }; cout<<"Printing reverse Spiral of the matrix :\n"; printReverseSpiral(R, C, mat); return 0; }
Output
Printing reverse Spiral of the matrix −
99 87 56 12 9 13 91 50 8 21 2 1 23 12 98 6 5 34
- Related Articles
- Print a given matrix in counter-clockwise spiral form in C++
- Java program to print a given matrix in Spiral Form.
- Print a matrix in Reverse Wave Form in C++
- Print a matrix in a spiral form starting from a point in C++
- Print a given matrix in zigzag form in C++
- Print Matrix in spiral way\n
- Spiral Matrix in C++
- Spiral Matrix III in C++
- Program to print matrix elements in spiral order in python
- How to print a matrix of size n*n in spiral order using C#?
- C++ Program to Print Matrix in Z form?
- Print matrix in antispiral form
- Print n x n spiral matrix using O(1) extra space in C Program.
- Spiral Matrix II in Python
- Program to Print the Squared Matrix in Z form in C

Advertisements