動態使用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 : 
");    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
",even);    printf("The sum of odd numbers is : %d
",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

更新於:09-Mar-2021

1K+ 瀏覽

開啟你的 職業生涯

完成課程後獲得認證

開始
廣告