C program to swap two number using function and pointers

Spread the love

swap two number using function and pointers

The address of memory location num1 and num2 are passed to function and the pointers *a and *baccept those values. So, the pointer a and b points to address of num1 and num2 respectively. When, the value of pointer are changed, the value in memory location also changed correspondingly. Hence, change made to *a and *b was reflected in num1 and num2 in main function.

// C program to swap two number using function and pointers.*//
#include <stdio.h>
void swap(int *a,int *b);
int main(){
int num1=5,num2=10;
swap(&num1,&num2); /* address of num1 and num2 is passed to swap function */
printf(“Number1 = %d\n”,num1);
printf(“Number2 = %d”,num2);
return 0;
}
void swap(int *a,int *b){ /* pointer a and b points to address of num1 and num2 respectively */
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Output
Number1 = 10
Number2 = 5

swap two number

 

Search Keywords

C PROGRAM FOR SWAPPING OF TWO NUMBERS
swap 2 numbers using pointers in C
C Program to Swap Two Number Using Pointer
Program to swap two numbers using functions