Click on any exercise below to see the source code, program output and explanation of the code. Programs in this section make use of functions, arrays and pointers.
In C, functions are building blocks from which larger programs are constructed. They provide a convenient way to encapsulate some computation, which can be used without worrying about its implementation.
An array in C is a composite data structure comprising items of the same type. An array can be one-dimensional, two-dimensional or multi-dimensional.
Pointers are used to access memory and manipulate memory addresses.
Exercise 3.5.Write a function which, given a positive integer n, prints the nth Fibonacci number.
f(n) = f(n - 1) + f(n - 2). F(1) = f(2) = 1
Exercise 3.6. Write a program which, given a positive integer n, returns the value of n!
n! = n*(n – 1)! 0! = 1
Exercise 3.7. Write a program which, given a positive integer n and a real number x, returns the value of ex.
Ex = 1 + x/1 + x2/2! +...+xn/n!
Exercise 3.15. Write a C program which reads a text, and print it out one word per line, all punctuation and non-alpha characters being omitted. When typing input, end the data by typing the end-of-file character usually control+D.
Exercise 3.16. Write a recursive function which returns the gcd of two integers m and n given that
gcd(n, m) = gcd(n, m mod n)
Exercise 3.22. Write a program to read English text to end-of-data (type control-D to indicate end of data at a terminal, see below for detecting it), and print a count of word lengths, i.e. the total number of words of length 1 which occurred, the number of length 2, and so on. Define a word to be a sequence of alphabetic characters. You should allow for word lengths up to 25 letters.
Typical output should be like this:
length 1 : 10 occurrences
length 2 : 19 occurrences
length 3 : 127 occurrences
length 4 : 0 occurrences
length 5 : 18 occurrences
Exercise 3.25. Write a program to find out for a class of students, the number of families with 1, 2, 3, … up to 7 children. Data consists of number of children in each student's family. Design an appropriate format for the output.
Exercise 3.28. Write a program which drills a user in English - French vocabulary. Two arrays, english and french are used to hold the words such that french[i] contains the French equivalent of the word in english[i]. The program must display an English word and requests the user to enter the French equivalent for it. Incorporate a suitable scoring mechanism and give the user the opportunity to "give up". Modify the program to enable the user choose either English - French drill or French - English drill.
Exercise 3.29. Write a function “replace” which takes a pointer to a string as a parameter, which replaces all spaces in that string by minus signs, and delivers the number of spaces it replaced. Thus char *cat = "The cat sat"; n = replace( cat ); should set cat to "The-cat-sat" and n to 2.