Function In C Language Part - 2

Mastering C Programming: Understanding Function Parameter Passing and Recursion



Introduction

When it comes to passing arguments to functions in C programming, two methods stand out: Call By Value and Call By Reference. Additionally, the concept of recursion allows functions to call themselves. Let's delve into each of these topics and understand how they work.

Call By Value

In the world of Call By Value, actual arguments are passed to formal arguments, creating a copy for the function to operate on. Changes made to the formal arguments do not affect the original values. Let's illustrate this with a program:
 #include <stdio.h>

    void exchange(int p, int q);

    int main() {
        int a, b;

        printf("Enter Two Values:\n");
        scanf("%d %d", &a, &b);

        printf("Before Function Call: a=%d b=%d", a, b);

        exchange(10, 20);

        printf("After Function Call: a=%d b=%d", a, b);
    }

    void exchange(int p, int q) {
        int t;
        t = p;
        p = q;
        q = t;

        printf("In Function:\n p=%d q=%d", p, q);
    }
Explanation:
The program demonstrates Call By Value, showcasing that changes within the function do not affect the original values of 'a' and 'b'.

Call By Reference

Contrary to Call By Value, Call By Reference passes addresses (references) to functions, allowing the function to operate on the values directly. Formal arguments become pointers to actual parameters. Observe the following program:
 #include <stdio.h>

    void exchange(int *a, int *b);

    int main() {
        int a, b;

        printf("Enter Two Values:\n");
        scanf("%d %d", &a, &b);

        printf("Before Exchange: a=%d b=%d", a, b);

        exchange(&a, &b);

        printf("After Exchange: a=%d b=%d", a, b);
    }

    void exchange(int *a, int *b) {
        int t;
        t = *a;
        *a = *b;
        *b = t;

        printf("After Exchange value in function: a=%d b=%d", *a, *b);
    }
Explanation:
This example showcases Call By Reference, emphasizing that changes made to the arguments inside the function are permanent

Recursion

In C, a function can call itself, giving birth to recursive functions. Let's explore a simple factorial calculation using recursion:
 #include <stdio.h>

    int fact(int a);

    int main() {
        int n, factorial;

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

        factorial = fact(n);

        printf("Factorial: %d", factorial);
    }

    int fact(int a) {
        if (a == 1)
            return 1;
        else
            return a * fact(a - 1);
    }
Explanation:
The program calculates the factorial of a number using recursion, where the function calls itself until the base case is met.

In mastering C programming, understanding these fundamental concepts is crucial. Call By Value, Call By Reference, and recursion provide powerful tools for efficient and flexible code design.