Today there are many different types of algorithms running on computers. An algorithm defines a set of instructions that a computer needs to follow to solve a specific problem. A smart and performant algorithm leads to an accurate and efficient working result.
- 1.
Pour fresh water from container A to container C (empty);
- 2.
Pour ocean water from container B to container A;
- 3.
Pour fresh water from container C to container B. Mission is accomplished.
Operation | Container A | Container B | Container C | |
---|---|---|---|---|
Start | Introduce C | Fresh water | Ocean water | Empty |
After step 1 | A C | Fresh water -> empty | Ocean water | Empty -> fresh water |
After step 2 | B A | Empty -> Ocean water | Ocean water -> empty | Fresh water |
After step 3 | C B | Ocean water | Empty -> fresh water | Fresh water -> empty |
In many programs we will often run into situations when we need to set the value of a variable to that of another one. Let’s apply the same logic we have learned from the last example to exchange values between two variables. In other words, we’ll implement the algorithm we defined earlier.
Swapping Values Between Variables
Step | Operation | a | b | c |
---|---|---|---|---|
0 | int a = 5; int b = 4; | 5 | 4 | |
1 | int c = a; | 5 | 4 | 5 |
2 | a = b; | 4 | 4 | 5 |
3 | b = c; | 4 | 5 | 5 |
Other Approaches
a = a + b; now a = 9, b = 4
b = a – b; now a = 9, b = 5
a = a – b; now a = 4, b = 5
Successfully done!