In: Computer Science
C++ program please, can you show me where I did wrong. I'm trying to print the counter-clockwise spiral form using int *p, but my output turned out weird, thank you
void makeSpiral(int *p, int rows, int cols) { int left = 0, value = 1, top = 0; while(left < cols && top < rows) { for(int i = top;i < rows;++i) { *(p+i*cols+left) = value++; } left++; for(int i = left;i < cols;++i) { *(p+(rows-1)*cols+i) = value++; } rows--; if (top < rows) { for(int i = rows-1; i >= top; --i) { *(p + i * cols + (cols-1)) = value++; } cols--; } if (left < cols) { for(int i = cols - 1 ;i >= left; --i) { *(p + top * cols + i) = value++; } top++; } } }
My output:
---------------------------------------------
1
---------------------------------------------
1 4
2 3
---------------------------------------------
1 8 7
9 0 6
3 4 5
---------------------------------------------
1 12 11 10
13 16 0 14
15 0 0 8
4 5 6 7
---------------------------------------------
1 16 15 14 13
24 0 23 25 18
3 22 0 19 20
21 0 0 0 10
5 6 7 8 9
---------------------------------------------
1 18 17 16 15 14 13
28 27 26 0 25 0 20
21 22 23 24 0 0 11
4 5 6 7 8 9 10
---------------------------------------------
1 18 17 16
19 28 0 20
27 0 21 26
4 22 25 13
23 24 0 12
6 0 0 11
7 8 9 10
The output that I supposed to have:
---------------------------------
1
---------------------------------
1 3
---------------------------------
3
2
---------------------------------
1 4
2 3
---------------------------------
1 8 7
2 9 6
3 4 5
---------------------------------
1 12 11 10
2 13 16 9
3 14 15 8
4 5 6 7
---------------------------------
1 16 15 14 13
2 17 24 23 12
3 18 25 22 11
4 19 20 21 10
5 6 7 8 9
//Write c++ program to print the counter-clockwise
spiral
#include<iostream.h>
#include<conio.h>
#define R 3
#define C 3
void makeSpiral(int m, int n, int matrix[R][C])
{
int i, k = 0, l = 0;
int count = 0;
int total = m * n;
while (k < m && l < n){
if (count == total)
break;
for (i = k; i < m; ++i){
cout<<matrix[i][l]<<" ";
count++;
}
l++;
if (count == total)
break;
for (i = l; i < n; ++i){
cout<<matrix[m - 1][i]<<" ";
count++;
}
m--;
if (count == total)
break;
if (k < m){
for (i = m - 1; i >= k; --i){
cout<<matrix[i][n - 1]<<" ";
count++;
}
n--;
}
if (count == total)
break;
if (l < n){
for (i = n - 1; i >= l; --i){
cout<<matrix[k][i]<<" ";
count++;
}
k++;
}
}
}
void main()
{
int mat[R][C] =
{
{1, 16 ,15 ,14, 13},
{2, 17 ,24 ,23 ,12},
{3, 18, 25, 22, 11},
{4 ,19 ,20, 21, 10},
{5, 6, 7, 8, 9}
};
cout<<"Conter Clockwise Spiral from of the matrix is
:\n";
makeSpiral(R, C, mat);
getch();
}
Output: