In this chapter, you will complete the topic of simple loops. That’s simple in a sense of “not nested,” not in a sense of “trivial.” No loops are trivial, especially the loops in this chapter.
The chapter and the whole book will close with a bonus: a moon landing simulation game. If you find the exercises in this chapter too difficult, play the game only.
Thank God It’s Friday (TGIF)
It is time to get acquainted with the while loop, which is a cousin of the do-while loop you are already familiar with.
Task
Solution
Discussion
Let’s look at the program more closely.
While Loop
To write the loop, you use the while construct, which is similar in function to do-while, except its condition is at the beginning. The condition is thus being evaluated for the first time before the loop is entered, and if it does not hold, the loop body is not executed even a single time!
This Case
Testing the condition before entering the loop is exactly what you need to do. If today is Friday, you want to let it be untouched. Otherwise, you are adding one day.
TimeSpan Object
When you subtract two dates, the result that arises is always a TimeSpan object . Its Days property says how many days have passed during the “time span” between the two dates.
Power
Loops are frequently practiced in mathematical exercises.
Task
Just to remind you, 210 = 2×2×2×2×2×2×2×2×2×2 = 1024, which is the number 2 repeated 10 times in the final product.
Solution
The task can be solved using repeated multiplication by x. This means you use the intermediate result accumulation approach that you have already learned.
Sine
Continuing with mathematics, do you know how a computer actually performs calculations, for example, the sine function? If you are into mathematics, you might be interested in it.
Task
If you are not interested in how to calculate the value of the sine function, use this task as a challenge to write a more difficult loop.
Analysis
First, you have to analyze the calculation.
Infinite Series
The series to be summed is infinite, but you may wonder how to sum an infinite number of numbers.
You cannot do this, of course. The trick is that you actually do not need to sum an infinite number of members of the series. At a certain point, they become so small that their contribution is somewhere far behind the decimal point.
For practical reasons, you need only a definite precision, say 15 decimal places; the double type does not accommodate more places anyway. You will thus be calculating the sum as long as the series members are greater than one on the 15th place after the decimal point.
Series Members
All the series members are similar to one another. They have an odd power up, odd factorial down, and a changing sign.
To remind you, 7! = 1 × 2 × 3 × … × 7. In other words, the factorial is the product of all the numbers from one to the number given.
Factorial
It is possible to calculate the factorial in a way similar to how you calculated the power earlier in this chapter, in other words, progressively multiplying all the numbers in a loop.
However, you can do it in a smarter way. You do not need to calculate every factorial from scratch. You can always get it much faster from the previously calculated one.
For example, 7! = 7 × 6 × 5!. The factorial of 7 can be calculated from the factorial of 5 by multiplying by “missing numbers” 6 and 7.
Power
A similar trick can be used to calculate the “power part” of each series member. The power does not have to be calculated from scratch. The next power is simply the previous power times x squared.
For example, x7 = x5 × x2.
Solution
Enhancement
You can make the calculation still better using the fact that the series converges the fastest for values of x around zero. The calculation for the big values of x could be converted to the small values of x using sine function symmetries.
I would think that Microsoft has this trick in the code of Math.Sin.
Moon Landing
Ever since the Apollo 11 moon landing , creating a simulation of a lunar module landing has been popular on various programming platforms. So, you will write a similar simulation as the concluding task of this book.
Task
You will write a program simulating the moon landing. It will keep track of the module’s height h above, the moon’s surface, the module’s velocity v, and the mass mF of the fuel remaining for landing.
Landing Velocity | Evaluation |
---|---|
Less than 4 m/s | Soft landing |
4–8 m/s | Hard landing |
Greater than 8 m/s | † |
If all the fuel is consumed before the landing is over, the program starts ignoring the entered braking values, and the braking force is set to zero.
Physical Model
The program will be based on the model of reality discussed here.
h = 50 (m)
v = 8 (m/s)
mF = 35 (kg)
In each step representing one second of the landing maneuver, the values of the tracked physical quantities will change according to the following relations (means the change of the corresponding quantity, as is usual in physics):
h = –v – a/2
v = a
mF = –F / 3000
The braking force is F = 360 × percent of braking.
The acceleration toward the surface is a = 1.62 – F / 8000.
Solution
Summary
This chapter closed the book with several examples of what might be considered advanced loops.
The first exercise was perhaps the easiest. It got you acquainted with the while loop, a close relative of the do-while loop you are already familiar with. The only difference is that the while loop has its condition at the beginning, which means it is being evaluated already before the loop is entered for the first time. Subsequently, the loop’s body will never be executed in case the condition does not evaluate to true at the beginning.
This was precisely what you needed. If the present day was Friday, you did not want to execute the loop’s body (moving a day further) even a single time; you wanted to stay with Friday.
The next task transferred you into the domain of mathematics. You exercised repeated multiplication and gradual result accumulation to get the nth power of a specified number.
The Sine task was probably the most difficult one of the whole book. I presented it here as a bonus for mathematically minded readers. You saw how the computer can calculate the values of what is called a transcendent mathematical function.
The sine values can be calculated using an infinite Taylor series. The trick is to truncate the series after the finite number of its members at the moment they are becoming too small to add anything to the final result considering the finite precision of decimal numbers in the computer.
The solution also showed you some tricks to get the calculation faster. You used previous series members to efficiently calculate the next ones.
The final moon landing task combined many things you learned throughout the book in a relaxing game you can enjoy!
Personal Notes
Now that this book is at its end, allow me, please, a few personal notes. Programming is not only about computers, keywords, and algorithmic thinking. To me, it is a lifelong passion and personal .
Dice
I noted already that there are lots of exercises in this book simulating dice throwing because I played lots of board games as a child. These were not just games purchased from a store. I invented many of my own games then, with most of them simulating sport events. There were different rules for sprints, long runs, jumps, bike races, soccer, and so on. That was possibly a good preparation for becoming a programmer.
The Sine Task
I admit the Sine task of this chapter is substantially above a beginner’s level. I included it to give you a glimpse at your possible future in the Wonderful Land of Programming.
To me, the task also has a personal connection. At some point when I was in school, I wondered how a calculator computes sines. I was thinking the function values are tabulated (“hardwired”) in the calculator and further interpolated. Only later did I find out the other way, the one you saw.
Moon Landing
A simplified version of the moon landing task was actually my first encounter with programming. No, I didn’t program it; I was its computer instead.
When I was young, I read a special issue of a journal explaining programming to youngsters like me. The issue contained a paper computer. It was a piece of paper with windows representing variables. In these windows, you could pull paper strips, writing a variable’s values on them. Assigning a new value to a variable? You just pulled the strip to hide the old value and wrote down a new value on the same strip with a pencil.
I performed all the calculations using an electronic calculator. I was executing the program’s statements, and I was the computer’s CPU running at a marvelous speed of 0.5 Hz (yes, the G is omitted intentionally), which could be boosted to 0.6 Hz using a chocolate bar.
At that time, which was 1982 in Czechoslovakia, I landed that moon module possibly several hundred times, later also using my software on a programmable calculator. Perhaps I was the most experienced astronaut of the days. Regardless, that was a highly motivating road toward programming.
Concluding Wish
To stay on a cosmic note, I hope I managed to launch you into your own programming orbit. Sometimes, I went a bit deep, so maybe you will appreciate returning to the exercises and working through the book a few times. It’s a way to refill the supplies of your cosmic station.
I wish you many joys and successes in your future programming!