使用指针查找用户输入数组类型的C程序。


问题

编写一个C程序,使用指针检查给定数组中的元素是偶数、奇数还是两者兼有。

解决方案

用户需要输入一个整数数组,然后显示数组的类型。

示例1 − 输入:5 3 1,输出:奇数数组

示例2 − 输入:2 4 6 8,输出:偶数数组

示例3 − 输入:1 2 3 4 5,输出:混合数组

算法

参考以下算法,使用指针查找用户输入的数组类型。

步骤1:运行时读取数组大小。

步骤2:输入数组元素。

步骤3:声明指针变量。

步骤3:使用指针变量检查数组的所有元素是否都是奇数。

然后,打印“奇数”。

步骤4:使用指针变量检查数组的所有元素是否都是偶数。

然后,打印“偶数”。

步骤5:否则,打印“混合”。

示例

以下是使用指针查找用户输入数组类型的C程序:

 在线演示

#include<stdio.h>
#include<stdlib.h>
int*createArray (int);
void readArray(int,int *);
int findType(int , int *);
int main(){
   int *a,n,c=0,d=0;
   printf("Enter the size of array
");    scanf("%d",&n);    printf("Enter the elements of array
");    createArray(n);    readArray(n,a);    findType(n,a);    return 0; } int *createArray(int n){    int *a;    a=(int*)malloc(n*sizeof(int));    return a; } void readArray(int n,int *a){    for(int i=0;i<n;i++){       scanf("%d",a+i); }} int findType(int n, int *a){    int c=0,d=0;    for(int i=0;i<n;i++){       if(a[i]%2==0){          c++;       }       else{          d++;    }}    if(c==n){       printf("The array type is Even
");    }    if(d==n){       printf("The array type is Odd
");    }    if(c!=n && d!=n){       printf("The array type is Mixed
");    }    return 0; }

输出

执行上述程序时,将产生以下输出:

Enter the size of array
4
Enter the elements of array
12
14
16
18
The array type is Even

更新于:2021年3月26日

516 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.