# Logic needed with explanation.

Hi I need to come up with a solution for the following problem. Tell me how to code in C?

Input:

``````1 2 3 4
``````

Output:

``````1 2 3 4
4 1 2 1
3 4 3 2
2 1 4 3``````

``````#include<stdio>
int main(){

printf("1 2 3 4\n");
printf(" 4 1 2 1\n");
printf("3 4 3 2\n");
printf("2 1 4 3\n");
return 0;
}
``````

6 Likes

Have a look at below codes

In main use w = 4 and h = 4.
Moreover in cout (while printing), numbers larger than 4 to smaller numbers.

1 Like

1 Like

Having a problem statement would make things easier. It looks like a permutation of the input repeated 4 times but what exactly are you trying to achieve? You have to help us help you.

1 Like

i think he wants to print it in spiral form!!!

if this is ne kind of homework…then pls do it yourself…try it…if u get stuck somewhere then ask…and provide your code…it is easy…just give it a shot!!!

nice gesture Will implement it now Thanx for the explanation

3 Likes

hahaha

lol good one

Thanks a lot… I find it difficult to understand your logic… I must spend some time with the code to crack it…

You can initialize the matrix with all -1. (-1 means not visited)

1. Start with (x = 0, y = 0), written = 0

2. while x < width && arr[x][y] == -1, arr[x++][y] = next number, ++written.

3. –x, ++y

4. while y < height && arr[x][y] == -1, arr[x][y++] = next number, ++written.

5. –x, --y

6. while x >= 0 && arr[x][y] == -1, arr[x–][y] = next number, ++written.

7. ++x, --y

8. while y >= 0 && arr[x][y] == -1, arr[x][y–] = next number, ++written

9. ++x, ++y

10. if written != width * height, go to step 2
Try to implement this, if you find anything difficult do post it.