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
- Declare three integer variables:
a,b, andtemp. - Read values into
aandb. - Print the original values.
- Store the value of
aintotemp. - Copy the value of
bintoa. - Copy the value of
tempintob. - 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)