even strings of an array in backwards way - c

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

Related

how to write a code that prints an specific numerical spiral pattern in c using for loops without array

I want to write a code that gets the integer n from the user and prints numbers in a spiral pattern from 1 to n*n without using arrays.
output for entering 5
input3
output:
1 2 3
8 9 4
7 6 5
do you have any suggestions on how to write this code?
EDIT:
here is the code using arrays:
#include <stdio.h>
int main(){
/*declaration of the variables*/
int i, j, ascendingNumbers;
int leftAndTop, rightAndBottom;
int size;
scanf("%d", &size);
int matrix[size][size];
leftAndTop = 0;
rightAndBottom = size - 1;
ascendingNumbers = 1;
/*filling the array*/
for(i = 1; i <= size/2; i++, leftAndTop++, rightAndBottom--){
/*left to right*/
for(j = leftAndTop; j <= rightAndBottom; j++, ascendingNumbers++){
matrix[leftAndTop][j] = ascendingNumbers;
}
/*top to bottom*/
for(j = leftAndTop + 1; j <= rightAndBottom; j++, ascendingNumbers++){
matrix[j][rightAndBottom] = ascendingNumbers;
}
/*right to left*/
for(j = rightAndBottom-1; j >= leftAndTop; j--, ascendingNumbers++){
matrix[rightAndBottom][j] = ascendingNumbers;
}
/*bottom to top*/
for(j = rightAndBottom - 1; j >= leftAndTop+1; j--, ascendingNumbers++){
matrix[j][leftAndTop] = ascendingNumbers;
}
}
/*fill the center for odd size*/
if(size % 2){
matrix[leftAndTop][j + 1] = ascendingNumbers;
}
/*print*/
for(i = 0; i < size; i++){
for(j = 0; j < size; j++){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
One solution is to take code that already can fill an array with the spiral pattern, and put it in a nested loop that uses that code to find the number for the current printing position. There are certainly more efficient solutions, but this allows you to transform a solution that works for arrays into one that does not need arrays.
The first program here uses an array to print a spiral pattern of numbers. The second program is a modified version of the first that prints a number when the printing position matches the position in the spiral loop instead of storing it in an array. I'll leave it to you to see if you can modify your existing code to accomplish this.
Using a 2d array:
/* A program that prints a spiral using a 2d array */
#include <stdio.h>
int main(int argc, char *argv[])
{
int size;
if (argc < 2 || (sscanf(argv[1], "%d", &size) != 1) || size < 1) {
fprintf(stderr, "Usage: spiral N [N > 0]\n");
return 1;
}
int arr[size][size];
int num_elems = size * size;
enum Dir { RIGHT, DOWN, LEFT, UP };
int num_directions = 4;
int side_len = size;
int row = 0; // arr row index
int col = 0; // arr column index
int pos = 0; // position in a side
// travel around the spiral to fill the array
enum Dir direction = RIGHT;
for (int i = 0; i < num_elems; i++) {
arr[row][col] = i + 1;
++pos;
if (pos == side_len) { // change direction
direction = (direction + 1) % num_directions;
pos = 0;
// having changed direction, shorten side_len in two cases
if (direction == DOWN || direction == UP) {
--side_len;
}
}
switch (direction) {
case RIGHT:
++col;
break;
case DOWN:
++row;
break;
case LEFT:
--col;
break;
case UP:
--row;
break;
default:
fprintf(stderr, "Unexpected value in switch statement\n");
return 1;
}
}
for (row = 0; row < size; row++) {
for (col = 0; col < size; col++) {
printf("%4d", arr[row][col]);
}
putchar('\n');
}
putchar('\n');
return 0;
}
Using only loops:
/* A program that prints a spiral using loops but no arrays */
#include <stdio.h>
int main(int argc, char *argv[])
{
int size;
if (argc < 2 || (sscanf(argv[1], "%d", &size) != 1) || size < 0) {
fprintf(stderr, "Usage: spiral N [N >= 0]\n");
return 1;
}
int num_elems = size * size;
enum Dir { RIGHT, DOWN, LEFT, UP };
int num_directions = 4;
// loop printing positions: print a row at a time
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
int side_len = size; // length of current side
int row = 0; // arr row index
int col = 0; // arr column index
int pos = 0; // position in a side
// travel around spiral until printing number is reached
enum Dir direction = RIGHT;
for (int i = 0; i < num_elems; i++) {
if (row == y && col == x) { // print and escape loop
printf("%4d", i + 1);
break;
}
++pos;
if (pos == side_len) { // change direction
direction = (direction + 1) % num_directions;
pos = 0;
// having changed direction, shorten side_len in two cases
if (direction == DOWN || direction == UP) {
--side_len;
}
}
switch (direction) {
case RIGHT:
++col;
break;
case DOWN:
++row;
break;
case LEFT:
--col;
break;
case UP:
--row;
break;
default:
fprintf(stderr, "Unexpected value in switch statement\n");
return 1;
}
}
}
// newline after row
putchar('\n');
}
// newline after printing all numbers
putchar('\n');
return 0;
}
Here are a couple of sample interactions with the second program:
>$ ./spiral2 3
1 2 3
8 9 4
7 6 5
>$ ./spiral2 6
1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11

Fill 2d array in spiral order in c

I'm doing program where I enter the number from keyboard. Then 2d array is created, and it's filled in spiral order till this number. All elements after the number will be equal to 0; The function fills the array in spiral order (to right -> down -> left -> up).
Code is:
#include <stdio.h>
#include <time.h>
void spiral(int array[100][100], int m, int n, int s)
{
int size, b, x = 0, y = 1, num = 1;
size = m*n;
for (num=1;num<=size+1;num++)
{
for (b = x; b < n; b++)
{
if (num <=s) {
array[x][b] = num;
num++;
}
else array[x][b] = 0;
}
if (num == size + 1)
{
break;
}
for (b = y; b < m; b++)
{
if (num <=s) {
array[b][n - 1] = num;
num++;
}
else array[b][n - 1] = 0;
}
if (num == size + 1)
{
break;
}
y++;
n--;
for (b = n - 1; b > x; b--)
{
if (num <= s) {
array[m - 1][b] = num;
num++;
}
else array[m - 1][b] = 0;
}
if (num == size + 1)
{
break;
}
for (b = m - 1; b > x; b--)
{
if (num <= s) {
array[b][x] = num;
num++;
}
else array[b][x] = 0;
}
x++;
m--;
}
}
int main()
{
int m, n, s, array[100][100];
srand(time(NULL));
//m=3;
// n=4;
m = 2 + rand() % 5;
n = 2 + rand() % 5;
//memset(array, 0, sizeof(array[0][0]) * 10 * 10);
printf("enter the number \n");
scanf("%i", &s);
spiral(array, m, n, s);
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
printf("%i\t", array[i][j]);
}
printf("\n");
}
return (0); }
However it doesn't work always correctly.
For example when i enter 15 and the program generates 4*3 array the output is`
1 2 3
10 12 4
9 -858993460 5
8 7 6`
However expected output is
1 2 3
10 11 4
9 12 5
8 7 6
Or when i enter 15 and the program generates 4*5 array the output is
1 2 3 4 5
14 0 0 0 6
13 0 0 0 7
12 11 10 9 8
And the expected output is
1 2 3 4 5
14 15 0 0 6
13 0 0 0 7
12 11 10 9 8
I can't find whats wrong with this code.
Try this:
void printArray(int array[10][10], int m, int n) {
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
printf("%i\t", array[i][j]);
}
printf("\n");
}
printf("\n");
}
void spiral(int array[10][10], int m, int n, int s)
{
int size, b, x = 0, y = 1, num = 1;
size = m*n;
while ( num <= s )
{
for (b = x; b < n; b++)
{
if (num <= s) {
array[x][b] = num;
num++;
} else array[x][b] = 0;
}
if (num == size + 1)
{
break;
}
for (b = y; b < m; b++)
{
if (num <= s) {
array[b][n - 1] = num;
num++;
} else array[b][n - 1] = 0;
}
if (num == size + 1)
{
break;
}
y++;
n--;
for (b = n - 1; b > x; b--)
{
if (num <= s) {
array[m - 1][b] = num;
num++;
} else array[m - 1][b] = 0;
}
if (num == size + 1)
{
break;
}
for (b = m - 1; b > x; b--)
{
if (num <= s) {
array[b][x] = num;
num++;
} else array[b][x] = 0;
}
x++;
m--;
}
}
int main()
{
int m, n, s, array[10][10];
srand(time(NULL));
m = 2 + rand() % 5;
n = 2 + rand() % 5;
memset(array, 0, sizeof(array[0][0]) * 10* 10);
printf("enter the number \n");
scanf("%i", &s);
spiral(array, m, n, s);
printArray(array, m, n);
return (0);
}
Before you had some weird for loop on top of your spiral function. The num++ in it interfered with the fact that you already increased num by one and made it skip the number the next time it would write in the uppermost line.
I changed it to a while loop that runs until num>s and it seems to work for me now.
Note that I just added printArray for easier debugging.

