Computer >> 컴퓨터 >  >> 프로그램 작성 >> C 프로그래밍

C 언어에서 2차원 배열이란 무엇입니까?

<시간/>

배열은 공통 이름으로 저장하는 관련 항목 그룹입니다.

구문

배열을 선언하는 구문은 다음과 같습니다 -

datatype array_name [size];

배열 유형

배열은 크게 세 가지 유형으로 분류됩니다. 다음과 같습니다 -

  • 1차원 배열
  • 2차원 배열
  • 다차원 배열

초기화

배열은 다음과 같은 두 가지 방법으로 초기화할 수 있습니다. -

  • 컴파일 시간 초기화
  • 런타임 초기화.

2개의 다차원 배열

이들은 값 테이블을 행렬 응용 프로그램에 저장해야 하는 상황에서 사용됩니다.

구문

구문은 다음과 같습니다 -

datatype array_ name [rowsize] [column size];

예를 들어 정수 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("\n");
   }
}

출력

출력은 다음과 같습니다 -

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("\n");
   }
}

출력

출력은 다음과 같습니다 -

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: \n");
   for(i=0;i<2;i++){
      for(j=0;j<3;j++){
         printf("A[%d][%d] :",i,j);
         scanf("%d",&A[i][j]);
      }
      printf("\n");
   }
   for(i=0;i<2;i++){
      for(j=0;j<3;j++){
         printf("B[%d][%d] :",i,j);
         scanf("%d",&B[i][j]);
      }
      printf("\n");
   }
   //Calculating sum and printing output//
   printf("Sum array is : \n");
   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("\n");
   }
   //Calculating product and printing output//
   printf("Product array is : \n");
   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("\n");
   }
}

출력

출력은 다음과 같습니다 -

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