Skip to content
Home » C Programs » C Program to Swap Two Numbers Using Pointers

C Program to Swap Two Numbers Using Pointers

Simple swap two numbers in c without using third variable. swapping the numbers ensures that the numbers assigned in the c programming language will be swapped. Pointers are used to swap two numbers in a c program. Swapping the numbers ensures that the numbers assigned in the c programming language will be swapped.

Temporary Variable in C

A temporary variable in computer programming is a variable with a short lifetime, typically used to hold data that will be discarded soon or before it can be placed in a more permanent memory location. 

A temporary variable in computer programming is a variable with a short lifetime, typically used to hold data that will be discarded soon or before it can be placed in a more permanent memory location. Because it has a short lifetime, it is typically declared as a local variable, i.e. a variable with a limited scope.

Address of Operator in C

The (&) operator is a unary operator that returns the operand’s memory address. For example, if var is an integer variable, its address is &var. The precedence and right-to-left associativity of this operator are the same as those of the other unary operators. Using the address of operator in c we have executed the swap two numbers in c without using third variable for beginners

Pointer in C

In C, a pointer is a variable that stores the address of another variable. This variable can be of any type, including int, char, array, function, or pointer. The pointer’s size is determined by the architecture. However, in 32-bit architecture, a pointer is 2 bytes in size. 

Swap Two Numbers in C Without Using Third Variable

//swap two numbers in c without using third variable
#include<stdio.h>
int main()
{
int a, b;
int *ptra, *ptrb;
int temp;
printf("Enter value for a: ");
scanf("%d", &a);
printf("Enter value for b: ");
scanf("%d", &b);
printf("Values before swapping are: a = %d b = %d", a, b);
ptra = &a; 
ptrb = &b; 
temp = *ptra; 
*ptra = *ptrb; 
*ptrb = temp; 
printf("Values after swapping are: a = %d b = %d", a, b);
}

Output of swap two numbers in c without using third variable:

Enter value for a: 4

Enter value for b: 5

The values before swapping are: a = 4 b = 5

The values after swapping are: a = 5 b = 4