C program to swap two numbers using function

Here we are going to write a c program to swap two numbers using function. We have already done this program without function you can checkout:

Today we will do this using function. 

How we will perform swapping?

Suppose we have initially stored two numbers in two variables like,

Before swapping,

a = 20 and b = 48

After swapping,

a = 48 and b = 20

Now lets discuss about the approach.

First we will create a function named swap() of void return type and it will take two integer as parameter. The integers which we are sending as parameter are the numbers which we want to swap. Then at last in the function we will print the swapped numbers. Then in main() function we will call the swap() function, that's it . Now lets code it.

C program to swap two numbers using function 
#include <stdio.h>

void swap(int a, int b){
    a=a+b;
    b=a-b;
    a=a-b;
    printf("After swapping\n a=%d b=%d",a,b);
}

int main(){
    int a,b;
    printf("enter value for a: ");
    scanf("%d",&a);
    printf("enter value for b: ");
    scanf("%d",&b);
    swap(a,b);
    return 0;
}


Output

enter value for a: 45
enter value for b: 27
     
After swapping 
 a=27 b=45 

More like this

• Factorial of a number program in c using function 

• Prime Number check in C using function

• Palindrome Number in C using function 

• Add two numbers in C using function  

• Palindrome String program in c using function 

Post a Comment

If you have any doubts, please let me know

Previous Post Next Post