In: Computer Science
Write a c program arrays2.c that checks if an integer array
contains three identical consecutive elements. Assume the number of
identical consecutive elements are no more than three if they
exist.
Sample input/output #1:
Enter the length of the array: 11
Enter the elements of the array: -12 0 4 2 2 2 36 7 7 7 43
Output: The array contains 2 of three identical consecutive
elements: 2 7
Sample input/output #2:
Enter the length of the array: 4
Enter the elements of the array: -12 0 4 36
Output: The array does NOT contain identical consecutive
elements
Sample input/output #3:
Enter the length of the array: 11
Enter the elements of the array: -12 0 4 2 2 2 36 7 7 43 43
Output: The array contains 1 of identical consecutive elements:
2
1) Name your program arrays2.c
2) Include and implement the following function in the program. Do
not modify the function prototype.
void search_three(int *a1, int *a2, int n, int *num_three);
The function takes two integer array parameter a1 and a2 of size n.
a1 is the input array. a2 is the output array containing the
integers that are in the three consecutive integers. num_three as a
pointer variable, pointing to the variable for the total number of
the three consecutive integers (also the actual size of the output
array). For example, the total number of the three consecutive
integers for sample input #1 is 2, 0 for sample input #2, and 1 for
sample input #3.
The function should use pointer arithmetic – not subscripting – to
visit array elements. In other words, eliminate the loop index
variables and all use of the [] operator in the function.
3) In the main function, ask the user to enter the size of the
input array, declare the input array and output array of the same
size, and then ask the user to enter the elements of the input
array. The main function calls search_three function, and displays
the result.
C Program
#include <stdio.h>
#include<conio.h>
void search_three(int *a1,int *a2,int n,int *num_three)
{
int ans=0;
for(int i=0;i<n-2;i++)
{
if((*(a1+i)==*(a1+i+1)))
{
if(*(a1+i)==*(a1+i+2))
{
*(a2+ans)=*(a1+i);
ans++;
(*num_three)++;
}
}
else
continue;
}
if(ans!=0){
printf("The array contains %d of identical consecutive elements:
",*num_three);
//printing the values of final output array.
for(int i=0;i<ans;i++)
printf("%d ",*(a2+i));
return;
}
printf("The array does NOT contain identical consecutive
elements");
}
void main {
int n;
printf("Enter the length of the array: ");
scanf("%d",&n);
printf("\n");
int a1[n];
int a2[n];
printf("Enter the elements of the array: ");
for(int i=0;i<n;i++)
scanf("%d",&a1[i]);
printf("\n");
int count=0;
int *num_three;
num_three=&count;
search_three(a1,a2,n,num_three);
}
EXAMPLES :
INPUT 1:
OUTPUT 2:
INPUT 2 :
OUTPUT 2: