C Program to swap the values of two variables.
Objective
Write a C program to swap the values of two variables using a function (Call by Value).
Algorithm / Approach
- Declare a function prototype
void swap(int, int)beforemain(). - Inside
main(), read two variablesxandy. - Call the function passing the variables as arguments:
swap(x, y). - Inside the
swapfunction definition, use a temporary variable to swap the values of the parameters. - Print the swapped values from inside the
swapfunction.
main.c
#include<stdio.h>
void swap(int, int); <font color="blue">//prototype</font>
int main( ){
int x,y;
printf("Enter X: ");
scanf("%d",&x);
printf("Enter Y: ");
scanf("%d",&y);
printf("BEFORE SWAP:\n");
printf("X=%d and Y=%d",x,y);
swap(x,y); <font color="blue">//calling</font>
return 0;
}
<font color="blue">//definition</font>
void swap(int x, int y){
int temp = x;
x = y;
y = temp;
printf("AFTER SWAP : \n");
printf("X=%d and Y=%d",x,y);
}
Expected Output
Enter X: 15 Enter Y: 28 BEFORE SWAP: X=15 and Y=28 AFTER SWAP: X=28 and Y=15
Explanation of the Program
- This program demonstrates "Call by Value". When you pass variables to a function, C creates a complete copy of those variables in memory.
- Because the
swapfunction only receives copies, swapping them inside the function does NOT affect the originalxandyback inmain(). - To actually swap the variables so that
main()sees the change, you must use "Call by Reference" using Pointers (which is covered in a later program).
Complexity
Time Complexity
O(1)
Space Complexity
O(1)