Home » C solved programs » C pointer programs

C program to swap two numbers using pointers

In this C program, we are going to learn how to swap two integer numbers using pointers? Here, we are using the concept of call by reference (also known as call by address).

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

Here, we are using a function to swap the values swap() - function has two integer pointer type arguments and within the body we are swapping them. Since address of the actual values are passing within the function, swapping will be done with the actual arguments.

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.