Q:

C program to swap two numbers using pointers

belongs to collection: C pointers example programs

0

C program to swap two numbers using pointers

Given two integer numbers are we have to swap their values using pointers in C language.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Swap two numbers using call by reference (address) in C

/*C program to swap two numbers using pointers.*/
#include <stdio.h>
 
// function : swap two numbers using pointers
void swap(int *a,int *b)
{
    int t;
     t   = *a;
    *a   = *b;
    *b   =  t;
}
 
int main()
{
    int num1,num2;
     
    printf("Enter value of num1: ");
    scanf("%d",&num1);
    printf("Enter value of num2: ");
    scanf("%d",&num2);
     
    //print values before swapping
    printf("Before Swapping: num1=%d, num2=%d\n",num1,num2);
     
    //call function by passing addresses of num1 and num2
    swap(&num1,&num2);
     
    //print values after swapping
    printf("After  Swapping: num1=%d, num2=%d\n",num1,num2);    
     
    return 0;
}

Output

Enter value of num1: 10
Enter value of num2: 20
Before Swapping: num1=10, num2=20
After  Swapping: num1=20, num2=10

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C program to create, initialize, assign and access... >>
<< C program to change the value of constant integer ...