Programming & Design
Question:
c prog for swapping two numbers?
?
2009-06-12 02:40:11 UTC
can u pls write the prog for swapping two numbers??
Four answers:
tbshmkr
2009-06-12 03:03:31 UTC
Pseudocode
=
There are many ways to do that, here are some.
Code snippets:
1)
int x, y; /* are the two numbers */
x = x+y;
y = x - y;
x = x - y;
2)
x = x*y;
y = x/y;
x = x/y;
3)
x = x ^ y;
y = x ^ y ;
x = x ^ y ;
NOTE: These logics have some limitations
Logic 1 has the Overflow problem when we add (x+y).
Logic 2 has the Overflow problem when we multiply ( x*y) and y should not be Zero.
Logic 3 has the same and its not works on the float numbers.
=
#include
#include
void main()
{
int a,b;
printf("\n Enter the 2 numbers");
scanf("%d%d",&a,&b);
//swaping of 2 numbers without using temp variable
a=a+b;
b=a-b;
a=a-b;
/* or
a=a*b;
b=a/b;
a=a/b;
*/
printf("\n A = %d \n B = %d\n");
getch();
}
SwapNe@L
2009-06-12 03:40:38 UTC
Hi..
If You Want To Swap TWO Numbers make use of third variable for temporary store values of both variables which are to be swapped..
void swap()
{
int x,y,temp(temporary variable);
temp=x; //put value of x into temp
x=y; //put value of y into x;
y=temp; //put value of temp which is original value of x to y;
}
yipee...we hav jus swapped two numbers
(We Can Also Accept These Values Of x & y From Users)
e.g.
printf("enter the value for x & y");
scanf("%d %d",&x,&y);
cheer's
Thanx...
ITGuy
Akhila I
2009-06-13 02:24:40 UTC
include
#include
void main()
{
int x,y,t;
printf("Enter the two nos:");
scanf("%d%d",x,y);
t=x;
x=y;
y=t;
getch();
}
or
without using of third variable
#include
#include
void main()
{
int x,y;
printf("Enter the two nos:");
scanf("%d%d",x,y);
x=x+y;
y=x-y;
x=x-y;
getch();
}
x = x+y;
y = x - y;
x = x - y;
2)
x = x*y;
y = x/y;
x = x/y;
3)
x = x ^ y;
y = x ^ y ;
x = x ^ y ;
Raja Sekar
2009-06-12 02:55:26 UTC
program for swapping two nos;
with t
#include
#include
void main()
{
int x,y,t;
printf("Enter the two nos:");
scanf("%d%d",x,y);
t=x;
x=y;
y=t;
getch();
}
or
without t
#include
#include
void main()
{
int x,y;
printf("Enter the two nos:");
scanf("%d%d",x,y);
x=x-y;
y=x+y;
x=y-x;
getch();
}
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...