Computer >> 컴퓨터 >  >> 프로그래밍 >> C 프로그래밍

C 언어로 배열에 요소 삽입하는 방법 완벽 정리

배열 요소 삽입 개요

C 언어에서는 배열의 시작 위치, 중간, 끝 등 원하는 어느 위치에든 요소를 삽입할 수 있습니다.

다만 요소를 삽입하면 기존 요소들의 위치(인덱스)가 한 칸씩 뒤로 밀려날 뿐, 배열의 실제 크기 자체가 늘어나는 것은 아닙니다. C 언어의 배열은 선언 시점에 크기가 고정되기 때문에, 삽입 작업은 기존 요소들을 이동시키는 방식으로 수행됩니다.

요소 삽입 로직

배열에 요소를 삽입할 때 사용되는 기본 로직은 다음과 같습니다.

  • 배열의 크기를 입력받습니다.
  • 요소를 삽입할 위치를 입력받습니다.
  • 해당 위치에 삽입할 값을 입력받습니다.

핵심 삽입 코드는 다음과 같습니다.

for(i=size-1;i>=pos-1;i--)
    student[i+1]=student[i];
    student[pos-1]= value;

위 코드는 삽입 위치부터 배열 끝까지의 요소를 한 칸씩 뒤로 이동시킨 후, 지정한 위치에 새로운 값을 넣는 방식으로 동작합니다. 최종 배열은 for 반복문을 사용하여 출력하면 됩니다.

전체 프로그램

#include<stdio.h>
int main(){
    int student[40],pos,i,size,value;
    printf("enter no of elements in array of students:");
    scanf("%d",&size);
    printf("enter %d elements are:\n",size);
    for(i=0;i<size;i++)
        scanf("%d",&student[i]);
    printf("enter the position where you want to insert the element:");
    scanf("%d",&pos);
    printf("enter the value into that poition:");
    scanf("%d",&value);
    for(i=size-1;i>=pos-1;i--)
        student[i+1]=student[i];
    student[pos-1]= value;
    printf("final array after inserting the value is\n");
    for(i=0;i<=size;i++)
        printf("%d\n",student[i]);
    return 0;
}

실행 결과

enter no of elements in array of students:6
enter 6 elements are:
12
23
34
45
56
67
enter the position where you want to insert the element:3
enter the value into that poition:48
final array after inserting the value is
12
23
48
34
45
56
67

위 실행 결과를 보면, 3번째 위치에 값 48을 삽입했을 때 기존의 34부터 67까지의 요소들이 한 칸씩 뒤로 밀려난 것을 확인할 수 있습니다. 이처럼 배열 요소 삽입은 새로운 공간을 추가하는 것이 아니라, 기존 데이터를 이동시켜 빈자리를 만들고 그 자리에 값을 채우는 방식으로 이루어집니다.