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

C 언어에서 for 루프로 배열의 짝수와 홀수 분리하는 방법

배열(array)은 여러 개의 관련된 데이터 항목들을 하나의 이름으로 저장할 수 있는 자료구조입니다.

예를 들어, int student[30];처럼 선언하면 'student'라는 배열 이름 하나로 30개의 데이터 항목을 관리할 수 있습니다.

배열의 주요 연산

  • 탐색(Searching) - 특정 요소가 배열에 존재하는지 확인합니다.
  • 정렬(Sorting) - 배열의 요소들을 오름차순 또는 내림차순으로 정렬합니다.
  • 순회(Traversing) - 배열의 모든 요소를 순서대로 처리합니다.
  • 삽입(Inserting) - 배열에 새로운 요소를 추가합니다.
  • 삭제(Deleting) - 배열에서 특정 요소를 제거합니다.

짝수 찾기 로직

배열에서 짝수를 찾는 기본 로직은 나머지 연산자(%)를 활용하는 것입니다. 어떤 수를 2로 나눈 나머지가 0이면 짝수입니다.

for(i = 0; i < size; i ++){
    if(a[i] % 2 == 0){
        even[Ecount] = a[i];
        Ecount++;
    }
}

홀수 찾기 로직

반대로 홀수는 2로 나눈 나머지가 0이 아닌 경우입니다.

for(i = 0; i < size; i ++){
    if(a[i] % 2 != 0){
        odd[Ocount] = a[i];
        Ocount++;
    }
}

결과 출력 함수

분리된 짝수 배열을 출력하려면 아래와 같이 display 함수를 호출합니다.

printf("no: of elements comes under even are = %d \n", Ecount);
printf("The elements that are present in an even array is: ");
void display(int a[], int size){
    int i;
    for(i = 0; i < size; i++){
        printf("%d \t ", a[i]);
    }
    printf("\n");
}

홀수 배열도 동일한 방식으로 출력할 수 있습니다.

printf("no: of elements comes under odd are = %d \n", Ocount);
printf("The elements that are present in an odd array is : ");
void display(int a[], int size){
    int i;
    for(i = 0; i < size; i++){
        printf("%d \t ", a[i]);
    }
    printf("\n");
}

전체 프로그램

다음은 C 언어에서 for 루프를 사용하여 배열의 짝수와 홀수를 분리하는 완전한 프로그램입니다.

#include<stdio.h>
void display(int a[], int size);
int main(){
    int size, i, a[10], even[20], odd[20];
    int Ecount = 0, Ocount = 0;
    printf("enter size of array :\n");
    scanf("%d", &size);
    printf("enter array elements:\n");
    for(i = 0; i < size; i++){
        scanf("%d", &a[i]);
    }
    for(i = 0; i < size; i ++){
        if(a[i] % 2 == 0){
            even[Ecount] = a[i];
            Ecount++;
        }
        else{
            odd[Ocount] = a[i];
            Ocount++;
        }
    }
    printf("no: of elements comes under even are = %d \n", Ecount);
    printf("The elements that are present in an even array is: ");
    display(even, Ecount);
    printf("no: of elements comes under odd are = %d \n", Ocount);
    printf("The elements that are present in an odd array is : ");
    display(odd, Ocount);
    return 0;
}
void display(int a[], int size){
    int i;
    for(i = 0; i < size; i++){
        printf("%d \t ", a[i]);
    }
    printf("\n");
}

프로그램 실행 흐름

  1. 사용자로부터 배열의 크기를 입력받습니다.
  2. 배열의 각 요소를 입력받아 저장합니다.
  3. for 루프를 돌며 각 요소를 2로 나누어 나머지가 0이면 짝수 배열에, 아니면 홀수 배열에 저장합니다.
  4. 각각의 개수와 함께 짝수 배열과 홀수 배열을 출력합니다.

실행 결과

위 프로그램을 실행하면 다음과 같은 결과를 얻을 수 있습니다.

enter size of array:
5
enter array elements:
23
45
67
12
34
no: of elements comes under even are = 2
The elements that are present in an even array is: 12 34
no: of elements comes under odd are = 3
The elements that are present in an odd array is : 23 45 67

이 예제에서 입력값 23, 45, 67은 홀수로 분류되고, 12와 34는 짝수로 분류됩니다. 이처럼 나머지 연산자와 if-else 조건문만으로도 배열의 요소를 손쉽게 분리할 수 있습니다.