C program to find array type entered by user using pointers.

CServer Side ProgrammingProgramming

Problem

Write a C Program to find the array type that we need to check, whether the given elements in an array are even numbers or odd numbers or combination of both by using pointers.

Solution

The user has to enter an array of integers, then, display the type of the array.

Example 1 − Input: 5 3 1, Output: odd array

Example 2 − Input: 2 4 6 8, Output: even array

Example 3 − Input: 1 2 3 4 5, Output: mixed array

Algorithm

Refer an algorithm given below to find the array type entered by user with the help of pointers.

Step 1: Read the size of array at runtime.

Step 2: Input the array elements.

Step 3: Declare the pointer variable.

Step 3: Check, if all the elements of the array are odd by using pointer variable.

Then, print "Odd".

Step 4: Check, if all the elements of the array are even by using pointer variable.

Then, print "Even".

Step 5: Else, print "Mixed".

Example

Following is the C program to find the array type entered by user with the help of pointers −

 Live Demo

#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\n");
   scanf("%d",&n);
   printf("Enter the elements of array\n");
   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\n");
   }
   if(d==n){
      printf("The array type is Odd\n");
   }
   if(c!=n && d!=n){
      printf("The array type is Mixed\n");
   }
   return 0;
}

Output

When the above program is executed, it produces the following output −

Enter the size of array
4
Enter the elements of array
12
14
16
18
The array type is Even
raja
Published on 26-Mar-2021 07:39:17
Advertisements