C program to swap two numbers using call by reference

Write a C program to swap two numbers using pointers and functions. How to swap two numbers using call by reference method. Logic to swap two number using pointers in C program.

Example

Input

Input num1: 10
Input num2: 20

Output

Values after swapping:
Num1 = 20
Num2 = 10

Required knowledge

Basic C programming, Functions, Pointers

Must know – Program to swap two numbers using bitwise operator

Logic to swap two numbers using call by reference

Swapping two numbers is simple and a fundamental thing. You need not to know any rocket science for swapping two numbers. Simple swapping can be achieved in three steps –

  1. Copy the value of first number say num1 to some temporary variable say temp.
  2. Copy the value of second number say num2 to the first number. Which is num1 = num2.
  3. Copy back the value of first number stored in temp to second number. Which is num2 = temp.

Let us implement this logic using call by reference concept in functions.

Program to swap two numbers using call by reference

/**
 * C program to swap two number using call by reference
 */

#include <stdio.h>

/* Swap function declaration */
void swap(int * num1, int * num2);

int main()
{
    int num1, num2;

    /* Input numbers */
    printf("Enter two numbers: ");
    scanf("%d%d", &num1, &num2);

    /* Print original values of num1 and num2 */
    printf("Before swapping in main n");
    printf("Value of num1 = %d \n", num1);
    printf("Value of num2 = %d \n\n", num2);

    /* Pass the addresses of num1 and num2 */
    swap(&num1, &num2);

    /* Print the swapped values of num1 and num2 */
    printf("After swapping in main n");
    printf("Value of num1 = %d \n", num1);
    printf("Value of num2 = %d \n\n", num2);

    return 0;
}


/**
 * Function to swap two numbers
 */
void swap(int * num1, int * num2)
{
    int temp;

    // Copy the value of num1 to some temp variable
    temp = *num1;

    // Copy the value of num2 to num1
    *num1= *num2;

    // Copy the value of num1 stored in temp to num2
    *num2= temp;

    printf("After swapping in swap function n");
    printf("Value of num1 = %d \n", *num1);
    printf("Value of num2 = %d \n\n", *num2);
}

Before moving on to other post, learn more ways to play with swapping numbers.

Read more – Program to swap first and last digits of a number

Output

Enter two numbers: 10 20
Before swapping in main
Value of num1 = 10
Value of num2 = 20

After swapping in swap function
Value of num1 = 20
Value of num2 = 10

After swapping in main
Value of num1 = 20
Value of num2 = 10

Happy coding 😉