C Program To Swap Two Numbers using Function


Lets write a C program to swap 2 numbers using function/method.

When we call a function and pass the actual value it’s called as Call by Value method. If we pass the reference or the address of the variable while calling the function, then it’s called Call by Reference.

In today’s video tutorial we’ll be showing you the concept of Call By Value.

Call by Reference Example: Swapping 2 numbers using pointers

We have written the same C program using pointer and function to illustrate the concept of call by reference. To achieve call by reference we need to use pointers concept. Please watch the video tutorial present at C Program To Swap Two Numbers using Pointers to understand the concept of pointers and call by reference.

Related Read:
Swap 2 Numbers Using a Temporary Variable: C
Function / Methods In C Programming Language

Video Tutorial: C Program To Swap Two Numbers using Function


[youtube https://www.youtube.com/watch?v=EOySeeYYxr4]

YouTube Link: https://www.youtube.com/watch?v=EOySeeYYxr4 [Watch the Video In Full Screen.]


Source Code: C Program To Swap Two Numbers using Function

#include<stdio.h>

void swap(int, int);

int main()
{
    int a, b;

    printf("Enter values for a and b\n");
    scanf("%d%d", &a, &b);

    printf("\n\nBefore swapping: a = %d and b = %d\n", a, b);

    swap(a, b);

    return 0;
}

void swap(int x, int y)
{
    int temp;

    temp = x;
    x    = y;
    y    = temp;

    printf("\nAfter swapping: a = %d and b = %d\n", x, y);
}

Output 1:
Enter values for a and b
20
50

Before swapping: a = 20 and b = 50
After swapping: a = 50 and b = 20

Output 2:
Enter values for a and b
80
90

Before swapping: a = 80 and b = 90
After swapping: a = 90 and b = 80

Logic To Swap Two Numbers

We ask the user to enter values for variable a and b. We pass the user entered values to swap() function. Since we are passing the values to the function, its called Call by value method.

Values of a and b are copied into local variables of swap() that is x and y. We take a local variable temp inside swap() function. We assign the value of x to temp. Then we assign the value of y to x. And finally we assign the value of temp to y. This swaps the values of variable x and y.

Since swap() method doesn’t return anything, we print the values of x and y inside swap() method itself.


temp = x;
x = y;
y = temp;

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Leave a Reply

Your email address will not be published. Required fields are marked *