In: Computer Science
Answer the following Discrete Structures
Suppose string s = (s1 s2 ..sn). Give a recursive definition of the function numOnes(n), which counts the number of 1s in bit-string of length n, Make sure to define the function for the base case, numOnes(0).
Explanation :
String :
In the light of the above discussions, the solution to the given set of question is as follows:
The Solution :
INPUT :The given bit string s = ( s1 s2 ... sn )
OUTPUT : The number of 1s in the string s counted by the recursive function numOnes(n).
Note : The function should define the base case numOnes( 0 ) .
Definition of the recursive function numOnes(n) :
numOnes ( n )
{
int number = 0; // define variable to store the number of 1s, initialised to 0
int i = 0 ; // define loop variable
int length = n; // define variable length to denote the length of the string passed as argument in the function call
string s = ( s1 s2 ... sn ) ; // the given string of bits consisting a series of 0 or 1, may be blank string as well
for ( i = 0, i < length, i++ )
{
if s [ i ] = =1,
{
number = number + 1;
} // end if
return number;
} // end for loop
} // end function
Note : For the base case numOnes ( 0 ), the function returns number = 0 as it was initialised to 0.
This concludes the answer to all parts of the question along with the necessary explanations.
Please do not forget to like the answer if it helps you. Thank you.