C program to swap two numbers with and without using third variable, swapping in c using function. swapping means interchanging
Program to Swap Numbers Using Temporary Variable:
#include<stdio.h>
main()
{
int x,y,temp;
printf("Enter the value of x:");
scanf("%d",&x);
printf("Enter the value of y:");
scanf("%d",&y);
temp=x;
x=y;
y=temp;
printf("The value of x: %d\n",x);
printf("The value of y: %d",y);
}
main()
{
int x,y,temp;
printf("Enter the value of x:");
scanf("%d",&x);
printf("Enter the value of y:");
scanf("%d",&y);
temp=x;
x=y;
y=temp;
printf("The value of x: %d\n",x);
printf("The value of y: %d",y);
}
Output:
We can swap two numbers without using third variable. There are two common ways to swap two numbers without using third variable
Program to Swap Number Without Using Temporary Variables:
1.using '+' and '-' Arthmetic Operators
#include<stdio.h>
main()
{
int x,y;
printf("Enter the value of x:");
scanf("%d",&x);
printf("Enter the value of y:");
scanf("%d",&y);
x=x+y;
y=x-y;
x=x-y;
printf("The value of x: %d\n",x);
printf("The value of y: %d",y);
}
main()
{
int x,y;
printf("Enter the value of x:");
scanf("%d",&x);
printf("Enter the value of y:");
scanf("%d",&y);
x=x+y;
y=x-y;
x=x-y;
printf("The value of x: %d\n",x);
printf("The value of y: %d",y);
}
Output:
2..using * and '/' Arthmetic Operators
#include<stdio.h>
main()
{
int x,y;
printf("Enter the value of x:");
scanf("%d",&x);
printf("Enter the value of y:");
scanf("%d",&y);
x=x*y;
y=x/y;
x=x/y;
printf("The value of x: %d\n",x);
printf("The value of y: %d",y);
}
main()
{
int x,y;
printf("Enter the value of x:");
scanf("%d",&x);
printf("Enter the value of y:");
scanf("%d",&y);
x=x*y;
y=x/y;
x=x/y;
printf("The value of x: %d\n",x);
printf("The value of y: %d",y);
}
Output:
It would be good if we use a function to swap the given numbers instead of writing the entire logic in the main function:
#include<stdio.h>
void swap(int &,int &);
main()
{
int x,y;
printf("Enter the value of x:");
scanf("%d",&x);
printf("Enter the value of y:");
scanf("%d",&y);
swap(x,y);
printf("The value of x: %d",x);
printf("\nThe value of y: %d",y);
}
void swap(int &x,int &y)
{
x=x+y;
y=x-y;
x=x-y;
}
void swap(int &,int &);
main()
{
int x,y;
printf("Enter the value of x:");
scanf("%d",&x);
printf("Enter the value of y:");
scanf("%d",&y);
swap(x,y);
printf("The value of x: %d",x);
printf("\nThe value of y: %d",y);
}
void swap(int &x,int &y)
{
x=x+y;
y=x-y;
x=x-y;
}
Output:
C Programs to Swap Two Numbers
Reviewed by vijay pratap singh
on
April 26, 2017
Rating:
No comments: