1. (7 pts) Write a function called recursive_string_length () that accepts a poi
ID: 3815391 • Letter: 1
Question
1. (7 pts) Write a function called recursive_string_length () that accepts a pointer to a string as a parameter, recursively counts the number of characters in the string (excluding the null character), and returns the integer count. For example, the count for “CptS121” is 7. You may not use any functions from <string.h>.
2. (8 pts) Write a function recursive_string_copy() which accepts a pointer to a source string and a pointer to a destination string as parameters, recursively copies from the source to destination (including the null character), and returns nothing. You may not use any functions from <string.h>. Hint: each recursive step requires that you pass in the address of the next character to copy from the source and the address of the next destination character location.
Explanation / Answer
CODE: FIND EXPLANATION IN COMMENTS. REQUIRED FUNCTIONS IN BOLD
//Program to calculate length of string recursively and copy string recursively
#include <stdio.h>
int recursive_string_length(char *); //Prototype of function to find length
void recursive_string_copy(char *, char *); //Prototype of function to copy string
int main()
{
char *source = "hello";
char *destination;
recursive_string_copy(source, destination);
int length = recursive_string_length(destination);
printf("Copied String is %s length of string %s = %d ",destination,source,length);
return 0;
}
//Function Definition to find length of string recursively
int recursive_string_length(char *string)
{
static int len = 0; //Static variable to count length
if(*string != '') //Check for end of string
{
len++; //Increment length if string is not null
*string++; //Increment pointer location by 1
recursive_string_length(string); //Call function recursively from new pointer location
}
else
{
return len; //Return length when string is null i.e., length is counted
}
}
//Function Definition to copy string recursively
void recursive_string_copy (char *source, char *destination)
{
if (*source != '') //Check if source pointer is null
{
*destination = *source; //Copy character from source to destination
*destination++; //Increment destination pointer to next location
*source++; //Increment source pointer to next location
recursive_string_copy(source, destination); //Call function recursively until source is NULL
}
else
{
*destination = ''; //Append NULL character when string is copied
}
}
OUTPUT:
sh-4.2$ gcc -o main main.c
sh-4.2$ main
Copied String is hello
length of string hello = 5
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.