C語言中的二維陣列是什麼?


陣列是一組相關的專案,它們以一個共同的名稱儲存。

語法

宣告陣列的語法如下:

datatype array_name [size];

陣列型別

陣列大致分為三種類型。它們如下:

  • 一維陣列
  • 二維陣列
  • 多維陣列

初始化

陣列可以透過兩種方式初始化,如下所示:

  • 編譯時初始化。
  • 執行時初始化。

二維陣列

這些用於需要儲存值表(或)矩陣應用程式的情況。

語法

語法如下所示:

datatype array_ name [rowsize] [column size];

例如 int a[5] [5];

a[0][0]
10
a[0][1]
20
a[0][2]
30
a[1][0]
40
a[1][1]
50
a[1][2]
60
a[2][0]
a[2][1]a[2][2]


以下是 C 程式的編譯時初始化

示例

 線上演示

#include<stdio.h>
main ( ){
   int a[3][3] = {10,20,30,40,50,60,70,80,90};
   int i,j;
   printf ("elements of the array are");
   for ( i=0; i<3; i++){
      for (j=0;j<3; j++){
         printf("%d \t", a[i] [j]);
      }
      printf("
");    } }

輸出

輸出如下所示:

elements of the array are:
10 20 30
40 50 60
70 80 90

以下是 C 程式的執行時初始化

示例

 線上演示

#include<stdio.h>
main ( ){
   int a[3][3] ,i,j;
   printf ("enter elements of array");
   for ( i=0; i<3; i++){
      for (j=0;j<3; j++){
         scanf("%d", &a[i] [j]);
      }
   }
   printf("elements of the array are");
   for ( i=0; i<3; i++){
      for (j=0;j<3; j++){
         printf("%d\t", a[i] [j]);
      }
      printf("
");    } }

輸出

輸出如下所示:

Enter elements of array :
1 2 3 4 5 6 7 8 9
Elements of the array are
1 2 3
4 5 6
7 8 9

以下是使用執行時編譯計算陣列中所有元素的和與積的 C 程式:

示例

 線上演示

#include<stdio.h>
void main(){
   //Declaring the array - run time//
   int A[2][3],B[2][3],i,j,sum[i][j],product[i][j];
   //Reading elements into the array's A and B using for loop//
   printf("Enter elements into the array A: 
");    for(i=0;i<2;i++){       for(j=0;j<3;j++){          printf("A[%d][%d] :",i,j);          scanf("%d",&A[i][j]);       }       printf("
");    }    for(i=0;i<2;i++){       for(j=0;j<3;j++){          printf("B[%d][%d] :",i,j);          scanf("%d",&B[i][j]);       }       printf("
");    }    //Calculating sum and printing output//    printf("Sum array is :
");    for(i=0;i<2;i++){       for(j=0;j<3;j++){          sum[i][j]=A[i][j]+B[i][j];          printf("%d\t",sum[i][j]);       }       printf("
");    }    //Calculating product and printing output//    printf("Product array is :
");    for(i=0;i<2;i++){       for(j=0;j<3;j++){          product[i][j]=A[i][j]*B[i][j];          printf("%d\t",product[i][j]);       }       printf("
");    } }

輸出

輸出如下所示:

Enter elements into the array A:
A[0][0] :2
A[0][1] :3
A[0][2] :1
A[1][0] :2
A[1][1] :4
A[1][2] :5
B[0][0] :1
B[0][1] :2
B[0][2] :3
B[1][0] :5
B[1][1] :6
B[1][2] :7
Sum array is :
3 5 4
7 10 12
Product array is :
2 6 3
10 24 35

更新於: 2021年3月15日

3K+ 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.