먼저 C 프로그래밍 언어의 1차원 배열 처리를 이해합시다.
1D 배열 처리
1D Array(읽기)에 값을 저장하는 방법은 다음과 같습니다. -
int num[5]
int i;
for(i=0;i<5;i++){
Scanf("%d",&num[i]);
} 1차원 배열에서 저장된 값을 가져오기(쓰기)는 다음과 같이 수행됩니다. -
int num[5]
int i;
for(i=0;i<5;i++){
printff("%d",num[i]);
} 예시 프로그램
다음은 배열에서 역순으로 요소를 인쇄하는 C 프로그램입니다. -
#include<stdio.h>
void main(){
//Declaring the array - run time//
int array[5],i;
//Reading elements into the array//
printf("Enter elements into the array: \n");
//For loop//
for(i=0;i<5;i++){
//Reading User I/p//
printf("array[%d] :",i);
scanf("%d",&array[i]);
}
//Displaying reverse order of elements in the array//
printf("The elements from the array displayed in the reverse order are : \n");
for(i=4;i>=0;i--){
//Displaying O/p//
printf("array[%d] :",i);
printf("%d\n",array[i]);
}
} 출력
위의 프로그램이 실행되면 다음과 같은 결과가 생성됩니다 -
Enter elements into the array: array[0] :1 array[1] :2 array[2] :3 array[3] :4 array[4] :5 The elements from the array displayed in the reverse order are: array[4] :5 array[3] :4 array[2] :3 array[1] :2 array[0] :1
2D 배열 처리
2D Array(읽기)에 값을 저장하는 방법은 다음과 같습니다. -
int a[4][3];
int i,j;
for(i=0;i<4;i++){
for(j=0;j<3;j++){
scanf("%d",&a[i][j]);
}
} 2차원 배열에서 저장된 값을 가져오기(쓰기)는 다음과 같이 수행됩니다. -
int a[4][3];
int i,j;
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("%d",a[i][j]);
}
} 예시 프로그램
다음은 런타임 컴파일을 사용하여 배열에 있는 모든 요소의 합과 곱을 계산하는 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] :4 A[1][0] :1 A[1][1] :2 A[1][2] :3 B[0][0] :4 B[0][1] :5 B[0][2] :3 B[1][0] :2 B[1][1] :1 B[1][2] :2 Sum array is: 6 8 7 3 3 5 Product array is: 8 15 12 2 2 6