Windows Forms C# - Loops and Arrays

2018/02/02 13:42
Loops 
Programming often requires repeated execution of a given sequence of operations. Loop is a basic programming design that allows multiple execution of a source code snippet. Depending on the type of the loop, the program code in it is repeated either a fixed number of times or while a condition is in effect.
A loop that never ends is called an infinite loop. The use of an infinite loop is rarely required except in cases where the break operator is used in the body of the cycle to stop its execution prematurely. Let's take a look at the Cycle constructs in the C# language.

While loop
The simplest and most used loop. Code structure and block scheme are as shown:
while (condition)
{
    Loop body;
}
For the while loop, the boolean expression (condition) is first calculated and if the result is true, the sequence of operations in the body of the loop is performed. Then the input condition is checked again and, if true, the body of the cycle is again performed. All this is repeated over and over again until at some point the conditional statement returns false. At this point, the loop ends and the program continues from the next row immediately after the loop.


Do-While loop
It is similar to the While loop, except that the boolean condition is checked after the loop runs. This type of loop is called a post-test loop. A do-while loop looks like this:
do
{
    Loop body;
}
while (condition);
The body of the loop is initially executed. Then condition is checked. If it is true, the body of the loop is repeated, otherwise the loop ends. This logic is repeated until the loop condition is violated. The body of the loop is repeated at least once. If the loop condition is always true, the loop will never end.
The Do-While loop is used when you need to ensure that the sequence of operations in it is executed repeatedly and at least once at the beginning of the loop.

For loop
These loops are a bit more complicated than the While and Do-While loops, but they can solve more complicated tasks with less code. 
Logic scheme is shown on the picture.
for (initialization; condition; counter refresh)
{
    Loop body;
}

Since none of the listed elements of the for-loop is mandatory, all of them can skipped and an infinite loop will be created:

for ( ; ; )
{
    Loop body;
}

For loop – initialization
for (int num = 0; ...; ...)
{
    // num variable can be accessed only inside the for loop
}
// outside the num variable cannot be accessed and used
Initialization runs only once, just before entering the loop. Typically, the initialization block is used to declare the variable-counter (also called the leading variable) and set its default value. This variable is "visible" and can only be used within the loop. It is possible for the initialization block to declare and initialize more than one variable.
For loop – condition
for (int num = 0; num< 10; ...)
{
    Loop body;
}
The loop condition is performed once before each iteration of the loop, just as with the while loops. When the result is true, the loop body is executed, and when false it is skipped and the loop ends (passes to the rest of the program immediately after the loop).
For loop – refreshing counter
for (int num = 0; num< 10; num++)
{
    Loop body;
}
This code is executed after each iteration after the completion of the loop body. It is most often used to update the counter value.
For loop – loop body
The body of the loop contains an arbitrary block of source code. It contains the leading variables declared in the initialization block of the cycle.
Foreach loop
This loop serves to crawl all elements of an array, list, or other collection of elements.
Here's how one foreach loop looks like:
foreach (variable in collection)
{
    statements;
}
It is preferred by programmers because it saves writing code when required to craw all elements of specific collection.
Break operator
It is used to prematurely exit a loop before it completes its execution in its natural way. When break operator occurs, the loop is terminated and the execution of the program continues from the next row immediately after the body of the loop. The termination of a loop with the break operator can only occur from his body when it is executed in the iteration of the loop. When a break is executed, the code after it in the body of the loop is skipped and not executed.
Continue operator
The operator stops the current iteration of the innermost loop without escaping from it.
Array
The arrays are an integral part of most programming languages. They represent sets of variables that are called elements:


The array elements in C# are numbered 0, 1, 2, ... N-1. These element numbers are called indexes. The number of elements in an array is called the array length.
All elements of an array are of the same type, whether primitive or reference. This helps to present a group of homogeneous elements such as ordered sequenced sequence and to process as a whole.
The arrays can be of different sizes, the one-dimensional and two-dimensional arrays are being the most common. One-dimensional arrays are also called vectors, and two-dimensional arrays – matrix.
List<T>


List<T> is the template version of ArrayList. When initializing a List<T> object, you specify the type of items that the list will contain; replace T-type markings with some real type of data (such as a number or string). The List class is represented in memory as an array, one of which holds its elements, and the rest is free and is kept as a backup. Thanks to the spare empty elements in the array, the addition operation almost always manages to add the new element without expanding the array. Sometimes, of course, resizing is required, but since each resizing doubles the size of the array, it happens so rarely that it can be ignored against the background of the number of additions.
Sample tasks
1) Create Windows Forms application which demonstrates all types of loops.
Solution:
Create new Windows Forms Application project and design the form as show on the picture:


