Swapping of two numbers in C using pointers
In this post, you will learn swapping of two numbers in the C programming language using pointers. Such a type of question is generally asked in programming interviews. The interviewer may ask you to write a program for the swapping of two numbers using a particular method.
A pointer is a variable whose value is the address of another variable, i.e., the direct address of the memory location. Here, we have used C pointer for swapping of two numbers.
C Program to Swap two numbers using pointers
In the given C program, we take a local variable temp and two variables, x and y. We take two pointer variables, *a and *b. Pointer variable a holds the address of x and pointer variable b holds the address of y. Using the below logic, we swap the values present at addresses x( or a ) and y( or b ).
#include <stdio.h>
int main()
{
int x, y, *a, *b, temp;
printf("Enter the value of x and y: \n");
scanf("%d%d", &x, &y);
//print values before swapping
printf("Before Swapping: \nx = %d\ny = %d\n", x, y);
a = &x;
b = &y;
temp = *b;
*b = *a;
*a = temp;
//print values after swapping
printf("After Swapping: \nx = %d\ny = %d\n", x, y);
return 0;
}
Output of the above code:
Enter the value of x and y:
45 89
Before Swapping:
x = 45
y = 89
After Swapping:
x = 89
y = 45
Enter the value of x and y:
112 834
Before Swapping:
x = 112
y = 834
After Swapping:
x = 834
y = 112
Related Articles
Prime factors of a number in cArmstrong number program in c
Write a program to check leap year in c
C program to find area of rectangle
C program to convert celsius to fahrenheit
Fibonacci series program in C using recursion
Write a program to find area of circle in C
C program to find greatest of three numbers
C program for addition of two numbers
C program to calculate compound interest
C program to find the ASCII value of a character
C program to convert Decimal to Octal
C program to convert decimal to binary
Write a C program to calculate Simple Interest
C program to check whether a number is even or odd
C program to reverse a number
C program to check palindrome number
C program to check whether an alphabet is a vowel or consonant
Program to find square root of a number in C
C program to check whether a number is positive or negative