TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
spiral_print.cpp File Reference

Print the elements of a matrix traversing it spirally. More...

#include <iostream>
Include dependency graph for spiral_print.cpp:

Go to the source code of this file.

Functions

void genArray (int **a, int r, int c)
 
void spiralPrint (int **a, int r, int c)
 
int main ()
 

Detailed Description

Print the elements of a matrix traversing it spirally.

Definition in file spiral_print.cpp.

Function Documentation

◆ genArray()

void genArray ( int ** a,
int r,
int c )

Arrange sequence of numbers from '1' in a matrix form

Parameters
[out]amatrix to fill
[in]rnumber of rows
[in]cnumber of columns

Definition at line 12 of file spiral_print.cpp.

12 {
13 int value = 1;
14 for (int i = 0; i < r; i++) {
15 for (int j = 0; j < c; j++) {
16 a[i][j] = value;
17 std::cout << a[i][j] << " ";
18 value++;
19 }
20 std::cout << std::endl;
21 }
22}

◆ main()

int main ( void )

main function

Definition at line 69 of file spiral_print.cpp.

69 {
70 int r, c;
71 std::cin >> r >> c;
72 int **a = new int *[r];
73 for (int i = 0; i < r; i++) a[i] = new int[c];
74
75 genArray(a, r, c);
76 spiralPrint(a, r, c);
77
78 for (int i = 0; i < r; i++) delete[] a[i];
79 delete[] a;
80 return 0;
81}
void spiralPrint(int **a, int r, int c)
void genArray(int **a, int r, int c)

◆ spiralPrint()

void spiralPrint ( int ** a,
int r,
int c )

Traverse the matrix spirally and print the sequence of elements

Parameters
[in]amatrix to read from
[in]rnumber of rows
[in]cnumber of columns

Print start row

Print the end col

Print the end row

Print the start Col

Definition at line 29 of file spiral_print.cpp.

29 {
30 int startRow = 0, endRow = r - 1;
31 int startCol = 0, endCol = c - 1;
32 int cnt = 0;
33
34 while (startRow <= endRow && startCol <= endCol) {
36 for (int i = startCol; i <= endCol; i++, cnt++) {
37 std::cout << a[startRow][i] << " ";
38 }
39 startRow++;
40
42 for (int i = startRow; i <= endRow; i++, cnt++) {
43 std::cout << a[i][endCol] << " ";
44 }
45 endCol--;
46
48 if (cnt == r * c) {
49 break;
50 }
51
52 for (int i = endCol; i >= startCol; i--, cnt++) {
53 std::cout << a[endRow][i] << " ";
54 }
55 endRow--;
56
58 if (cnt == r * c) {
59 break;
60 }
61 for (int i = endRow; i >= startRow; i--, cnt++) {
62 std::cout << a[i][startCol] << " ";
63 }
64 startCol++;
65 }
66}