C program to swap two numbers using pointers

Category: C Program

Swap two numbers in C using pointers, a powerful and efficient technique. This program stores two numbers in variables, and swaps their values after executing.

Pointers in C are variables that store the memory addresses of other variables. This allows you to directly access and manipulate the data stored in those variables, without having to use their names. Pointers can be used to swap two numbers in C by storing the value of one number in a temporary variable, and then assigning the value of the other number to the first number. Finally, the value stored in the temporary variable is assigned to the second number.

Steps to swap two numbers using pointers in C

  • Declare two integer variables, num1 and num2, to store the numbers to be swapped.
  • Declare two pointers, ptr1 and ptr2, to store the memory addresses of num1 and num2, respectively.
  • Initialize the pointers ptr1 and ptr2 to point to the memory addresses of num1 and num2, respectively.
  • Store the value of num1 in a temporary variable, temp.
  • Assign the value of num2 to num1.
  • Assign the value of temp to num2.

Write a C program to swap two numbers using pointers

#include <stdio.h>

void swap_numbers(int *ptr1, int *ptr2) {
  int temp;
  temp = *ptr1;
  *ptr1 = *ptr2;
  *ptr2 = temp;
}

void main() {
  int num1, num2;

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

  swap_numbers(&num1, &num2);

  printf("The swapped numbers are: %d %d", num1, num2);
}

Output -

Enter two numbers: 10 20
The swapped numbers are: 20 10

Advantages of using pointers to swap two numbers

There are several advantages to using pointers to swap two numbers in C:

  • It is more efficient than using a temporary variable, as it does not require the allocation and deallocation of memory.
  • It is more flexible, as it can be used to swap any two variables, regardless of their data type.
  • It is more readable, as it makes the code more concise and easier to understand.

Recommended Posts