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?

(1 votes)
Loading...

Similar Posts

Subscribe
Notify of
8 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
JanaL161
11 months ago

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)

GuteAntwort2021
11 months ago
Reply to  JanaL161

It is obviously about learning the absolute foundations of programming…

J0T4T4
11 months ago

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

GuteAntwort2021
11 months ago

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:

  • Remove content from cup 1 and place it in a new place (help variable).
  • Pack contents from cup 2 in cup 1.
  • Remove contents from the auxiliary container and place them in cup 2.

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
10 months ago
Reply to  7K1NGS

Where is the problem exactly?

int number_elements = sizeof(numbers)/2;