© Radek Vystavěl 2017

Radek Vystavěl, C# Programming for Absolute Beginners, https://doi.org/10.1007/978-1-4842-3318-4_22

22. Number Series

Radek Vystavěl

(1)Ondřjov, Czech Republic

Several programming tasks reduce to generating regular number series. This is what you are going to study in this chapter. You will also get a better understanding of loops this way.

Every Other

You are already able to generate a simple number series, say from one to ten. You will tackle generating a bit more complex series now.

Task

In this task, you will display “every other” number until 20 (see Figure 22-1).

A458464_1_En_22_Fig1_HTML.jpg
Figure 22-1 Displaying every other number

Solution

Here’s the code:

static void Main(string[] args)
{
    // Output
    for (int number = 2; number <= 20; number += 2)
    {
        Console.WriteLine(number);
    }


    // Waiting for Enter
    Console.ReadLine();
}

Discussion

The most difficult point of the exercise is to realize how to write an iterator of the for loop. Since you want to augment the number variable by 2, the corresponding statement will be number += 2.

Alternative Solution

It is interesting to solve the exercise in another way. You can have an ordinary loop from 1 to 10 stepping by 1 and display twice the amount of its control variable rather than the variable itself.

static void Main(string[] args)
{
    // Output
    for (int line = 1; line <= 10; line++)
    {
        int displayedNumber = 2 * line;
        Console.WriteLine(displayedNumber);
    }


    // Waiting for Enter
    Console.ReadLine();
}

Descending Series

What if the numbers in the series were descending ? Many things will change then. Let’s take a look.

Task

In this task, you will display numbers going down from 10 to 1 (see Figure 22-2).

A458464_1_En_22_Fig2_HTML.jpg
Figure 22-2 Numbers going down

Solution

Here’s the code:

static void Main(string[] args)
{
    // Output
    for (int number = 10; number >= 1; number--)
    {
        Console.WriteLine(number);
    }


    // Waiting for Enter
    Console.ReadLine();
}

Discussion

Note the following:

  • The loop’s initializeris possibly the simplest. You just start at ten.

  • The iterator is not difficult either; the numbers go down, which is why you just subtract 1 at the end of each turn.

  • The most difficult is the loop condition. You have to formulate it in such a way that it holds as long as you want the loop to go on and that it ceases holding at the moment you want to quit. The correct test is whether the number variable is greater than or equal to 1.

Decimal Numbers

A series with decimal numbers might surprise you.

Task

In this task, you will generate a series from 9 to 0 with the numbers decreasing by 0.9 in every step (see Figure 22-3).

A458464_1_En_22_Fig3_HTML.jpg
Figure 22-3 Decreasing by 0.9

Seemingly Correct Solution

Using the style of the previous exercise, you could write the following:

static void Main(string[] args)
{
    // Output
    for (double number = 9; number >= 0; number -= 0.9)
    {
        Console.WriteLine(number.ToString("N1"));
    }


    // Waiting for Enter
    Console.ReadLine();
}

Testing

However, testing discloses the missing last member of the series: 0 (see Figure 22-4).

A458464_1_En_22_Fig4_HTML.jpg
Figure 22-4 Missing last number

How can that be?

The Cause of the Error

The exercise shows how working with decimal numbers can be tricky; you need to be careful because decimal arithmetic can be imprecise!

You can sense the cause when you omit the formatting on a single decimal place (.ToString("N1")). Try it (see Figure 22-5).

A458464_1_En_22_Fig5_HTML.jpg
Figure 22-5 Omitting the formatting

You can see that the expected second-to-last series member is slightly less than it is supposed to be. Further subtraction of 0.9 gets you slightly below zero, which is why the expected last zero is not displayed.

Correct Solution

Working with decimal numbers , you need to specify a loop’s terminal value with a slight free play.

The correct solution of the exercise thus looks like this:

static void Main(string[] args)
{
    // Output
    for (double number = 9; number >= -0.0001; number -= 0.9)
    {
        Console.WriteLine(number.ToString("N1"));
    }


    // Waiting for Enter
    Console.ReadLine();
}

Check the result!

Second Powers

Now, what about displaying two connected numbers in a single line?

Task

In addition to numbers in a 1 to 10 series, you can display the corresponding second power in every line of output (see Figure 22-6).

A458464_1_En_22_Fig6_HTML.jpg
Figure 22-6 Displaying the second power

Solution

Here’s the code:

static void Main(string[] args)
{
    // Output
    for (int number = 1; number <= 10; number++)
    {
        int secondPower = number * number;
        Console.WriteLine(number.ToString() + " " + secondPower.ToString());
    }


    // Waiting for Enter
    Console.ReadLine();
}

Two in a Row

Let’s stay with two numbers in a line here.

Task

In this task, you will generate a 1 to 20 series with a couple of numbers in every line of output (see Figure 22-7).

A458464_1_En_22_Fig7_HTML.jpg
Figure 22-7 Displaying more than one number on a line

Solution

This exercise closely resembles the task of the alternating loop from the previous chapter. It can be solved in a number of ways, too. I will choose one of them: you will add a space after an odd number and a line break after an even number .

Here’s the code:

static void Main(string[] args)
{
    // Output
    for (int number = 1; number <= 20; number++)
    {
        Console.Write(number);


        // What goes after the number depends on even/odd test
        if (number % 2 != 0)
        {
            // Odd number, displaying space
            Console.Write(" ");
        }
        else
        {
            // Even number, new line
            Console.WriteLine();
        }
    }


    // Waiting for Enter
    Console.ReadLine();
}

Two Independent Series

Another interesting case that you might meet some day is the case of two independent series .

Task

You will have two, a bit arbitrary, number series with a different count of members. The first one is descending by 2 in every step (111, 109, …, 97), and the second one is ascending by 3 in every step (237, 240, …, 270).

The program will display both a number from the first series and a number from the second series in every row (see Figure 22-8).

A458464_1_En_22_Fig8_HTML.jpg
Figure 22-8 More complex alternating

Solution

Here’s the code:

static void Main(string[] args)
{
    // Preparation
    int first = 111;


    // Output
    for (int second = 237; second <= 270; second += 3)
    {
        // Preparing first text
        string firstText = first >= 97 ?
            first.ToString().PadLeft(3) : "   ";


        // Actual output
        Console.WriteLine(firstText + " " + second.ToString());


        // Changing x
        first -= 2;
    }


    // Waiting for Enter
    Console.ReadLine();
}

Discussion

Note the following:

  • One of the series (the longer one) is displayed using the loop’s control variable. The other one uses another independent variable .

  • In every step, you check whether the shorter series still goes on.

  • To achieve some nice formatting, you use the PadLeft method call, which adds spaces to the left of its parameter to reach the specified total number of characters.

Summary

In this chapter, you practiced loops on tasks of generating various number series. Specifically, you learned the following:

  • How to write the loop’s iterator when the series is stepping by 2.

  • How to display in a loop’s body not directly the control variable but the value derived (calculated) from it.

  • How to generate a descending series using the -- operator in a loop’s iterator and specify the loop condition using the >= operator so that it is fulfilled as long as you want to do looping.

  • That decimal number series require extra care because of the imprecise representation of decimal numbers in memory. This means, for example, that you need to provide an extra free play in the loop condition.

You also solved cases with two numbers in a single output row, with the more difficult final task of two independent series.

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

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