C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Functions in C

Swap numbers using function

Swap Two Numbers using a Function — a simple yet essential example to understand call by value and call by reference in C.

C Program: Swap Two Numbers using Function (Call by reference)

Method 1: Call by Reference - Address Passing

C

#include <stdio.h>

 

// Function declaration

void swap(int *x, int *y);

 

int main() {

    int a, b;

 

    // Input two numbers

    printf("Enter two numbers: ");

    scanf("%d %d", &a, &b);

 

    printf("\nBefore swapping: a = %d, b = %d\n", a, b);

 

    // Function call (pass addresses)

    swap(&a, &b);

 

    printf("After swapping: a = %d, b = %d\n", a, b);

 

    return 0;

}

 

// Function definition using call by reference

void swap(int *x, int *y) {

    int temp;

 

    temp = *x;

    *x = *y;

    *y = temp;

}

Output

 
OUTPUT :
Enter two numbers: 10 20

Before swapping: a = 10, b = 20
After swapping: a = 20, b = 10

Explanation

  1. Function Parameters
    • The function swap() takes pointers as parameters (int *x and int *y).
    • This allows direct modification of the original variables in main().
  2. Logic
    • A temporary variable temp is used to hold one value during the swap.
    • Then values are exchanged using pointer dereferencing (*x and *y).
  3. Why Use Pointers?
    • In C, arguments are passed by value by default.
    • To modify the actual variables, we pass their addresses (call by reference).

 

C Program: Swap Two Numbers using Function (Call by Value)

Method 2: Call by Value

C

#include <stdio.h>

 

// Function declaration

void swap(int x, int y);

 

int main() {

    int a, b;

 

    // Input two numbers

    printf("Enter two numbers: ");

    scanf("%d %d", &a, &b);

 

    printf("\nBefore swapping (in main): a = %d, b = %d\n", a, b);

 

    // Function call

    swap(a, b);

 

    printf("After swapping (in main): a = %d, b = %d\n", a, b);

 

    return 0;

}

 

// Function definition (call by value)

void swap(int x, int y) {

    int temp;

 

    temp = x;

    x = y;

    y = temp;

 

    printf("After swapping (inside function): x = %d, y = %d\n", x, y);

}

Output

 
OUTPUT :
Enter two numbers: 10 20

Before swapping (in main): a = 10, b = 20
After swapping (inside function): x = 20, y = 10
After swapping (in main): a = 10, b = 20

Explanation

  1. Function Parameters
    • The function receives copies of the variables (x and y).
    • Any changes inside swap() affect only the local copies, not the originals.
  2. Key Concept: Call by Value
    • In C, arguments are passed by value by default.
    • Hence, swapping inside the function does not change the values in main().
  3. Execution Flow
    • Values are swapped inside the function but remain unchanged outside it.