---
# System prepended metadata

title: 二維矩陣翻轉
tags: [初階程式設計]

---

# 二維矩陣翻轉 

大家不客氣

```cpp=
#include <stdio.h>
#include <time.h>
#include <string.h>
#define SIZE 10

// function to print a two dimensional array
void printArray(int a[SIZE][SIZE], int size){
    for(int i = 0; i < size; i++){
        for(int j= 0; j < size; j++){
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }
}

int main(){

    srand(time(0));
    int n;

    // get the size of the square
    printf("Please enter the size of the square.(size between 2 and 10): ");
    scanf("%d", &n);

    // check whether the input number is within the range
    while(n < 2 || n > 10){
        printf("Invalid size. Please enter again.(size between 2 and 10): ");
        scanf("%d", &n);
    }

    // initialize the dimensional arrays
    int arr[SIZE][SIZE] = {0}, brr[SIZE][SIZE] = {0};
    // memset(arr, 0, sizeof(arr));

    // print the initialized square
    printf("\nInitialized square:\n");
    printArray(arr, n);

    // generate the random numbers for the dimensional array
    for(int i = 0; i < n; i++){
        for(int j= 0; j < n; j++){
            arr[i][j] = rand() % 99 + 1;
        }
    }

    // print the randomized square
    printf("\nRandomized square:\n");
    printArray(arr, n);

    // rotate the dimensional array
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            brr[j][i] = arr[n-i-1][j];
        }
    }

    // print the rotated square
    printf("\nSquare rotated 90 degree:\n");
    printArray(brr, n);
}
```