In this tutorial we will going to learn how to swap two numbers using pointer. If you want to learn more about pointer then you can go through my previous post Pointers in C Programming with Examples.
My System Configuration :
Fujitsu A555 with 12GB RAM, OS – Kubuntu 18.04, IDE used Geany (you can use your own favorite like Notepad++, Codeblock, Kate, Gedit, Sublime text …, Compiler : GCC .
Complete Code for C program to swap two numbers using pointer
/* * Filename : swappointer.c * C program to swap two no * using pointer * By Sanjay Prasad */ #include <stdio.h> void swap(int *n1, int *n2){ int temp; temp=*n1; *n1=*n2; *n2=temp; } int main(){ int a,b; printf("Enter 1st no. a : "); scanf("%d",&a); printf("\nEnter 2nd no. b: "); scanf("%d",&b); printf("\na contain %d",a); printf("\nb contain %d",b); swap(&a,&b); printf("\nAfter Swap \na contain %d",a); printf("\nAfter Swap \nb contain %d",b); printf("\n"); return 0; }
How to Compile and Run :
first create a file named swappointer.c somewhere. Open terminal and using cd to go there and use command given below :
gcc swappointer.c (will compile code)
./a.out (will execute code)