Name the controls as follows:
- ListBox – lbResult;
- Button „For” – bFor;
- Button „While“ – bWhile;
- Button „Endless“ – bEndless;
- Button „Do“ – bDo;
- Button „Nested“ – bNested;
- Button „Foreach“ – bForeach;
- Button „Graphic1“ – bGraphic1;
- Button „Graphic2“ – bGraphic2.
Replace the content of the source code file with the following:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace Loops
{
    public partial class Form1 : Form
    {
        int number, P, x1, y1, hlf;
        string S;
        bool bGraph1Clicked =false;
        bool bGraph2Clicked = false;

        Pen myPen = new Pen(Color.Cyan, 3);
        
        public Form1()
        {
            InitializeComponent();
        }

        private void bFor_Click(object sender, EventArgs e)
        {
            lbResult.Items.Clear();

            lbResult.Items.Add("For loop with step 1:");

            for (number = 0; number <= 5; number++)
                lbResult.Items.Add(number);

            lbResult.Items.Add("For loop with step 5:");

            for (number = 0; number <= 25; number += 5)
                lbResult.Items.Add(number);
        }

        private void bWhile_Click(object sender, EventArgs e)
        {
            lbResult.Items.Clear();

            number = 1;

            lbResult.Items.Add("Powers of 2:");

            while (number <= 1000)
            {
                number *= 2;
                lbResult.Items.Add(number);
            }
        }

        private void bEndless_Click(object sender, EventArgs e)
        {
            lbResult.Items.Clear();

            for (; ; )
                lbResult.Items.Add("Endless loop...");
        }

        private void bDo_Click(object sender, EventArgs e)
        {
            lbResult.Items.Clear();

            number = 10;

            do
            {
                lbResult.Items.Add(number);
                number =- number;
            }
            while (number == 0);
        }

        private void bNested_Click(object sender, EventArgs e)
        {
            lbResult.Items.Clear();

            for (number = 1; number <= 10; number++)
            {
                S = " " + number + " : ";
                for (P = 2; P <= 4; P++)
                    S = S + Math.Pow(number, P) + " ";
                lbResult.Items.Add(S);
            }
        }

        private void bForeach_Click(object sender, EventArgs e)
        {
            lbResult.Items.Clear();

            string[] pets = { "dog", "cat", "bird" };

            foreach (string value in pets)
            {
                lbResult.Items.Add(value);
            }
        }

        private void InitDrawingTools(PaintEventArgs e)
        {
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

            myPen.DashStyle = DashStyle.Solid;
            myPen.Color = Color.DarkMagenta;
            myPen.Width = 1;
        }

        private void DrawCircle(int x, int y, int width, int height, Pen myPen, PaintEventArgs e)
        {
            e.Graphics.DrawEllipse(myPen, x, y, width, height);
        }

        private void bGraphic1_Click(object sender, EventArgs e)
        {
            bGraph1Clicked = true;
            this.Refresh();
        }

        private void bGraphic2_Click(object sender, EventArgs e)
        {
            bGraph2Clicked = true;
            this.Refresh();
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            InitDrawingTools(e);

            if (bGraph1Clicked)
            {
                x1 = 260;
                y1 = 40;

                for (number = 1; number <= 25; number = number + 5)
                    DrawCircle(x1, y1, number, number, myPen, e);
            }

            if (bGraph2Clicked)
            {
                x1 = 260;
                y1 = 100;

                for (number = 2; number <= 26; number = number + 4)
                {
                    hlf = number / 2;
                    DrawCircle(x1 - hlf, y1 - hlf, number, number, myPen, e);
                }
            }
        }
    }
}


2) Crete Windows Forms application with the following functionalities:
  • Draw numbers from 1 to 10 with words on English and Bulgarian; 
  • Create a button that, when pressed, alternates colors pre-set in an array, for a background of the form 
  • A ComboBox control to be used to also loads predefined colors in an array to change the color of the shape. 
  • Set the number of days in the months in an array and use a DateTimePicker control to indicate how many days have passed since the beginning of the year to the selected day. 

Solution:
Create new Windows Forms Application project and design the form as shown in the picture:

