C Program to Swap Two Numbers Using Pointers

1. Introduction

Using pointers is one of the efficient ways to swap the values of two numbers in C programming. By directly accessing the memory addresses of the variables, the swapping operation can be achieved without the need for a temporary variable. In this article, we'll dive into a C program that demonstrates this concept.

2. Program Overview

1. Declare two integer variables.

2. Declare two pointers that will point to these integer variables.

3. Using the pointers, swap the values of the integer variables.

4. Display the swapped values.

3. Code Program

#include <stdio.h>

// Function to swap two numbers using pointers
void swap(int *a, int *b) {
    int temp;

    // Storing value pointed by 'a' in 'temp'
    temp = *a;

    // Storing value pointed by 'b' in address pointed by 'a'
    *a = *b;

    // Storing value from 'temp' in address pointed by 'b'
    *b = temp;
}

int main() {
    int num1, num2;
    int *ptr1, *ptr2;

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

    // Pointers initialized to the address of the numbers
    ptr1 = &num1;
    ptr2 = &num2;

    // Calling the swap function
    swap(ptr1, ptr2);

    // Display the swapped values
    printf("After swapping:\n");
    printf("Number 1 = %d\n", num1);
    printf("Number 2 = %d\n", num2);

    return 0;
}

Output:

Enter two numbers:
5 10
After swapping:
Number 1 = 10
Number 2 = 5

4. Step By Step Explanation

1. The program starts with the declaration of two integers num1 and num2, which will store the numbers to be swapped.

2. Two pointers, ptr1 and ptr2, are declared. These pointers will be used to access the memory locations of num1 and num2 respectively.

3. The user is prompted to enter two numbers which are stored in num1 and num2.

4. The pointers ptr1 and ptr2 are then initialized to point to the memory addresses of num1 and num2.

5. A swap function is called with these pointers as arguments. Inside this function:

  • The value at the address pointed to by ptr1 (which is num1) is stored in a temporary variable temp.
  • The value at the address pointed to by ptr2 (which is num2) is then stored at the address pointed to by ptr1.
  • The value in temp (original value of num1) is stored at the address pointed to by ptr2.

6. Back in the main function, the swapped values are displayed, showcasing that the numbers have been successfully swapped without using a third variable (apart from the temporary one in the swap function).

Comments