© Ron Dai 2019
R. DaiLearn Java with Mathhttps://doi.org/10.1007/978-1-4842-5209-3_6

6. First Algorithm

Ron Dai1 
(1)
Seattle, WA, USA
 

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.

Next is an example of creating an algorithm using real-world objects. Here we will look at how to exchange different kinds of water (fresh water and ocean water) between two containers of the same size. From common sense, we know to use a third empty container with the same size. Here is a series of actions you take to get this job done:
  1. 1.

    Pour fresh water from container A to container C (empty);

     
  2. 2.

    Pour ocean water from container B to container A;

     
  3. 3.

    Pour fresh water from container C to container B. Mission is accomplished.

     
You can see how water in each container was changed after each step from this table.
 

Operation

Container A

Container B

Container C

Start

Introduce C

Fresh water

Ocean water

Empty

After step 1

A ../images/485723_1_En_6_Chapter/485723_1_En_6_Figa_HTML.gif C

Fresh water -> empty

Ocean water

Empty -> fresh water

After step 2

B ../images/485723_1_En_6_Chapter/485723_1_En_6_Figa_HTML.gif A

Empty -> Ocean water

Ocean water -> empty

Fresh water

After step 3

C ../images/485723_1_En_6_Chapter/485723_1_En_6_Figa_HTML.gif 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

Assume two integers, a = 5 and b = 4. We want to switch their values so that it will become a = 4 and b = 5. Following the order of operations listed in the next table, values in variables a and b will be switched over.

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

You may use other methods to swap values between the two integers without using a temporary variable. One method is by utilizing the + and operators to exchange values:
  • a = a + b; ../images/485723_1_En_6_Chapter/485723_1_En_6_Figa_HTML.gif now a = 9, b = 4

  • b = a – b; ../images/485723_1_En_6_Chapter/485723_1_En_6_Figa_HTML.gif now a = 9, b = 5

  • a = a – b; ../images/485723_1_En_6_Chapter/485723_1_En_6_Figa_HTML.gif now a = 4, b = 5

Successfully done!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.133.96