C program to swap two numbers using pointers

In this article, we are going to learn the C program to swap two numbers using pointers. We will learn this one by one using each sample code.

  • Write a C program to swap two numbers using pointers and functions.
  • How to swap two numbers using call by reference method.
  • Logic to swap two number using pointers in C program.

1. C program to swap two number using pointers


In this example, we have defined two integer numbers and a temp variable and assigned the address of these to the variable to the pointer.

We are asking the user to input 2 variables and store the variable into the pointer. Finally use the pointers variable along with the temp variable to swap the number.

#include <stdio.h>


int main()
{
    int num1, num2;
	int tmpNum;
	
	int *ptr1, *ptr2;
	
	ptr1 = &num1; 
    ptr2 = &num2;

    printf("Please enter two numbers to swap: ");
    scanf("%d%d", ptr1, ptr2);

    
    printf("The numbers entered by user are num1 = %d , num2 = %d \n",num1,num2);

	tmpNum = *ptr1;
	*ptr1= *ptr2;
    *ptr2= tmpNum;
		
	printf("The numbers After Swapping are num1 = %d , num2 = %d \n",num1,num2);

    return 0;
}

Output

Please enter two numbers to swap: 10
12
The numbers entered by user are num1 = 10 , num2 = 12 
The numbers After Swapping are num1 = 12 , num2 = 10

2. C program to swap two numbers using pointers and functions


In this example, we have defined two integer numbers and a temp variable and assigned the address of these to the variable to the pointer.

  • We are asking the user to input 2 variables and store the variable into the pointer. Finally use the pointers variable along with the temp variable to swap the number.
  • We have defined a function swapNum() to swap the numbers by using pointer
#include <stdio.h>
void swapNum(int * num1, int * num2);

void swapNum(int * num1, int * num2)
{
    int tmpNum;

     tmpNum = *num1;
    *num1= *num2;
    *num2= tmpNum;
}

int main()
{
    int num1, num2;

    printf("Please enter two numbers to swap: ");
    scanf("%d%d", &num1, &num2);

    
    printf("The numbers entered by user are num1 = %d , num2 = %d",num1,num2);

  
    swapNum(&num1, &num2);

	
    printf("The numbers After Swapping are num1 = %d , num2 = %d",num1,num2);

    return 0;
}

Output

Please enter two numbers to swap: 20
12
The numbers entered by user are num1 = 20 , num2 = 12 
The numbers After Swapping are num1 = 12 , num2 = 20