Here we are going to see how to swap two numbers using 3rd variable, With program, flowchart and algorithm.
In this program we use very simple logic, we just assign value of one variable i.e 'X' to a temporary variable 'temp' and then assign value of second variable i.e 'Y' to 1st variable 'X'. now swapping for X is done. X is having value of Y, now we will assign value of temp (which is actual value of X) to Y.
Also Read: Swap two elements using a pointer.
Also Read: swapping without using 3rd variable
Program:
#include <stdio.h>
/* Swap numbers using temporary variable By SlashMyCode.com*/
int main()
{
int x, y, temp;
printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);
printf("Before Swapping Numbers:\n x = %d y = %d",x,y);
temp = x;
x = y;
y = temp;
/* Swap numbers using temporary variable By SlashMyCode.com*/
printf("\n After Swapping Numbers:\n x = %d y = %d",x,y);
return 0;
}
Output:
Algorithm:
- START
- Declare variables x, y, temp
- temp = x
- x = y
- y = temp
- STOP
Flowchart:
No comments:
Post a Comment
Feel free to ask us any question regarding this post