Name the controls as follows:
- Button „Initialize“ – bInitialize
- Button „Change Form Color“ – bChangeFormColor
- Button „Add Color“ – bAddColor
- ComboBox control – cbColors
- DateTimePicker control – dateTimePicker1
- TextBox control – tbDateTime
Replace the content of Form1.cs with the following:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace Arrays
{
    public partial class Form1 : Form
    {
        int number, x1, y1, widht, height;
        int colorCount = 0;

        string[] EnglishNumbers;
        string[] BulgarianNumbers;
        string[] EnglishColors;

        int[] Days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        
        Color[] Colors;
        Color[] EnglishColor;

        List<Color> colorList = new List<Color>();

        bool bInitializeClicked = false;
        bool bAddColorClicked = false;

        SolidBrush myBrushDrawText = new SolidBrush(Color.DarkCyan);
        Font drawFont = new Font("Courier New", 10, FontStyle.Bold);
        string drawString = "";

        Pen myPen = new Pen(Color.Black, 2);

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            EnglishNumbers = new string[11];
            EnglishNumbers[0] = "zero";
            EnglishNumbers[1] = "one";
            EnglishNumbers[2] = "two";
            EnglishNumbers[3] = "three";
            EnglishNumbers[4] = "four";
            EnglishNumbers[5] = "five";
            EnglishNumbers[6] = "six";
            EnglishNumbers[7] = "seven";
            EnglishNumbers[8] = "eight";
            EnglishNumbers[9] = "nine";
            EnglishNumbers[10] = "ten";

            BulgarianNumbers = new string[11] {"нула", "едно", "две", "три", "четири", "пет", "шест", "седем", "осем", "девет", "десет"};

            Colors = new Color[3];
            Colors[0] = Color.Red;
            Colors[1] = Color.Brown;
            Colors[2] = Color.Green;

            EnglishColorsFunc();
        }

        private void EnglishColorsFunc()
        {
            EnglishColors = new string[4] {"Red", "Yellow", "Blue", "Green"};
            EnglishColor=new Color[4] {Color.Red, Color.Yellow, Color.Blue, Color.Green};

            cbColors.Text = "Select color:";

            for (number = 0; number < 4; number++)
                cbColors.Items.Add(EnglishColors[number]);
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            if (bInitializeClicked)
                StringInitialize(e);

            if (bAddColorClicked)
                DisplayColors(e);
        }

        private void DrawStrings(string drawString, Font drawFont, Brush myBrushDrawText, int x, int y, PaintEventArgs e)
        {
            e.Graphics.DrawString(drawString, drawFont, myBrushDrawText, x, y);
        }

        private void DrawEllipse(int x1, int y1, int width, int height, Pen myPen, PaintEventArgs e)
        {
            e.Graphics.DrawEllipse(myPen, x1, y1, width, height);
        }
        
        private void bInitialize_Click(object sender, EventArgs e)
        {
            bInitializeClicked = true;
            
            this.Refresh();
        }

        private void StringInitialize(PaintEventArgs e)
        {
            x1 = 20;
            y1 = 50;

            for (number = 0; number <= 10; number++)
            {
                drawString = number.ToString();
                DrawStrings(drawString, drawFont, myBrushDrawText, x1, y1, e);

                DrawStrings(EnglishNumbers[number].ToString(), drawFont, myBrushDrawText, x1 + 50, y1, e);
                DrawStrings(BulgarianNumbers[number].ToString(), drawFont, myBrushDrawText, x1 + 100, y1, e);
                
                y1 = y1 + 15;
            }
        }

        private void bChangeFormColor_Click(object sender, EventArgs e)
        {
            colorCount++;

            if (colorCount > 2)
                colorCount = 0;

            this.BackColor = Colors[colorCount];
        }

        private void cbColors_SelectedIndexChanged(object sender, EventArgs e)
        {
            number = cbColors.SelectedIndex;

            this.BackColor = EnglishColor[number];
        }

        private bool IsDate(string inputDate)
        {
            DateTime dt;
            return DateTime.TryParse(inputDate,out dt);
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            int mounth = dateTimePicker1.Value.Month;
            int julian = dateTimePicker1.Value.Day;
            int year = dateTimePicker1.Value.Year;

            if (IsDate("2/29/" + year))
                Days[2] = 29;
            else
                Days[2] = 28;

            for (int m = 1; m < mounth - 1; m++)
                julian = julian + Days[m];

            tbDateTime.Text = "Day " + julian;
        }

        private void DisplayColors(PaintEventArgs e)
        {
            x1 = bAddColor.Location.X;
            y1 = bAddColor.Location.Y + bAddColor.Height;
            widht = height = 25;

            foreach (Color getColorFromList in colorList)
            {
                myPen.Color = getColorFromList;
                
                DrawEllipse(x1, y1, widht, height, myPen, e);

                x1 = x1 + 30;
                
                if (x1 > this.Width - 15)
                {
                    x1 = bAddColor.Location.X;
                    y1 = y1 + 30;
                }
            }
        }
        
        private void bAddColor_Click(object sender, EventArgs e)
        {
            bAddColorClicked = true;

            colorDialog1.ShowDialog();

            colorList.Add(colorDialog1.Color);
            
            this.Refresh();
        }
    }
}


Self-assignments
1) Create Windows Forms application that contains two arrays: arrayMounth of type string and arrayDays of type int. When a button is pressed, display the number of days for each month in format > Month: Number of Days.
2) Create an application that allows the insertion of a matrix [3x3] and a calculation of its determinant. Entered matrix elements to be stored in a three-dimensional array. Entering matrix elements to take place via DataGridView control.