Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to swap the values of two variables.

C Code Example — Function Programs

ADVERTISEMENT

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

  1. Declare a function prototype void swap(int, int) before main().
  2. Inside main(), read two variables x and y.
  3. Call the function passing the variables as arguments: swap(x, y).
  4. Inside the swap function definition, use a temporary variable to swap the values of the parameters.
  5. Print the swapped values from inside the swap function.
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 swap function only receives copies, swapping them inside the function does NOT affect the original x and y back in main().
  • 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)
ADVERTISEMENT