To learn recursion you need to pump up some muscles. To do so – make some of exercises which are listed below. If something did not work out, you can peep the solution. Most likely the next day you will forget about the solution – so you can try to implement this exercise again. Recursion is a rather atypical task for the brain, so it’s good idea to repeat the same exercise several times. Solutions are below.
- printing numbers from 1 to n
- print even/odd numbers up to n
- exponentiation of n
- print n! (factorial is the product of numbers up to n)
- printing the sum of numbers from n to m
- printing Fibonacci numbers (each next is the sum of the previous two)
- print Collatz numbers (even: n/2; odd: n*3+1)
- copying a string from one to another
- printing array elements
- print line backwards
- converting decimal to binary
- binary search
- bubble sort
- merge sort
Printing numbers from 1 to n using recursion (Stukensia’s variant)
// print numbers from 1 to n #include <stdio.h> #include <cs50.h> int printn (int n); int main (void) { int n = get_int ("Number: "); printn (n); } int printn (int n) { if (n == 1) { printf ("%i\n", n); return 0; } else { printn(n-1); printf ("%i\n", n); return 0; } return 0; }
Print even / odd numbers up to n
#include <stdio.h> int number (int n_max); int main (void) { int n_max; printf("Max number: "); scanf( "%d", &n_max); int num = number(n_max); return 0; } int number (num) { if (num == 0) { printf ("0\n"); return 0; } else { // print even numbers if ((num % 2) == 0) { printf ("%i\n", num); } number (num - 1); } return 0; }