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

C 언어를 사용하여 동적으로 요소 집합에서 짝수 및 홀수 찾기

<시간/>

문제

동적 메모리 할당 함수를 사용하여 요소 집합에서 짝수와 홀수의 합을 계산합니다.

해결책

이 프로그램에서는 일련의 숫자에서 짝수와 홀수를 찾으려고 합니다.

집합 요소에서 짝수를 찾는 데 사용되는 논리는 다음과 같습니다. -

for(i=0;i<n;i++){
   if(*(p+i)%2==0) {//checking whether no is even or not
      even=even+*(p+i); //calculating sum of even all even numbers in a list
   }
}

집합 요소에서 홀수를 찾는 데 사용되는 논리는 다음과 같습니다. -

for(i=0;i<n;i++){
   if(*(p+i)%2==0) {//checking number is even or odd
      even=even+*(p+i);
   }
   Else {//if number s odd enter into block
      odd=odd+*(p+i); //calculating sum of all odd numbers in a list
   }
}

예시

#include<stdio.h>
#include<stdlib.h>
void main(){
   //Declaring variables, pointers//
   int i,n;
   int *p;
   int even=0,odd=0;
   //Declaring base address p using malloc//
   p=(int *)malloc(n*sizeof(int));
   //Reading number of elements//
   printf("Enter the number of elements : ");
   scanf("%d",&n);
   /*Printing O/p -
   We have to use if statement because we have to check if memory
   has been successfully allocated/reserved or not*/
   if (p==NULL){
      printf("Memory not available");
      exit(0);
   }
   //Storing elements into location using for loop//
   printf("The elements are : \n");
   for(i=0;i<n;i++){
      scanf("%d",p+i);
   }
   for(i=0;i<n;i++){
      if(*(p+i)%2==0){
         even=even+*(p+i);
      }
      else{
         odd=odd+*(p+i);
      }
   }
   printf("The sum of even numbers is : %d\n",even);
   printf("The sum of odd numbers is : %d\n",odd);
}

출력

Enter the number of elements : 5
The elements are :
34
23
12
11
45
The sum of even numbers is : 46
The sum of odd numbers is : 79