C Functions

Write a C program to find the factorial of a number using recursion

Description: Write a recursive function to find the factorial of a number taken as input.

Hint:

  • n! = n x (n - 1)! and 0! = 1. The second rule is the base case.

C program for factorial using recursion

#include <stdio.h>

unsigned long long factorial(int n) {
    if (n <= 1) {
        return 1;                    // base case
    }
    return n * factorial(n - 1);     // recursive call
}

int main(void) {
    int n;

    printf("Enter a number: ");
    scanf("%d", &n);

    printf("Factorial of %d = %llu\n", n, factorial(n));
    return 0;
}

Output:

Output of the above program is

Enter a number: 6
Factorial of 6 = 720

How it works

  • factorial(6) calls factorial(5), and so on, until factorial(1) returns 1.
  • Then the answers are multiplied while the calls return: 1, 2, 6, 24, 120 and 720.

Read C Recursion.

Write a C program to swap two numbers using a function and pointers

Description: Write a function which swaps the values of two variables. The values must change in the main() function.

Hint:

  • Pass the addresses of the variables with &, and use * inside the function.

C program to swap two numbers using pointers

#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main(void) {
    int x, y;

    printf("Enter two numbers: ");
    scanf("%d %d", &x, &y);

    swap(&x, &y);
    printf("After swapping: x = %d, y = %d\n", x, y);
    return 0;
}

Output:

Output of the above program is

Enter two numbers: 5 9
After swapping: x = 9, y = 5

How it works

  • The function gets the addresses of x and y, so it changes the original values.
  • With normal parameters (call by value), the function would swap only its own copies.

Read Call by Value and Reference.