IN C PROGRAMMING Q. ARRAY330 Given an array of ints, compute recursively if the
ID: 3874835 • Letter: I
Question
IN C PROGRAMMING
Q. ARRAY330
Given an array of ints, compute recursively if the array contains somewhere a value followed in the array by that value times 10. We'll use the convention of considering only the part of the array that begins at the given index. In this way, a recursive call can pass index+1 to move down the array. The initial call will pass in index as 0.
array330([1, 2, 20], 3, 0) true
array330([3, 30], 2, 0) true
array330([3], 1, 0) false
array330([1, 2, 3, 4, 5, 6], 6, 0) false
array330([1, 2, 3, 4, 4, 50, 500, 6], 7, 0) true
array330([], 0, 0) false
CODE:
array330([1, 2, 20], 3, 0) true
array330([3, 30], 2, 0) true
array330([3], 1, 0) false
array330([1, 2, 3, 4, 5, 6], 6, 0) false
array330([1, 2, 3, 4, 4, 50, 500, 6], 7, 0) true
array330([], 0, 0) false
Explanation / Answer
C code for the given requirement:
#include<stdio.h>
#include<stdbool.h>
bool array(int a[],int length,int index);
int main()
{
//array declaration with values
//change the array values for different test cases
int a[]={1, 2, 3, 4, 4, 50, 500, 6};
int i,len=0;
//for loop to calcualte the lenght of the array
for(i=0;a[i]!='';i++)
{
len++;
}
//calling the recursive function and assiging returning value to variable result of type boolean
bool result=array(a,len,0);
//if result value is 1 then print true
if(result==1)
printf("True");
//else print false
else if(result==0)
printf("False");
getch();
system("pause");
return 0;
}
//recursive function implementation
bool array(int a[],int length,int index)
{
//if array is empty or value does not match
if(length==0 || (length-1)==0)
{
return false; //return false
}
//if conditon for the array contains value folosomewhere a value followed in the array by that value times 10.
if(a[index]*10==a[index+1])
return true;
else //else call the recursive function
return array(a,(length-1),index+1);
}
Output:
True