Write a C program to recursively find if a given array contains a 4.
For example,
{8, 6, 4, 3, 2} → true
{1,2,5}→ false
Note:
Refer to the problem requirements.
Function Specification:
int array4(int *a, int n)
Input and Output Format:
Input consists of n+1 integers, where the first integer corresponds to 'n', the number of elements, followed by 'n' integers.
The output consists of a string "4 is not present" or "4 is present".
Sample Input 1:
Enter the number of elements in the array
5
Enter the elements in the array
8
6
4
3
2
Sample Output 1:
4 is present
Sample Input 2:
Enter the number of elements in the array
3
Enter the elements in the array
1
2
5
Sample Output 2:
4 is not present
Implementation of the above problem:
#include<stdio.h>
int r,l;
int array4(int *a, int x)
{
if (r < l)
return -1;
if (*(a+l) == x)
return l;
l=l+1;
return array4(a, x);
}
int main()
{
int arr[100], i, n;
printf("Enter the number of elements in the array\n");
scanf("%d", &n);
int *ptr=arr;
printf("Enter the elements in the array\n");
for (i = 0; i < n; i++)
{
scanf("%d", ptr);
ptr++;
}
int x = 4;
l=0;
r=n-1;
int index = array4(arr, x);
if (index != -1)
printf("%d is present", x);
else
printf("%d is not present", x);
return 0;
}
Thanks
Mukesh Rajput
Post A Comment:
0 comments: