C Language: Recursion Exercises


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.

  1. printing numbers from 1 to n
  2. print even/odd numbers up to n
  3. exponentiation of n
  4. print n! (factorial is the product of numbers up to n)
  5. printing the sum of numbers from n to m
  6. printing Fibonacci numbers (each next is the sum of the previous two)
  7. print Collatz numbers (even: n/2; odd: n*3+1)
  8. copying a string from one to another
  9. printing array elements
  10. print line backwards
  11. converting decimal to binary
  12. binary search
  13. bubble sort
  14. 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;
}

 


This entry was posted in C language (en). Bookmark the permalink.

Leave a Reply

🇬🇧 Attention! Comments with URLs/email are not allowed.
🇷🇺 Комментарии со ссылками/email удаляются автоматически.