164k views
2 votes
Given two int variables, i and j, which have been declared and initialized, and two other int variables, itemp and jtemp, which have been declared, write some code that swaps the values in i and j by copying their values to itemp and jtemp respectively, and then copying itemp and jtemp to j and i respectively.

User PropoLis
by
7.4k points

1 Answer

4 votes
itemp = i; jtemp = j; i = jtemp; j = itemp; The above code example assumes that you're writing in C, C++, java, or some other language with similar syntax. Since all the variables i, j, itemp, and jtemp have the same type, you can simply assign one to another without having to worry about type compatability or conversions. When the 4 assignment statements have executed, i will have the original value of j, and j will have the original value of i, effectively swapping the two values between the two variables.
User Oren
by
8.0k points