Reputation: 11
I have tried like this, but I can print this pattern correctly only for 4.
When I give 5,2 or other numbers as input the code fails...
How can I modify this program to match the exact output? I have searched in many platforms but cannot find the answer..
This is the expected output:
input: 2
2 2 2
2 1 2
2 2 2
input: 5
5 5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4 5
5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 2 1 2 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 3 3 3 3 4 5
5 4 4 4 4 4 4 4 5
5 5 5 5 5 5 5 5 5
input: 7
7 7 7 7 7 7 7 7 7 7 7 7 7
7 6 6 6 6 6 6 6 6 6 6 6 7
7 6 5 5 5 5 5 5 5 5 5 6 7
7 6 5 4 4 4 4 4 4 4 5 6 7
7 6 5 4 3 3 3 3 3 4 5 6 7
7 6 5 4 3 2 2 2 3 4 5 6 7
7 6 5 4 3 2 1 2 3 4 5 6 7
7 6 5 4 3 2 2 2 3 4 5 6 7
7 6 5 4 3 3 3 3 3 4 5 6 7
7 6 5 4 4 4 4 4 4 4 5 6 7
7 6 5 5 5 5 5 5 5 5 5 6 7
7 6 6 6 6 6 6 6 6 6 6 6 7
7 7 7 7 7 7 7 7 7 7 7 7 7
Here is the code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n;
scanf("%d", &n);
// Complete the code to print the pattern.
int limit = (n * 2) - 1;
int row, column;
for (row = 1; row <= limit; row++) {
for (column = 1; column <= limit; column++) {
if (column == 1 || column == 7 || row == 1 || row == 7)
printf("%d ", n);
else if (column == 2 || column == 6 || row == 2 || row == 6)
printf("%d ", n - 1);
else if (column == 3 || column == 5 || row == 3 || row == 5)
printf("%d ", n - 2);
else if (column == 4 || column == 4 || row == 4 || row == 4)
printf("%d ", n - 3);
}
printf("\n");
}
return 0;
}
Upvotes: 1
Views: 69
Reputation: 212268
You are working too hard. (Or, depending on your point of view, not working hard enough!). Instead of chaining a lot of if statments, just compute the value based on the current location. Something like:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define max(x, y) ((x) > (y) ? (x) : (y))
int
main(int argc, char **argv)
{
char *k = "";
int n = argc > 1 ? strtol(argv[1], &k, 10) : 5;
if( *k || n > 9 || n < 1 ){
fprintf(stderr, "Invalid argument. Must be 0 < n < 10\n");
return 1;
}
for( int x = 1 - n; x < n; x += 1 ){
for( int y = n - 1; y > -n; y -= 1 ){
printf("%d", 1 + max(abs(x),abs(y)));
putchar(y == 1 - n ? '\n' : ' ');
}
}
}
Upvotes: 2