I wish to print a pattern in C language like this:
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
Currently I have this:
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
if(i>=j)
{
printf(" %d ",j+i-1);
}
}
printf("\n");
}
printf("\n");
}
I am not getting the desired result.Please can anybody help
Basically if you analyze the difference between numbers at each row:
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
^ ^ ^ ^
diff 4 3 2 1
Then for each column (except the first one which is equal to the row) the formula is:
col_value = val(row, col-1) + (5-col))
For example, the last row:
5 9 12 14 15
9 = 5 + (5-1)
12 = 9 + (5-2)
14 = 12 + (5-3)
15 = 14 + (5-4)
Code:
#include<stdio.h>
int main()
{
int i,j,k;
for(i=1;i<=5;i++)
{
k = i;
for(j=1;j<=i;j++)
{
printf("%d ", k);
k += 5-j;
}
printf("\n");
}
return 0;
}
Check this :
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
int temp = 4;
int sum = 0;
for(j=1;j<=i;j++)
{
if (j == 1)
sum = i;
else{
sum = sum + temp --;
}
printf("%d ",sum);
}
printf("\n");
}
}
int main () {
int k,i, j;
for (i = 1; i <=5; i++) {
k = i;
for (j = 1; j <= i; j++) {
printf ("%d ", k);
k = k + (5-j);
}
printf ("\n");
}
}
The logic is quite straight forward.
1) The number of elements in a row equals the row number. Hence use the inner loop with j = 1 to j <= i
2) If you see the pattern you observe that every row starts with the number equals to the row index, the next number is +4 and then +3 and so on.
3) Hence use k = k + (5-j)
int main()
{
int i,j,temp=0,l;
for(i=1;i<=5;i++)
{
l=4;
temp = i;
for(j=1;j<=i;j++)
{
if(j>1)
{
printf("%d\t",temp+l);
temp = temp+l;
l=l-1;
}
else
printf("%d\t",i);
}
printf("\n");
}
getch();
return 0;
}
Related
Here is the code that I have written:-
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int ctr = 0;
void partition(int arr[], int n) {
int i, j, k = 0, r, in = 0, te, flag = 0;
int *sum;
sum = (int*)malloc(sizeof(int) * pow(2, n));
for (i = 0; i < pow(2, n); i++) {
printf("{");
for (j = 0; j < n; j++) {
if (i & (1 << j)) {
printf("%d ", arr[j]);
sum[k] = sum[k] + arr[j];
}
}
k++;
printf("}");
printf("\n");
}
printf("\n \n");
int *temp;
for (k = 0; k < pow(2, n) - 1; k++) {
in = 0;
temp = (int*)malloc(sizeof(int));
for (r = k + 1; r < pow(2, n); r++) {
if (sum[k] == sum[r]) {
printf("\n Printing solution for sum %d", sum[k]);
for (i = 0; i < pow(2, n); i++) {
if (i == k || i == r) {
printf("{");
for (j = 0; j < n; j++) {
if (i & 1 << j) {
for (te = 0; te < in; te++) { //Disjointness
if (temp[te] == arr[j])
flag = 1;
}
if (flag == 1)
break;
temp[in++] = arr[j];
temp = (int*)realloc(temp, sizeof(int));
printf("%d ", arr[j]);
}
}
printf("}");
printf("\n");
}
}
break;
}
}
free(temp);
}
}
void main() {
int *arr, n, i;
printf("\n Enter the number of elements in the set \n");
scanf("%d", &n);
arr = (int*)malloc(sizeof(int) * n);
printf("\n Enter the set elements \n");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
partition(arr, n);
}
It works perfectly for the input {1,2,3}. For {1,2,3,4}, it gives the correct output as well.
For {1,2,3,4}, the output is:
Printing solution for sum 3{1 2 }
{3 }
Printing solution for sum 4{1 3 }
{4 }
Printing solution for sum 5{2 3 }
{1 4 }
Printing solution for sum 6{1 2 3 }
{}
Printing solution for sum 7{}
{}
But if the input is {1,5,11,5}, the output is:
Printing solution for sum 5{5 }
{}
Printing solution for sum 6{}
{}
Printing solution for sum 11{}
{}
Printing solution for sum 16{}
{}
Printing solution for sum 17{}
{}
Since {1,5,5} and {11} is a solution, in this case, the expected output should be Printing Solution for sum 11 {1,5,5} and {11} but it's not displaying that.
What is the problem and how can I fix it?
Your algorithm is too complicated. You start on the correct path, computing the sum of all subsets of the set, but you do not correctly compute all possible disjoint subsets to try and find one with the same sum.
Here is a simpler approach:
enumerate all subsets
for each subset, compute the sum and store a structure with the subset signature and its sum into an array.
sort the array by the value of the sum
iterate over the sorted array:
for each element, iterate over the subsequent elements with the same sum, if one of them has a disjoint subset signature, you have a match, print it.
the space complexity is O(2N) and the time complexity is even worse at O(2N+1), which is very bad, but manageable for small sets.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
struct s { int sig, sum; };
int compare(const void *p1, const void *p2) {
int sum1 = ((const struct s*)p1)->sum;
int sum2 = ((const struct s*)p2)->sum;
return (sum1 > sum2) - (sum1 < sum2);
}
void print_set(int arr[], size_t sig) {
printf("{");
while (sig) {
if (sig & 1)
printf(" %d", *arr);
arr++;
sig >>= 1;
}
printf(" } ");
}
void partition(int arr[], int n) {
size_t i, j, count = 1ULL << n;
struct s *array = calloc(sizeof(*array), count);
int b, sum;
if (array != NULL) {
for (i = 1; i < count; i++) {
sum = 0;
for (b = 0; b < n; b++) {
if (i & (1ULL << b))
sum += arr[b];
}
array[i].sig = i;
array[i].sum = sum;
}
qsort(array, count, sizeof(*array), compare);
for (i = 0; i < count; i++) {
for (j = i + 1; j < count && array[i].sum == array[j].sum; j++) {
if ((array[i].sig & array[j].sig) == 0) {
printf("solution with sum=%d: ", array[i].sum);
print_set(arr, array[i].sig);
print_set(arr, array[j].sig);
printf("\n");
}
}
}
free(array);
}
}
int main() {
int *arr, n, i;
printf("Enter the number of elements in the set: ");
if (scanf("%d", &n) == 1) {
arr = (int*)malloc(sizeof(int) * n);
if (arr != NULL) {
printf("Enter the set elements: ");
for (i = 0; i < n; i++) {
if (scanf("%d", &arr[i]) != 1)
return 1;
}
partition(arr, n);
free(arr);
}
}
return 0;
}
Output:
Enter the number of elements in the set: 3
Enter the set elements: 1 2 3
solution with sum=3: { 3 } { 1 2 }
Enter the number of elements in the set: 4
Enter the set elements: 1 2 3 4
solution with sum=3: { 1 2 } { 3 }
solution with sum=4: { 4 } { 1 3 }
solution with sum=5: { 2 3 } { 1 4 }
Enter the number of elements in the set: 4
Enter the set elements: 1 5 11 5
solution with sum=5: { 5 } { 5 }
solution with sum=11: { 11 } { 1 5 5 }
You may find the following to be a place to start. What this sample program does is to take a set of values and then generate as possible disjoint subsets where the sum of the elements of each subset are equal between the two subsets.
I am not sure if this actually answers your question. The requirements specified are quite loose. The source you provide does not compile with Visual Studio and when a few basic compile errors were corrected the resulting program crashed. I also find your example output confusing.
The criteria for disjoint subsets as created by this program are:
values in one subset can not appear in the other
membership is ordered and tracked via an index assigned to each element of the superset
a subset may have duplicate values but not duplicate indexed elements
the empty set is not considered to be a valid disjoint subset since it has no elements
there must be at least two subsets that can be formed from the set
only two subsets are considered and there may be more (e.g. {1, 2, 3, 4, 5} could have {2,3}, {1,4}, {5}).
The source code follows. This is from a single C source code file that is part of a Visual Studio C++ solution with the C++ main() calling the C source code entry point of mymain2(). I did it that way because it was easier for me.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct {
int *pSet; // array of values. array is malloced when max number is known.
int nSetMax; // max number of array elements, amount malloced.
int nSetCur; // current number of in use array elements.
} SetType;
static void generateSet (int i, int arr[], int n, SetType *temp)
{
int j;
temp->nSetCur = 0;
for (j = 0; j < n; j++)
{
if ( i & (1 << j))
{
int te;
int flag = 0;
for (te = 0; te < temp->nSetCur; te++)
{
// we compute disjoint property by the order of the elements in
// the set using element index in order to allow duplicate values per
// request of the question. Exampe 1, 5, 11, 5 as list of values.
if (temp->pSet[te] == j)
flag = 1;
}
if (flag == 1)
continue;
temp->pSet[temp->nSetCur] = j;
temp->nSetCur++;
}
}
}
static void printItems (int arr[], const SetType temp)
{
if (temp.nSetCur > 0) {
int j;
int sum = 0;
printf(" {");
for (j = 0; j < temp.nSetCur; j++) {
printf("%2d ", arr[temp.pSet[j]]);
sum += arr[temp.pSet[j]];
}
printf("} = %3d\n", sum);
} else
printf (" {}\n");
}
// determine if the two sets are disjoint by comparing the element indexes
// of the elements in each subset. the element index is the position of the
// subset element in the set from which the subset was drawn.
static int checkSetsByIndex (const SetType tempI, const SetType tempR)
{
int i;
for (i = 0; i < tempI.nSetCur; i++) {
int j;
for (j = 0; j < tempR.nSetCur; j++) {
if (tempI.pSet[i] == tempR.pSet[j])
return 0;
}
}
return 1;
}
// determine if the two sets are disjoint by comparing the element values
// of the elements in each subset. the element value is the value of the
// subset element in the set from which the subset was drawn.
// we may have duplicate values but as long as they are not in two different
// subsets then we allow it.
static int checkSetsByValue (int arr[], const SetType tempI, const SetType tempR)
{
int i;
#if 1
// following code does a check that the two sets are disjoint by value
// meaning they do not share any values. however a set may have multiple
// elements with the same value.
// if not needed then you can turn it off with Preprocessor check.
for (i = 0; i < tempI.nSetCur; i++) {
int j;
for (j = 0; j < tempR.nSetCur; j++) {
if (arr[tempI.pSet[i]] == arr[tempR.pSet[j]])
return 0;
}
}
#endif
return 1;
}
static void partition(int arr[], int n)
{
int i;
int iPow2n = pow(2, n);
int *sum = calloc(iPow2n, sizeof(int));
printf ("Generate and list sums\n");
for(i = 0; i < iPow2n; i++)
{
int j;
printf(" {");
for (j = 0; j < n; j++)
{
if (i & (1 << j))
{
printf("%2d ", arr[j]);
sum[i] = sum[i] + arr[j];
}
}
printf("} = %3d\n", sum[i]);
}
printf("\n\nGenerate list of disjoint sets for each sum.\n");
for (i = 0; i < iPow2n - 1; i++)
{
int r;
SetType tempI = {calloc(iPow2n, sizeof(SetType)), iPow2n, 0};
SetType tempR = {calloc(iPow2n, sizeof(SetType)), iPow2n, 0};
for(r = i + 1; r < iPow2n; r++)
{
if(sum[i] == sum[r])
{
generateSet (i, arr, n, &tempI);
generateSet (r, arr, n, &tempR);
// check disjoint subsets by looking at the index of the
// subset elements where the index is the index of the original
// set from which the subset is drawn.
if (checkSetsByIndex (tempI, tempR)) {
// check that the two subsets are disjoint by element values
// as well. this means that while a subset may have duplicate
// values, the elements of each subset must be disjoint can not
// have elements whose values are the same.
// so if we have a set {1, 5, 11, 5} then subsets of
// {5}, {5} is invalid but {1, 5, 5}, {11} is valid.
if (checkSetsByValue (arr, tempI, tempR)) {
printf("\n Printing solution for sum %d\n", sum[i]);
printItems (arr, tempI);
printItems (arr, tempR);
break;
}
}
}
}
free(tempI.pSet);
free(tempR.pSet);
}
}
int mymain2(void)
{
int n;
printf("\n Enter the number of elements in the set \n");
scanf("%d",&n);
if (n > 0) {
int i;
int *arr = malloc(sizeof(int) * n);
printf("\n Enter the set elements \n");
for (i = 0; i < n; i++)
{
scanf("%d",&arr[i]);
}
partition(arr,n);
free (arr);
}
return 0;
}
For a set of 4 values whose elements are {1, 2, 3, 4} it generates the following output:
Enter the number of elements in the set
4
Enter the set elements
1 2 3 4
Generate and list sums
{} = 0
{ 1 } = 1
{ 2 } = 2
{ 1 2 } = 3
{ 3 } = 3
{ 1 3 } = 4
{ 2 3 } = 5
{ 1 2 3 } = 6
{ 4 } = 4
{ 1 4 } = 5
{ 2 4 } = 6
{ 1 2 4 } = 7
{ 3 4 } = 7
{ 1 3 4 } = 8
{ 2 3 4 } = 9
{ 1 2 3 4 } = 10
Generate list of disjoint sets for each sum.
Printing solution for sum 3
{ 1 2 } = 3
{ 3 } = 3
Printing solution for sum 4
{ 1 3 } = 4
{ 4 } = 4
Printing solution for sum 5
{ 2 3 } = 5
{ 1 4 } = 5
For a set of 4 values {1, 5, 11, 5} it generates the following output:
Enter the number of elements in the set
4
Enter the set elements
1 5 11 5
Generate and list sums
{} = 0
{ 1 } = 1
{ 5 } = 5
{ 1 5 } = 6
{11 } = 11
{ 1 11 } = 12
{ 5 11 } = 16
{ 1 5 11 } = 17
{ 5 } = 5
{ 1 5 } = 6
{ 5 5 } = 10
{ 1 5 5 } = 11
{11 5 } = 16
{ 1 11 5 } = 17
{ 5 11 5 } = 21
{ 1 5 11 5 } = 22
Generate list of disjoint sets for each sum.
Printing solution for sum 11
{11 } = 11
{ 1 5 5 } = 11
For a set of 5 values {1, 2, 3, 4, 5} it generates the following output:
Enter the number of elements in the set
5
Enter the set elements
1 2 3 4 5
Generate and list sums
{} = 0
{ 1 } = 1
{ 2 } = 2
{ 1 2 } = 3
{ 3 } = 3
{ 1 3 } = 4
{ 2 3 } = 5
{ 1 2 3 } = 6
{ 4 } = 4
{ 1 4 } = 5
{ 2 4 } = 6
{ 1 2 4 } = 7
{ 3 4 } = 7
{ 1 3 4 } = 8
{ 2 3 4 } = 9
{ 1 2 3 4 } = 10
{ 5 } = 5
{ 1 5 } = 6
{ 2 5 } = 7
{ 1 2 5 } = 8
{ 3 5 } = 8
{ 1 3 5 } = 9
{ 2 3 5 } = 10
{ 1 2 3 5 } = 11
{ 4 5 } = 9
{ 1 4 5 } = 10
{ 2 4 5 } = 11
{ 1 2 4 5 } = 12
{ 3 4 5 } = 12
{ 1 3 4 5 } = 13
{ 2 3 4 5 } = 14
{ 1 2 3 4 5 } = 15
Generate list of disjoint sets for each sum.
Printing solution for sum 3
{ 1 2 } = 3
{ 3 } = 3
Printing solution for sum 4
{ 1 3 } = 4
{ 4 } = 4
Printing solution for sum 5
{ 2 3 } = 5
{ 1 4 } = 5
Printing solution for sum 5
{ 1 4 } = 5
{ 5 } = 5
Printing solution for sum 6
{ 2 4 } = 6
{ 1 5 } = 6
Printing solution for sum 7
{ 3 4 } = 7
{ 2 5 } = 7
I wrote a function to print the below pattern.
For example, if the n value is 4 the pattern is
1
2 7
3 6 8
4 5 9 10
Or if the value of n is 5, then the pattern is
1
2 9
3 8 10
4 7 11 14
5 6 12 13 15
My function gives me the first two block but not the next block. I'm stuck here for long time!
My function is
int printPattern(int n) {
int row, column, fwdCtr = 1, evenCtr = 0, ctr = n;
for(row = 1; row <= n; row++) {
fwdCtr = row;
for(column = 1; column <= row; column++) {
if(column % 2 != 0) {
printf("%d ", fwdCtr++);
} else {
evenCtr = fwdCtr + ctr;
printf("%d ", evenCtr);
ctr = ctr - 2;
}
}
printf("\n");
}
}
What I get is
1
2 7
3 6 4
4 5 5 4
Please give suggestions of changes!
The following code should do it:
#include <stdio.h>
void f(int n)
{
for (int i = 0; i < n; ++i)
{
for (int j=0; j<=i; ++j)
{
// Calculate the numbers used so far by previous columns
int x = 0;
for(int v=0; v<j;++v)
{
x = x + (n-v);
}
if ((j % 2) == 0)
{
// even columns
printf("%d ", x+i-j+1);
}
else
{
// odd columns
printf("%d ", x+n-i);
}
}
printf("\n");
}
}
int main(void)
{
f(5);
return 0;
}
Output:
1
2 9
3 8 10
4 7 11 14
5 6 12 13 15
The easy thing to do is just print the right number based on the row and column and the value of n, like this
int main(void)
{
int n = 20;
for (int row = 0; row < n; row++) {
for (int col = 0; col <= row; col++)
printf("%3d ", 1 + col*n - (col-1)*col/2 + (col%2 ? n-1-row : row-col));
printf("\n");
}
}
I am trying to print an array in order to the even strings print backwards but the not even string in usual way. What do I do wrong with it?
For example:
1 0 3
9 7 3
5 7 8
and I need it:
1 0 3
3 7 9
5 7 8
But I also have a problem with filling an array in spiral way; how should I take a center of an array? Please, could you give an idea — how should I do this? And the array must be square. For example:
1 2 3
4 5 6
7 8 9
but I need it:
3 2 9
4 1 8
5 6 7
My code so far:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[10][10],n,m,i,j;
printf("Enter m: ");
scanf("%d",&m);
printf("Enter n: ");
scanf("%d",&n);
for(i=0;i<m;i++){
for(j=0;j<m;j++){
printf("a[%d][%d]: ",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
// in usual order
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("%d ",a[i][j]);
}
printf("\n");
}
for(i=0;i<m;i++){
for(j=0;j<n;j++){
if(i%2 != 0){
printf("%d ",a[i][j]);
}
else {
printf("%d ",a[n-i+1][j]);
}
}
printf("\n");
}
return 0;
}
example of filling an array in spiral
#include <stdio.h>
#include <string.h>
typedef enum {
N, W, S, E
} Dir;
typedef struct walker {
int row, col;
Dir dir;
int steps;
} Walker;
Walker go_forward(Walker walker){
switch(walker.dir){
case N:
walker.row -= 1;
break;
case W:
walker.col -= 1;
break;
case S:
walker.row += 1;
break;
case E:
walker.col += 1;
break;
}
return walker;
}
Walker proceed_left(Walker walker){
walker.dir = (walker.dir + 1) % 4;//turn left
walker = go_forward(walker);
return walker;
}
int main(void){
int n;
for(;;){
printf("Enter n(0 < n < 10): ");fflush(stdout);
int ret_s = scanf("%d", &n);
if(ret_s == 1){
if(0 < n && n < 10)
break;
} else if(ret_s == 0)
while(getchar() != '\n');//clear input
else //if(ret_s == EOF)
return 0;
}
int a[n][n];
memset(a, 0, sizeof(a));//zero clear
Walker walker = { .row = n / 2, .col = n / 2, .dir = E, .steps = 0 };
for(;;){
walker.steps += 1;
a[walker.row][walker.col] = walker.steps;
if(walker.steps == n * n)//goal
break;
Walker left = proceed_left(walker);
if(a[left.row][left.col] == 0)//left side is vacant
walker = left;
else
walker = go_forward(walker);
}
for(int r = 0; r < n; ++r){
for(int c = 0; c < n; ++c){
if(c)
putchar(' ');
printf("%2d", a[r][c]);
}
puts("");
}
}
Here is a program that includes the function spiral_fill(), which fills a square array with sequential ints, starting from 1 at the center, and proceeding in a counter-clockwise spiral. The function fills the array by first storing a 1 in the center, then filling the L-shaped region above and to the left, then below and to the right, and continuing until the array is filled.
#include <stdio.h>
#define ARR_SZ 3
void spiral_fill(size_t arr_sz, int arr[arr_sz][arr_sz]);
void print_arr(size_t rows, size_t cols, int arr[rows][cols]);
int main(void)
{
int test_arr[ARR_SZ][ARR_SZ];
spiral_fill(ARR_SZ, test_arr);
print_arr(ARR_SZ, ARR_SZ, test_arr);
return 0;
}
void spiral_fill(size_t arr_sz, int arr[arr_sz][arr_sz])
{
int center = arr_sz / 2;
int current = center;
int start_col, stop_col, start_row, stop_row;
size_t layer = 0;
int next_val = 1;
arr[center][center] = next_val++;
++layer;
while (layer < arr_sz) {
if (layer % 2) { // For odd layers, fill upper L
current -= layer;
start_col = center + layer / 2;
stop_col = center - (layer + 1) / 2;
for (int j = start_col; j >= stop_col; j--) {
arr[current][j] = next_val++;
}
start_row = center - layer / 2;
stop_row = center + layer / 2;
for (int i = start_row; i <= stop_row; i++) {
arr[i][current] = next_val++;
}
++layer;
} else { // For even layers, fill lower L
current += layer;
start_col = center - layer / 2;
stop_col = center + layer / 2;
for (int j = start_col; j <= stop_col; j++) {
arr[current][j] = next_val++;
}
start_row = center + (layer - 1) / 2;
stop_row = center - layer / 2;
for (int i = start_row; i >= stop_row ; i--) {
arr[i][current] = next_val++;
}
++layer;
}
}
}
void print_arr(size_t rows, size_t cols, int arr[rows][cols])
{
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
printf("%-5d ", arr[i][j]);
}
putchar('\n');
}
}
Here is a 3X3 array:
3 2 9
4 1 8
5 6 7
Here is a 6X6 array:
31 30 29 28 27 26
32 13 12 11 10 25
33 14 3 2 9 24
34 15 4 1 8 23
35 16 5 6 7 22
36 17 18 19 20 21
How do I print this?
1 3 6 10 15
2 5 9 14
4 8 13
7 12
11
I am able to come out the following code but I am unsure on how I can combine the following to produce the result I want.
#include <stdio.h>
int main()
{
int n = 5;
int start = a;
int i;
int j;
for (j = 1; j <= n; j++) /* This for loop produce 1 3 6 10 15 */
{
start = start + j;
printf("%d ", start);
}
printf("\n");
start = 1;
for (i = 0; i < 5; i++) /* This for loop produce 1 2 4 7 11 */
{
start = start + i;
printf("%d ", start);
}
return 0;
}
Please guide me as I am really not good in programming.
If you just want to print the mentioned pattern the fastest way is:
#include <stdio.h>
int main(){
puts("1 3 6 10 15");
puts("2 5 9 14");
puts("4 8 13");
puts("7 12");
puts("11");
return 0;
}
P.S: You are not taking any input from user.
Use nested loops.
#include <stdio.h>
int main()
{
int n = 5;
int row_start = 1, step, start_step = 2; row_step = 1, current;
for (int j = 1; j <= n; j++) /* This for loop produces the rows */
{
current = step = row_start;
step = start_step;
for(int i = j; i <= 5; i++) /* This for loop produces one row */
{
printf("%d ", current);
current += step;
++step;
}
printf("\n");
row_start += row_step;
++row_step;
++start_step;
}
return 0;
}
hi I am trying to print a 4 x 4 matrix in clockwise direction,
Input:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
Expected output is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
My code is:
int MAXR=3,MAXC=3,MINR=0,MINC=0;
while(MINR < MAXR && MINC < MAXC)
{
for(i=MINC;i<=MAXC;i++)
{
printf("%d ",arr[MINR][i]);
}
for(j=MINR+1;j<=MAXR;j++)
{
printf("%d ",arr[j][MAXC]);
}
for(i=MAXC-1;i>=MINC;i--)
{
printf("%d ",arr[MAXR][i]);
}
MINR++;
if((MINR%2)==0)
{
MINC=MINC+2;
}
//MAXR--;
//MAXC--;
//printf("\nMAXR=%d MINR=%d\n",MAXR,MINR);
for(j=MAXR-1;j>MINR;j--)
{
printf("%d ",arr[j][MINC]);
}
MAXR--;
MAXC--;
}
But output is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 11
Please help me to fix the bug!
Thanks!
output is:
I hope you have fixed your defect by now. But it was a fun spec, so here is my version:
gcc (GCC) 4.7.3: gcc -Wall -Wextra -std=c99 spiral.c
#include <stdio.h>
int main() {
int matrix[4][4] = {
{ 1, 2, 3, 4 },
{ 12, 13, 14, 5 },
{ 11, 16, 15, 6 },
{ 10, 9, 8, 7 } };
int edge = sizeof(matrix[0]) / sizeof(int) - 1;
int i = 0;
int j = 0;
printf("%d ", matrix[i][j]);
for (int c = 0; c < edge; ++c) { printf("%d ", matrix[i][++j]); }
while (0 < edge) {
for (int c = 0; c < edge; ++c) { printf("%d ", matrix[++i][j]); }
for (int c = 0; c < edge; ++c) { printf("%d ", matrix[i][--j]); }
--edge;
for (int c = 0; c < edge; ++c) { printf("%d ", matrix[--i][j]); }
for (int c = 0; c < edge; ++c) { printf("%d ", matrix[i][++j]); }
--edge;
}
return 0;
}
My approach was to write out the sequence of required changes to i and j and find the pattern. What I found was that the pattern appeared after the first line, so I did that as a separate initial step.
The following code will help you to print of a matrix of any size (rows/cols) clockwisely.
void printMatrixClockwisely(int** numbers, int rows, int columns)
{
if(numbers == NULL || columns <= 0 || rows <= 0)
return;
int start = 0;
while(columns > start * 2 && rows > start * 2)
{
PrintMatrixInCircle(numbers, columns, rows, start);
++start;
}
}
void printNumber(int number)
{
printf("%d\t", number);
}
void PrintMatrixInCircle(int** numbers, int columns, int rows, int start)
{
int endX = columns - 1 - start;
int endY = rows - 1 - start;
// print a row from left to right
for(int i = start; i <= endX; ++i)
{
int number = numbers[start][i];
printNumber(number);
}
// print a col from up to down
if(start < endY)
{
for(int i = start + 1; i <= endY; ++i)
{
int number = numbers[i][endX];
printNumber(number);
}
}
// print a row from right to left
if(start < endX && start < endY)
{
for(int i = endX - 1; i >= start; --i)
{
int number = numbers[endY][i];
printNumber(number);
}
}
// print a col from down to up
if(start < endX && start < endY - 1)
{
for(int i = endY - 1; i >= start + 1; --i)
{
int number = numbers[i][start];
printNumber(number);
}
}
}