Question:
Can anyone give me the coding for swaping two integers in C language?
venky
2007-11-19 07:15:49 UTC
condition is:
the receiving variable should be only one & the process should carry over in that variable itself.
it should receive two nos. inorder & it should reverse it & be given.
N.B., only C language coading.
Six answers:
colo
2007-11-19 07:24:29 UTC
variable or function??



anyways:

to swap integers have a temp value inside the function to store one of the integers.



do you use pointers because if not the original variables holding the numbers will still be the same and not reversed?



prototype:

assuming you use pointers:

void SwapInteger(int *, int*);



definition:

void SwapInteger(int *firstval, int *secondval) (pointers to int)

{

int temp;

temp = *firstval ;

(dereference or get value of address pointed to by firstval)

*firstval = *secondval;

*secondval = temp;

return;

}



assuming you know these stuff :-)



edit:

if you don't use pointers, you can't return two integers from a function so its gonna be a trickier than using pointers.





edit :

what do you mean by a receive? do you mean passing these as arguments to a function?



i don't think there is any way for a variable to act as three variables. given that you have two integers to be reversed, the temp variable will only take one declaration. the pointers are mainly address of the original two variables.





edit:

do you mean declaring only one variable to hold the operation to take the two integers and reverse it? make sure first that this is what your program wants. you can do only one assignment on an operation and you need the variables holding these integers to be included in the operation itself which would entail using 3 variables.
Achint
2007-11-19 07:33:21 UTC
let the variables be x and y



x=x+y ;

y=x-y ;

x=x-y ;



(i haven't written the syntax properly but this is the operation to swap the values of 2 variables without using a third one)
kiran kumar G
2007-11-19 21:08:32 UTC
#include

#include

main()

{

int i,j;

i=10;

j=20;

i=i+j; /*i=30

j=i-j; /*"j=10

i=i-j; /*"i=20

printf("i=%d,j=%d",i,j);

}

Actually i am working on SAP thats why i forget the syntax .please check the syntax and execute the program.But the logic i implemented is 100% correct
Smart
2007-11-19 20:41:26 UTC
int a=10;

int b=20;

a=a+b ;

b=a-b ;

a=a-b ;

print a,b;
poulami100
2007-11-19 07:25:00 UTC
int a=10;

int b=20;

int temp=0;

temp=a;

a=b;

b=temp;

//swapping done!
juntunen
2016-11-12 07:12:31 UTC
it is for toddlers. LOL.. right this is the completed code! #contain important() { int a,b,sum; printf("Please enter 1st Nubmer:n"); scanf("%d",&a); printf("Please enter 2nd Nubmer:n"); scanf("%d",&b); sum=a+b; printf("%d",sum); } (TAGALOG)magazine aral kc ng mabuti.haha


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...