C++, Recursion Hi there, below are recursive problems that I need to implement t
ID: 3863997 • Letter: C
Question
C++, Recursion
Hi there, below are recursive problems that I need to implement the codes and prove them using inductive proof.
(7) Implement a function that determines whether a given int is an element of an array of int:
(8) Using your function in (7), implement a function which determines whether one array is a “subset” of another (that is, whether every element in array a is also an element of array b):
And below are my codes that, I think, need to be fixed.
I think codes for problem #7 is correct, but #8 is not working as it's supposed to.
bool is_element_of(int i, int* array, int length){
if(length < 0)
return false;
if(array[length] == i)
return true;
else
return is_element_of(i, array, length - 1);
}
bool is_subset(int* a, int length_a, int* b, int length_b){
if(!is_element_of(b[length_b], a, length_a))
return false;
else
is_subset(a, length_a, b, length_b -1);
return true;
}
Can someone fix my functions and write out the inductive proof for each of them?
Thank you in advance!
Explanation / Answer
#include <iostream>
using namespace std;
bool is_element_of(int i, int* array, int length){
if(length < 0)
return false;
if(array[length] == i)
return true;
else
return is_element_of(i, array, length - 1);
}
//==== Currected function =======//
bool is_subset(int* a, int length_a, int* b, int length_b){
if(length_a < 0) // POINT TO BE NOTED
return true;
if(!is_element_of(a[length_a], b, length_b))
return false;
else
return is_subset(a, length_a-1, b, length_b);
return true;
}
//==== POINT TO BE NOTED ===//
// here we reached up to negative length means we searched whole array
// and till now we was getting eatch element of array a in array b .
//So at this position we can say that all elements of array a are present in array b
int main()
{
int a[] = {5,2,1};
int b[] = {1,2,5,1,2};
bool isTrue = is_subset(a,3,b,5);
cout <<"int a[] = {5,2,1}"<<endl;
cout <<"int b[] = {1,2,5,1,2};"<<endl;
if(isTrue){
cout << "Yes , Because all elements of array a are in array b" << endl;
}
else{
cout << "No , Because one or more elements of array a are not in array b" << endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.