How to swap variables in arrays (C compiler)?
Hello, I've been given a task where I'm supposed to swap variables using a for loop (in the C programming language). As in this example, I'm supposed to swap 1 with 4 and 2 with 3. I've been able to do everything, but unfortunately I'm stuck on the swapping part. Can someone help me?
c++ has since c++14 std::exchange: https://en.cppreference.com/w/cpp/utility/exchange. This uses low level optimizations to achieve the best possible solution for the respective platform.
Otherwise, it’s completely okay to use an auxiliary variable. Reading is also important. Or you use the tricks that have been described here. On the Internet you also find a lot about it. https://de.wikipedia.org/wiki/Dreiecksaustausch | https://en.wikipedia.org/wiki/Swap_(computer_programming)
It is obviously about learning the absolute foundations of programming…
@JanaL161 Thanks for the answer, but it is unfortunately as @GuteAntwort2021 writes. I am only learning the basics, but really thank you for your answer and your time. Still writing the source code is kind of not that easy.
I have fun playing out such tasks. In fact, two numerical variables can also be exchanged without auxiliary variables, see here:
*
y
x ← x + y // a + b
y ← x – y // (a + b) – b = a
x ← x – y // (a + b) – a = b
@J0T4T4 Thanks for your answer. The problem here is to make it with an auxiliary variable and the loop (for loop) should only run until n/2. Somehow I’m really hard to do this with the source code. You don’t know how it works, do you?
Hello.
Without having looked at the task now, how would you do it in real life?
Suppose you have two cups and want to pack what is under cup 1 in cup 2 and the other way. But you can only do one thing at any time and only wear one thing.
How would you solve the problem?
Exactly:
That’s how you’re in danger of programming. So you’ll start a storage location with a corresponding data type, i.e. an auxiliary variable, and then exchange according to the scheme.
LG
@GuteAntwort2021 Thanks for the example, this has made it easier for me to explain how it works. However, I don’t get any further with the source code because I need a for loop that only runs up to n/2. Always solve such tasks, but this time I really don’t get on with the source code.
Where is the problem exactly?