Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to swap two Number using Pointer

C Code Example — Function Programs

ADVERTISEMENT

C Program to swap two Number using Pointer

Objective

Write a C program to swap two numbers using Pointers (Call by Reference).

Algorithm / Approach

  1. Declare x, y, and pointers *a, *b.
  2. Assign the addresses: a = &x; b = &y;.
  3. Use a temp variable to swap the values located AT those memory addresses: temp = *b; *b = *a; *a = temp;.
  4. Print the original x and y variables to prove they were changed.
main.c
#include<stdio.h>
int main( ) {
 int x, y, *a, *b, temp;
 printf("Enter the value of X and Y : ");
 scanf("%d%d", &x, &y);
 printf("Before Swapping\nX = %d\nY = %d\n", x, y);
 a = &x;
 b = &y;
 temp = *b;
 *b = *a;
 *a = temp;
 printf("After Swapping\nX = %d\nY = %d\n", x, y);
 return 0;
}

Expected Output

Enter the value of X and Y : 10 20
Before Swapping
X = 10
Y = 20
After Swapping
X = 20
Y = 10

Explanation of the Program

  • This program fixes the flaw from Program #1. This is called "Call by Reference" (or Pass by Reference).
  • By manipulating the data directly at its physical memory address using pointers, any changes you make are permanent and immediately reflected in the original variables.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT