Starting from:

$30

Lab 11: Recursion SOLVED

CS 2401 
Lab 11: Recursion

For this lab you are to write two recursive problems. The two problems have nothing to do with each
other, so you should do the easy one first and test it, and then tackle the second one. The functions are
to be recursive, meaning that there will be no “while” or “for” anywhere in the program except where I
have shown it in the main below. No credit given for a non-recursive solution.
Problem One: Write a recursive function, called counting, that receives a single parameter which will
always be a positive number and then prints all the even numbers from 0 up to, and including the
number that was passed in, if that number is even, or one less than the number passed in if it is odd.
(“Up to” means that you start with the smallest number and end with the largest number.)
Run with the program with the values 23, 18, and -2. (No output should be generated by the last.)
The main for this program will look like this:
int main(){
int x;
for(int j = 0; j < 3; ++j){
cout << ”Enter a number: “;
 cin >> x;
cout << ”The even numbers counting up to there:\n”;
counting(x);
}
 // main for Part Two will go here
return 0;
}
The function that you are to implement is:
int counting(int n);
Problem Two: For this part, you need to write a recursive function which takes an integer n as input,
printing a pattern of n lines of asterisks. The first line contains one asterisk, the next line contains two
and so on up to the nth line which contains n asterisks. Line number n+1 again contains n asterisks,
the next line has n-1 asterisks, the next line n-2, and so on until the line 2n, which will have just one
asterisk. The main function is provided.
// helping function of see_stars to print stars
// should print n stars on the same line
// needs to be recursive
void print_stars(int n);
// calls print_stars in the body; also needs to be recursive
void see_stars(int count, int stop);
// add to the main
int n;
cout << “Enter a number between 1 and 30 to see the stars\n”;
cin >> n;
see_stars(1, n);
Sample output:
Enter a number between 1 and 30 and see the stars.
5
*
**
***
****
*****
*****
****
***
**
*
Submit your source code showing all three recursive functions, the main that calls them, and the script
file that shows a complete running of the program to Blackboard.

More products