Vấn đề
Tính tổng số chẵn và lẻ trong tập phần tử dùng hàm cấp phát bộ nhớ động.
Giải pháp
Chương trình tìm số chẵn/lẻ trong tập số.
Logic tìm số chẵn:
for(i=0;i<n;i++){ if(*(p+i)%2==0) {//kiểm tra số chẵn even=even+*(p+i); //tổng các số chẵn } }
Logic tìm số lẻ:
for(i=0;i<n;i++){ if(*(p+i)%2==0) {//kiểm tra chẵn/lẻ even=even+*(p+i); } Else {//nếu lẻ odd=odd+*(p+i); //tổng các số lẻ } }
Ví dụ
#include<stdio.h> #include<stdlib.h> void main(){ //Khai báo biến, con trỏ// int i,n; int *p; int even=0,odd=0; //Khai báo địa chỉ cơ sở p dùng malloc// p=(int *)malloc(n*sizeof(int)); //Nhập số phần tử// printf("Enter the number of elements : "); scanf("%d",&n); /*Kiểm tra cấp phát thành công*/ if (p==NULL){ printf("Memory not available"); exit(0); } //Lưu phần tử// 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); }
Kết quả
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