# Lab 5 Solution

\$30.00

Category: Tag:

## Description

Goals

• Create recursive functions

• Call your functions in a program

• Design the user interface

In this lab, you will implement three functions using recursion and write a menu program to call these functions.

1. Write a function that recursively reverses a string. The function will have a single parameter of type string. It will print the reversed characters to the screen followed by a newline character. Before you start writing code, try to answer these questions to yourself. What is the base case?

Will you print out the characters before or after the recursive function call? You can try it in both ways and see if it makes a difference and choose one way to use in the function.

1. Write a function that recursively calculates the sum of an array. The function should have 2 parameters, the array and an integer showing the number of elements (assume they are all integers) in the array. The function will use a recursive call to sum the value of all elements.

1. Write a recursive function to calculate the triangular number for N. (Or a function that counts the number of pins necessary for a triangular of N rows.) A triangular number is the sum of all items that form a triangle with N rows. It may help to think of the number of bowling pins if you changed the number of rows. For example, when N=0, the triangular number is 0; When N=1, the triangular number is 1; When N=2, the triangular number is 1+2=3; When N=3, the triangular number is 1+2+3=6, so on so forth.

You will also need to write a program to demonstrate all three recursive functions. Provide a menu for the user to select which function to run, and after running the function, return to the menu. For #1, you must prompt the user to enter a string and your program will print the reversed string on screen. For #2, you must prompt for a series of integers to be entered in the array. As your program read the numbers in, increment a count so it knows how many elements the array has. Use a symbol for users to indicate when they are done with entering numbers (choose any letter you think is proper, but you need to print it on screen at the beginning to let users know which one to enter). Then your program will print the sum of the array elements on

screen. For #3, prompt the user to enter an integer and your program will print the triangular number for that integer. You will need a fourth item in the menu to allow them to exit the program.

You can put all your codes in a single cpp file. But you are suggested to separate the implementation and declaration in cpp and hpp files and include a makefile in your code. For this lab, you do not need to write a report. Turn in all your program files in a zip file on TEACH.