卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章16882本站已运行3322

使用指针编写的C程序,用于查找用户输入的数组类型

使用指针编写的C程序,用于查找用户输入的数组类型

问题

编写一个 C 程序,通过指针查找我们需要检查的数组类型,数组中给定的元素是偶数、奇数还是两者的组合。

解决方案

用户必须输入一个整数数组,然后显示该数组的类型。

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

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

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

算法

参考下面给出的算法来查找用户输入的数组类型

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

第2步:输入数组元素。

第3步:声明指针变量。

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

然后,打印“Odd”。

第四步:使用指针变量检查数组的所有元素是否为偶数。

然后,打印“Even”。

第 5 步:否则,打印“Mixed”。

>

示例

以下是通过指针查找用户输入的数组类型的 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</p><p>");
   scanf("%d",&n);
   printf("Enter the elements of array</p><p>");
   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</p><p>");
   }
   if(d==n){
      printf("The array type is Odd</p><p>");
   }
   if(c!=n && d!=n){
      printf("The array type is Mixed</p><p>");
   }
   return 0;
}

输出

执行上述程序时,会产生以下输出 -

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

卓越飞翔博客
上一篇: 使用Python Mahotas加载图像
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