Examples of Recursion


Problems

Problem : Write the reverse() function recursively. This function takes a string and the length of the string as arguments and returns the same string with its characters in the reverse order.


Problem : Challenge: You're given a piece of memory containing characters divided into two sections, section a and section b, that follow each other in memory, b after a. You are also supplied with the lengths of a and b. Write a function that uses your reverse() function from above to swap the two sections such that the a section follows the b section. This does not require recursion.


Problem : Write a function count_spaces(char *s) that counts the number of whitespace characters that appear in a string. Characters are whitespace as defined by the isspace() function in the ctype library. Write this function recursively.


Problem : Why would a programmer most likely not use recursion for an implementation of the string library?


Problem : Write the function strrchr() iteratively and recursively.


Problem : A palindrome is a sequence of characters or numbers that looks the same forwards and backwards. For example, "Madam, I'm Adam" is a palindrome because it is spelled the same reading it from front to back as from back to front. The number 12321 is a numerical palindrome. Write a function that takes a string and its length as arguments and recursively determines whether the string is a palindrome: int ispalindrome(char *s, int len);


Problem : Write a recursive function void replace(char *s, char from, char to); that changes all occurrences of from in s to to. For example, if s were "steve", and from == 'e' and to == 'a', s would become "stava".


Take a Study Break

SparkLife

What's your Pretty Little Liars name?

Take this quiz to find out!

SparkLife

Which young actress just got married?

Click to find out!

SparkLife

Cat bearding WINS THE INTERNET

Have you seen this yet?

SparkLife

Scary movies with funny posters

These. Are. Hilarious.

Geek out!

The MindHut

Geeky Actors: Then and Now

Travel back in time!

The MindHut

Villains We Want These Actresses to Play

From super cute to super bad!

The MindHut

10 Movies Better Than Their Books

What do you think?

The MindHut

Summer Movie Open Thread

Leave your thoughts here!

The MindHut

12 Scientific Inaccuracies in Into Darkness

What did Star Trek get wrong?

The Book

Cover image

Read What You Love, Anywhere You Like

Get Our FREE NOOK Reading Apps