Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to swap values of two no.s

C Code Example — Basic Programs

ADVERTISEMENT

C Program to swap values of two no.s

Objective

Write a C program to swap the values of two variables using a temporary third variable.

Algorithm / Approach

  1. Declare three integer variables: a, b, and temp.
  2. Read values into a and b.
  3. Print the original values.
  4. Store the value of a into temp.
  5. Copy the value of b into a.
  6. Copy the value of temp into b.
  7. Print the swapped values.
main.c
#include<stdio.h>
int main( ) {
 int a, b, temp;
 printf("Enter Values A and B: ");
 scanf("%d%d",&a,&b);
 printf("BEFORE :");
 printf("A=%d B=%d\n",a,b);
 temp = a;
 a = b;
 b = temp;
 printf("AFTER :");
 printf("A=%d B=%d\n",a,b);
 return 0;
}

Expected Output

Enter Values for A and B :
12 13
BEFORE: A=12 B=13
AFTER : A=13 B=12

Explanation of the Program

  • Swapping two variables requires temporarily holding onto one of the values so it doesn't get overwritten.
  • Think of it like having a glass of milk (A) and a glass of juice (B). To swap their contents, you need an empty third glass (temp). You pour the milk into temp, pour the juice into A, and finally pour the milk from temp into B.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT