

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Problems and solutions related to recursive functions in c programming. It covers various examples such as fibonacci, factorial, hanoi, sumofdigits, oddevensum, displaytriangle, and log. For each problem, the base case and recursive case are stated.
Typology: Lab Reports
1 / 3
This page cannot be seen from the preview
Don't miss anything!


Today’s lab has us playing with recursive functions.
Problem 0: For the programs we looked at in class: fibonacci, factorial and hanoi. State what the base case and recursive case are:
recursive case:
recursive case:
recursive case:
Problem 1: Write a program with a recursive function:
int sumOfDigits ( int x ) ;
That takes a number like 234 and computes the sum of the digits
base case:
recursive case:
Problem 2: Write a program with a recursive function:
int oddEvenSum ( int n ) ;
That takes a number and computes the sum from 1 to n as follows: −1 + 2 − 3 + 4 − 5 + 6...n such that all odd evens are subtracted and all even numbers are added. Before you begin write what your base case will be and what your recursive case will be.
base case:
recursive case:
Problem 3: Write a program with a recursive function: void d i s p l a y T r i a n g l e ( int currentDepth , int t o t a l D e p t h , char c h a r a c t e r ) ; That will display a triangle of the prescribed depth with the prescribed character. For example d i s p l a y T r i a n g l e ( 5 , 5 ’#’ ) ;
####### #########
d i s p l a y T r i a n g l e ( 2 , 5 ’#’ ) ; ####### #########
Notice that the number of space to put before the sequence of characters is the current depth - 1. Also notice that we can use a loop to print out the correct number of characters, and use recursion for each line. Before you begin write what your base case will be and what your recursive case will be.
base case:
recursive case:
Problem 4: Write a program with a recursive function: int l o g ( int f , int b ,... ) ; That takes two integers ,f and b, and computes logb(f ). Re- member that: bx^ = f or put another way: b︸ ∗ b ∗ ...︷︷ ∗ b ∗ b︸ x
= f
So we can compute x as follows:
(((f / b)/b/...b)/b) ︸ ︷︷ ︸ b Consider the example: l o g ( 8 , 2 ) (8/2) = 4 (4/2) = 2 (2/2) = 1 1 < 2! We remember that anything raised to the 0th power is 1. So we had to divide by 2, three times. There fore we know that log 2 (8) = 3. We will only worry about solutions where the answer is whole number (i.e. 1 is the only stopping criterion to worry about. Before you begin write what your base case will be and what your recursive case will be.