Program in C to generate this pattern

This is the code that I've tried which simply generates numbers and prints. I am totally stuck about how to access the row numbers and interchange the printing positions of the rows of the matrix.
#include <stdio.h>
int main(void)
{
int i,a[10][10],j,n,count=1;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
a[i][j]=count;
printf("%d\t",count++);
}
printf("\n");
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d*\t",a[i][j]);
printf("\n");
}
return 0;
}
I am providing a link for the pattern which is to be printed, please check.
https://drive.google.com/open?id=1DKwW8dQggzNjjtAxwPTEI3nRS9AmpK-2Zw
My approach is to avoid the matrix altogether:
#include <stdio.h>
int main() {
int number;
(void) scanf("%d", &number);
int twice = 2 * number;
int squared = number * number;
for (int row = 0, upward = number, downward = 2 * squared; row < number; row++) {
int n = ((upward > squared) ? downward : upward) - number + 1;
for (int column = 0; column < number; column++) {
printf("%d*\t", n++);
}
printf("\n");
upward += twice;
downward -= twice;
}
return 0;
}
EXAMPLES
> ./a.out
3
1* 2* 3*
7* 8* 9*
4* 5* 6*
> ./a.out
4
1* 2* 3* 4*
9* 10* 11* 12*
13* 14* 15* 16*
5* 6* 7* 8*
> ./a.out
5
1* 2* 3* 4* 5*
11* 12* 13* 14* 15*
21* 22* 23* 24* 25*
16* 17* 18* 19* 20*
6* 7* 8* 9* 10*
>
This is my solution to the problem:
#include <stdio.h>
int main() {
int input = 0;
int i = 0;
int j = 0;
int k = 1;
scanf("%d", &input);
int array[input][input];
for(i = 0; i < (input/2); i++) {
for(j = 0; j < input; j++) {
array[i][j] = k;
k++;
}
for(j = 0; j < input; j++) {
array[input-1-i][j] = k;
k++;
}
}
if((input % 2) == 1) {
for(j = 0; j < input; j++) {
array[input/2][j] = k;
k++;
}
}
for(i = 0; i < input; i++) {
for(j = 0; j < input; j++) {
printf("\t%d", array[i][j]);
}
printf("\n");
}
return 0;
}
These are the outputs of the program for diferent inputs:
1
1
2
1 2
3 4
3
1 2 3
7 8 9
4 5 6
4
1 2 3 4
9 10 11 12
13 14 15 16
5 6 7 8
5
1 2 3 4 5
11 12 13 14 15
21 22 23 24 25
16 17 18 19 20
6 7 8 9 10

Print a pattern in C

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;
}

Clockwise Print of a 4X4 matrix in c

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);
}
}
}

Resources