© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2021
R. VystavělC# Programming for Absolute Beginnershttps://doi.org/10.1007/978-1-4842-7147-6_25

25. Advanced Loops

Radek Vystavěl1  
(1)
Ondřejov, Czech Republic
 

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

You will prepare a program that displays the date of the nearest Friday and the number of days remaining (see Figure 25-1).
../images/458464_2_En_25_Chapter/458464_2_En_25_Fig1_HTML.jpg
Figure 25-1

Displaying the nearest Friday

Solution

Here’s the code:
static void Main(string[] args)
{
    // Today's date
    DateTime today = DateTime.Today;
    // Moving day after day until hit on Friday
    DateTime date = today;
    while (date.DayOfWeek != DayOfWeek.Friday)
    {
        date = date.AddDays(1);
    }
    // Calculating remaining days
    TimeSpan dateDifference = date - today;
    int daysRemaining = dateDifference.Days;
    // Outputs
    Console.WriteLine("Nearest Friday: " + date.ToShortDateString());
    Console.WriteLine("Remaining days: " + daysRemaining.ToString());
    if (daysRemaining == 0)
    {
        Console.WriteLine("Thanks God!");
    }
    // Waiting for Enter
    Console.ReadLine();
}

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

You will write a program that calculates the nth power of the number x given the decimal x and the positive integer n on its input (see Figure 25-2).
../images/458464_2_En_25_Chapter/458464_2_En_25_Fig2_HTML.jpg
Figure 25-2

Calculating the nth power

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.

In principle, the solution is quite close to the one in the “Product of the Entered Numbers” section in Chapter 24:
static void Main(string[] args)
{
    // Inputs
    Console.Write("Enter x (number to be raised): ");
    string inputX = Console.ReadLine();
    double x = Convert.ToDouble(inputX);
    Console.Write("Enter n (power): ");
    string inputN = Console.ReadLine();
    int n = Convert.ToInt32(inputN);
    // Calculating
    double result = 1;
    for (int count = 0; count < n; count++)
    {
        result *= x;
    }
    // Output
    Console.WriteLine("x^n=" + result.ToString());
    // Waiting for Enter
    Console.ReadLine();
}

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.

To perform the task, you can use a so-called Taylor expansion. Some smart people found that the value of the sine function at a given point x (x is an angle in radians) can be calculated as a sum of infinite series:
$$ sin x=x-frac{x^3}{3!}+frac{x^5}{5!}-frac{x^7}{7!}+cdots $$

Task

The task now is to write a program that calculates the sum of this series and compares the result to the value of the ready-made method Math.Sin (see Figure 25-3).
../images/458464_2_En_25_Chapter/458464_2_En_25_Fig3_HTML.jpg
Figure 25-3

Calculating sine

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

Here’s the solution:
static void Main(string[] args)
{
    // Input
    Console.Write("Enter an angle in degrees: ");
    string input = Console.ReadLine();
    double angle = Convert.ToInt32(input);
    // Converting to radians
    double x = Math.PI / 180 * angle;
    // Preparations
    double member;
    double sum = 0;
    double tinyValue = 1e-15;
    double sign = 1;
    double power = x;
    double factorial = 1;
    double multiplier = 1;
    // Sum of the series
    do
    {
        // Calculating current member of the series
        member = sign * power / factorial;
        // Appending to sum
        sum += member;
        // Preparing next step
        sign *= -1;
        multiplier++;
        factorial *= multiplier;
        multiplier++;
        factorial *= multiplier;
        power *= x * x;
    } while (Math.Abs(member) > tinyValue);
    // Output
    Console.WriteLine("Our value: " + sum.ToString());
    Console.WriteLine("Math.Sin:  " + Math.Sin(x).ToString());
    // Waiting for Enter
    Console.ReadLine();
}

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.

The user’s task is to land softly (with the least possible velocity). In each step, representing one second of the landing maneuver, the user enters how much the braking should be applied based on a percentage. The higher the percent, the lower the velocity, but at the same time, the more fuel that’s consumed, as shown in Figure 25-4.
../images/458464_2_En_25_Chapter/458464_2_En_25_Fig4_HTML.jpg
Figure 25-4

The moon landing program

As soon as the height decreases below zero, the module has landed. The program notifies the user on the landing velocity and performs the evaluation according to the following table:

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.

Here are the initial values:
  • 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 = –va/2

v = a

mF = –F / 3000

where
  • The braking force is F = 360 × percent of braking.

  • The acceleration toward the surface is a = 1.62 – F / 8000.

Solution

Here’s the code:
static void Main(string[] args)
{
    // Initial values
    double h = 50, v = 8, mF = 35;
    // Preparation
    bool malfunction = false;
    // Repeating individual landing steps
    while (h >= 0)
    {
        // Displaying current values
        string height   = "Height: " + h.ToString("N1");
        string velocity = "Velocity: " + v.ToString("N1");
        string fuel     = "Fuel: " + mF.ToString("N1");
        Console.WriteLine(height + "  " + velocity + "  " + fuel);
        // Input
        Console.Write("Enter percentage of breaking (0-100): ");
        string input = Console.ReadLine();
        double percents = 0;
        try
        {
            percents = Convert.ToDouble(input);
            if (percents < 0 || percents > 100)
            {
                malfunction = true;
            }
        }
        catch (Exception)
        {
            malfunction = true;
        }
        if (malfunction)
        {
            percents = 0;
            Console.WriteLine("CONTROL MALFUNCTION!");
        }
        // Fuel check
        if (mF <= 0)
        {
            percents = 0;
            Console.WriteLine("NO FUEL!");
        }
        // Calculating new values
        double F = 360 * percents;
        double a = 1.62 - F / 8000;
        h -= v + a / 2;
        v += a;
        mF -= F / 3000;
        if (mF <= 0)
        {
            mF = 0;
        }
        // Output of an empty line
        Console.WriteLine();
    } // End of a single landing step
    // Output
    Console.WriteLine("Landing velocity: " + v.ToString("N1"));
    string evaluation = v < 4 ?
        "Soft landing, congratulations!" :
        (v <= 8 ? "Hard landing." : "Houston, crew is lost...");
    Console.WriteLine(evaluation);
    // Waiting for Enter
    Console.ReadLine();
}

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!

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

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