C 배열에 요소 삽입하기

CBeginner
지금 연습하기

소개

C 언어에서 배열은 연속된 메모리 위치에 저장된 유사한 데이터 유형의 모음입니다. 단일 변수 이름 아래에 여러 값을 저장하여 메모리 공간을 절약하고 코드 구조를 단순화하는 데 도움이 됩니다. 이 랩에서는 배열의 특정 위치에 요소를 삽입하는 방법을 배웁니다.

참고: 코딩을 연습하고 gcc 를 사용하여 컴파일하고 실행하는 방법을 배우려면 직접 ~/project/main.c 파일을 생성해야 합니다.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

배열 생성

이 단계에서는 초기 요소가 있는 배열을 생성하고 해당 값을 표시합니다.

#include <stdio.h>

int main() {
    // Define variables and array
    int array[5] = {10, 20, 30, 40, 50};
    int n = 5, i;

    printf("Initial array: ");
    for(i=0; i<n; i++) {
        printf("%d ", array[i]);
    }

    return 0;
}

사용자 입력 받기

이 단계에서는 삽입할 새 값과 값을 삽입할 인덱스에 대한 사용자 입력을 받습니다.

#include <stdio.h>

int main() {
    // Define variables and array
    int array[5] = {10, 20, 30, 40, 50};
    int n = 5, i, value, position;

    printf("Initial array: ");
    for(i=0; i<n; i++) {
        printf("%d ", array[i]);
    }

    // Take input for new value and position
    printf("\n\nEnter the value to insert: ");
    scanf("%d", &value);

    printf("Enter the position to insert: ");
    scanf("%d", &position);

    return 0;
}

요소 삽입

이 단계에서는 주어진 위치에 새 요소를 배열에 삽입합니다. 기존 요소를 위치의 오른쪽으로 이동시키고, 새 요소를 위치 인덱스에 추가합니다.

#include <stdio.h>

int main() {
    // Define variables and array
    int array[5] = {10, 20, 30, 40, 50};
    int n = 5, i, value, position;

    printf("Initial array: ");
    for(i=0; i<n; i++) {
        printf("%d ", array[i]);
    }

    // Take input for new value and position
    printf("\n\nEnter the value to insert: ");
    scanf("%d", &value);

    printf("Enter the position to insert: ");
    scanf("%d", &position);

    // Shift the existing elements to right of the position
    for(i=n-1; i>=position-1; i--) {
        array[i+1] = array[i];
    }

    // Insert the new element at the position index
    array[position-1] = value;

    return 0;
}

결과 표시

이 단계에서는 삽입된 요소가 포함된 새 배열을 표시합니다.

#include <stdio.h>

int main() {
    // Define variables and array
    int array[5] = {10, 20, 30, 40, 50};
    int n = 5, i, value, position;

    printf("Initial array: ");
    for(i=0; i<n; i++) {
        printf("%d ", array[i]);
    }

    // Take input for new value and position
    printf("\n\nEnter the value to insert: ");
    scanf("%d", &value);

    printf("Enter the position to insert: ");
    scanf("%d", &position);

    // Shift the existing elements to right of the position
    for(i=n-1; i>=position-1; i--) {
        array[i+1] = array[i];
    }

    // Insert the new element at the position index
    array[position-1] = value;

    // Display the new array
    printf("\n\nNew array with the inserted element: ");
    for(i=0; i<n+1; i++) {
        printf("%d ", array[i]);
    }

    return 0;
}

최종 코드

다음은 배열에 요소를 삽입하는 최종 코드입니다.

#include <stdio.h>

int main() {
    // Define variables and array
    int array[5] = {10, 20, 30, 40, 50};
    int n = 5, i, value, position;

    printf("Initial array: ");
    for(i=0; i<n; i++) {
        printf("%d ", array[i]);
    }

    // Take input for new value and position
    printf("\n\nEnter the value to insert: ");
    scanf("%d", &value);

    printf("Enter the position to insert: ");
    scanf("%d", &position);

    // Shift the existing elements to right of the position
    for(i=n-1; i>=position-1; i--) {
        array[i+1] = array[i];
    }

    // Insert the new element at the position index
    array[position-1] = value;

    // Display the new array
    printf("\n\nNew array with the inserted element: ");
    for(i=0; i<n+1; i++) {
        printf("%d ", array[i]);
    }

    return 0;
}

요약

이 랩에서는 C 를 사용하여 배열의 특정 위치에 요소를 삽입하는 방법을 배웠습니다. 초기 배열을 생성하고, 새 요소와 위치에 대한 사용자 입력을 받은 다음, 기존 요소를 오른쪽으로 이동하여 지정된 위치에 요소를 삽입하고, 새로운 결과 배열을 표시했습니다.