fact
Write a program fact.c that asks the user to enter an integer number N. The program then prints out the first N factorial numbers. Remember that fac(1)=1, fac(n)=n*fac(n-1). You should use a function fac that is written recursively.
Main Contents Page | CTEC1401 Programming in C |
Quick Reference |
Week 17: Functions II | Week 18: Functions III |
Week 19: Searching |
Before the lab session read CFTTP Chapter 11 and study the solved exercises very carefully.
Attempt the followingunsolved exercises at the end of Chapter 11:
Write a program fact.c that asks the user to enter an integer number N. The program then prints out the first N factorial numbers. Remember that fac(1)=1, fac(n)=n*fac(n-1). You should use a function fac that is written recursively.
Write a program called fibs.c that contains a recursive function for calculating the nth Fibonacci number. The program should accept a number as a command line argument and then call the Fibonacci function to calculate the corresponding Fibonacci number and then display the result. Recall the definition of the Fibonacci numbers:
Write a recursive function:
int sum( int x, int max ) { /* complete the code */ }that calculates the sum of the numbers from
x
to max
(inclusive). For example, sum (4, 7)
would compute 4 + 5 + 6 + 7
and return the value 22. The function must be recursive so you are
not allowed to use any conventional loop constructs.
Save your function along with a main program that tests it thoroughly into a file recSum.c. Compile and run the program.
Write a recursive function:
int sumP2( int maxP ) { /* complete the code */ }that calculates the sum of the powers of two from
0
to maxP
(inclusive). For example, sumP2(7)
would compute
20 +
21 +
22 +
23 +
24 +
25 +
26 +
27
and return the value 255. The function must be recursive so you are
not allowed to use any conventional loop constructs.
Save your function along with a main program that tests it thoroughly into a file sumP2.c. Compile and run the program.
Consider the following program. You will see that it takes its input values from the command line (rather than asking the user to enter them when the program is running).
This program demonstrates the use of command line arguments. The atoi
function is used to convert a string into an integer value.
#include <stdio.h> #include <stdlib.h> int ack( int m, int n ) { /* Complete this function */ } int main(int argc, char *argv[]) { int m, n; if(argc!=3) { printf("Usage: %s m n\n", argv[0]); exit(1); } m = atoi(argv[1]); n = atoi(argv[2]); printf("ack(%d,%d) = %d\n", m, n, ack(m, n)); return 0; }
ack
function. (Look up the definition of the
Ackermann function
to see how it works.)
time ack 0 0 time ack 2 4 time ack 3 7 time ack 3 9 time ack 3 10What do you notice?