C Program to swap two Number using Pointer
Objective
Write a C program to swap two numbers using Pointers (Call by Reference).
Algorithm / Approach
- Declare
x,y, and pointers*a,*b. - Assign the addresses:
a = &x; b = &y;. - Use a
tempvariable to swap the values located AT those memory addresses:temp = *b; *b = *a; *a = temp;. - Print the original
xandyvariables 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)