Using C23 constexpr for the size, build and print a 4 × 4 identity matrix in a file-scope array.
Solution
main.c
#include <stdio.h>
constexpr int N = 4;
static int identity[N][N]; /* allowed: N is a constant expression */
int main(void) {
for (int i = 0; i < N; i++)
identity[i][i] = 1;
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++)
printf("%d ", identity[r][c]);
printf("\n");
}
return 0;
}
Output Verified by compiling and running
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
A file-scope array needs a constant size. Before C23 that meant #define N 4 or an enum; constexpr int N = 4; gives the same compile-time constant with a real type and scope. The static array starts zeroed, so only the diagonal is set.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!