New to programming, im doing a problem where I’m supposed to print a square pattern of decreasing numbers like 5 would give:
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
i thought of using arrays and repeatedly subtracting from the array and printing it to solve this;
#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 *arr;
int k=1;
arr = calloc(2*n-1, sizeof(char));
for (int i = 0; i < 2*n-1; i++) {
*(arr + i) = n;
}
do {
for (int i = 0; i < 2*n-1; i++) {
printf("%d ", arr[i]);
}
printf("n");
for (int i = k; i < 2*n-1-k; i++) {
arr[i] = arr[i] - 1;
}
k++;
} while ( k <= n);
k=n-1;
for (int j = 1; j < n; j++) {
for (int i = k; i <2*n-1-k; i++) {
arr[i]++;
}
k--;
for (int i = 0; i < 2*n-1; i++) {
printf("%d ", arr[i]);
}
printf("n");
}
return 0;
}
this works in Visual studio code, but not on the compiler on the site, and not on another online compiler i tested it on. I’m assuming i messed up on the calloc part. What’s the problem here?
2
Answers
sizeof(int)
, notsizeof(char)
.Why not just:
?