1. In the following program, replace the iterative function by an equivalent recursive function:
#include<iostream>
using namespace std;
void iterative_fn(int n);
int main() {
int n;
cout<<"Enter a positive int\n";
cin>>n;
cout<<"\n";
iterative_fn(n);
}
void iterative_fn(int n){
for (int i=n; i>0;i--){
cout<<i<<endl;
}
}
2. Write a recursive function gcd that returns the
greatest common divisor of
and
, which is defined recursively as follows:
If
is equal to 0, then
is
; otherwise
is
%
,
where % is the modulus operator.
3. Write a function triangle(unsigned int m, unsigned int n) with the following properties:
void triangle(unsigned int m, unsigned int n)
// Precondition: m <= n
// Postcondition: The function has printed a pattern of 2*(n-m+1) lines
// to the output stream outs. The first line contains m asterisks, the next
// line contains m+1 asterisks, and so on up to a line with n asterisks.
// Then the pattern is repeated backwards, going n back down to m.
/* Example output:
triangle(3, 5) will print this to cout:
***
****
*****
*****
****
***
*/