Loop Structures and Arrays

So, let's look at some loop structures. This time we're going to do some string parsing with loops. The first goal: we're going to take the sum of all numbers in an array. Look at the following:
        Dim Weights As Integer() = New Integer() {20, 30, 40, 50, 60}
        Dim Heights() As Integer = New Integer() {20, 30, 40, 50, 60}
        'Both methods are valid in VB.
        private void btn5_Click(object sender, EventArgs e) {
            int lv;
            int[] weights = new int[] {10, 30, 70, 60, 20};
            // Arrays use brackets (square brackets) and placing [] after weights gives you an error.
        }// End of btn 5's click procedure.
Notice that C# uses square brackets to give an index to the array, while VB uses () parentheses to get the array. Again, VB parentheses doing double duty - parentheses are used for calling functions and for getting an index to an array, which makes it easy if you're worried about calling a function with a number and getting it mixed up with a simple array. Fortunately, Visual Studio Intellisense typically pops up telling you if you need to use square brackets or parentheses.
Also, notice how arrays are declared in C#. In VB.NET, you can have the () after Integer or after Weights and both turn out to be same thing. Not so in C# -- in C#, the [] must be after the data type because the [] is more of a description of the data type rather than the name. You are using an array of integers, not an array of names for integers! Initializing the values of an array can be done the same way that it is done in VB.NET: simply place new, the type of elements in the array, square brackets, and put in the values of the elements inside the array in between the braces. If you want to initialize a blank array, just put int[] weights = new int[5] and you'll have an array.
Here is another important distinction that I have to mention about arrays. In VB.NET, if you declare an array like this:
        Dim Weights As Integer() = New Integer(5) {}
The 5 references the maximum index of the array. Therefore the array has 6 elements: 0, 1, 2, 3, 4, and 5. If you declare an array the same way in C#:
            int[] weights = new int[5];
The 5 references the size of the array. Therefore the array has 5 elements: 0, 1, 2, 3, and 4. This is very important to understand if you are dealing with arrays, because you can easily find yourself going out of bounds on the C# array trying to access element five. Going from C# to VB, you may end up with bad results if you use .GetUpperBound in a loop and process element five without putting anything in it.
OK, so let's get the total of all of the items in the array.
        private void btn5_Click(object sender, EventArgs e) {
            int lv, tot = 0;
            int[] weights = new int[] {20, 40, 60, 70, 30};
            // Arrays use brackets (square brackets) and placing [] after weights gives you an error.
            for (lv = 0 ; lv <= weights.GetUpperBound(0) ; lv++) {
                tot += weights[lv];  // Add value of item in array to total.
            } // End of for loop using lv.
        }// End of btn 5's click procedure.
        Dim Weights As Integer() = New Integer() {10, 20, 30, 70, 60}
        Dim LV As Integer, Tot As Integer = 0
        For LV = 0 To Weights.GetUpperBound(0)
            Tot += Weights(LV)  'Add value of item in array to total
        Next
The VB.NET code is equivalent to the C# code. Now, let's look at the C# for loop. The for loop in C# consists of three sections:
The first section sets the initial value of the loop variable. In this case, we start off the loop by setting lv to zero. The last section (at the right end of the for loop) specifies what the for loop should do everytime it loops. In this case, we have lv++. In C#, lv++ is equivalent to saying lv = lv + 1 in VB.NET (and lv = lv + 1 also works in C#, if you desire to do that). So, everytime the loop loops, lv is incremented by one. The middle section of the for loop - in between the semicolons - specifies a condition that is used to determine if the loop should continue. While the condition is true, the loop will continue to loop. So, if you were to place a condition that is always true as the second section, you'll instantly have an infinite loop. If you type in the boolean value true for the second section, you'd get a compiler warning stating that execution will never get past the for loop.
So, you can also make the loop go backwards by changing around the three sections' content:
            for (lv = weights.GetUpperBound(0) ; lv >= 0 ; lv--) {
                tot += weights[lv];  // Add value of item in array to total.
            } // End of for loop using lv.
This loop makes the value of lv start from the upperbound and count backwards to zero. Notice that, in addition to the initial section, the condition has to be altered as well as the looping statement. The loop must decrement the value of lv, and it now stops looping once lv falls below 0.
Let's look at other loops in C# by parsing some strings. This time we will add a colon before every lowercase letter in a string. If you do this with a for loop going backwards, you'll keep finding the letter that you moved upwards into the string. You could do this with a for loop, but we'll use a while loop (because the next example is easier to perform with a while loop).
        private void btn6_Click(object sender, EventArgs e) {
            string S = tb2.Text;
            int lv = 0;
            while (lv < S.Length) {
                if (S[lv] >= 'a' && S[lv] <= 'z') {
                    S = S.Insert(lv, ":");
                    ++lv; // Incrementing lv prevents checking a letter already checked.
                } // End of if block
                ++lv;
            } // End of while loop
            tb2.Text = S;
        } // End of btn 6's click procedure.
While loops exist in VB.NET. Before VB.NET, they were While...Wend loops. But, Wend looks silly, so, in VB.NET, they turned into While and End While loops. In both cases, the VB Do Loop was much more robust and could do everything that a While Loop could do. So, in VB.NET, you essentially have two types of loops: For Loops and Do Loops. The rule of use between each was covered in the 'avoiding exit statements': use For Loops only if you have to do something to every element that you are looping through... otherwise, use a Do Loop. But enough about VB.NET, we're using C#!
Notice that the while loop is very simple in nature: you only need a condition and then you start making the while block. Note that there is no logical opposite of while (e.g. no 'until' keyword) just as there isn't one for the While Loop in VB. So, you can't set up an until loop in C#. You have to do the logical negation yourself. Speaking of logical operators:
Notice the && in the if block. && is equivalent to AndAlso in VB.NET. This means that both conditions of the if statement must be satisfied in order for the if block to run. So, the if statement requires the character to be from a to z. Also, note that we can refer to the individual characters in a string by using the [] square brackets. In VB.NET, you had to use the .Chars() member to access the characters of a string. Also, just like VB.NET, you cannot assign characters to the string to overwrite the character. You have to use the members of the string object to edit the string.
Another thing to note: characters in C# are surrounded by single quotes. In VB.NET, you'd put a lowercase c at the end of a single character string to make it a character (as in "P"c), but in C#, you just use single quotes (as in 'P'c).
Another thing to note: lv++ and ++lv do the same thing. The only differences comes when you want to use the increment expression in another expression. I have never found a need to do that, so I will typically write lv++ whenever I need to increment. The same is true for lv-- and --lv. Now, let's do something more complex. We're going to loop through a string until we find a space. When we find a space, we'll delete the space and then stop looping through the string.
        private void btn6_Click(object sender, EventArgs e) {
            string S = tb2.Text;
            int lv = 0;
            while (lv < S.Length && S[lv] != ' ') {
                ++lv;
            } // Loops through string to find a space.
            if (lv < S.Length) {
                S = S.Remove(lv, 1); // Remove the space we found.
            } else {
                MessageBox.Show("No space bar found in second textbox.");
            } // End of the if statement
            tb2.Text = S; // Return the string to the textbox.
        } // End of btn 6's click procedure.
Easy! You can also use && in the while block to have two conditions required to keep looping. A note on logical operators: && is the same as AndAlso and || is the same as OrElse. Not is ! when used for Booleans and ~ when used on integers as a binary operator. Other binary operators are &, equivalent to And in VB.NET, |, equivalent to Or in VB.NET, and ^, equivalent to Xor in VB.NET. Bit shifting << and >> are the same in both languages. Just remember to put the semicolon at the end.
        private void btn6_Click(object sender, EventArgs e) {
            string S = tb2.Text;
            int lv = tb2.TextLength;
            do {
                lv--;
            } while (lv >= 0 && S[lv] != ' ');
            if (lv >= 0) {
                S = S.Remove(lv, 1); // Remove the space we found.
            } else {
                MessageBox.Show("No space bar found in second textbox.");
            } // End of the if statement
            tb2.Text = S; // Return the string to the textbox.
        } // End of btn 6's click procedure.
The third type of loop is the do ... while loop. This is, obviously, equivalent to the Do While Loop of VB.NET, but with a few exceptions:
There is no until keyword in .NET. So, if you have an expression that you need to be false while the loop is running, you should put it all in parentheses and put an exclamation mark outside of it:
        private void btn6_Click(object sender, EventArgs e) {
            string S = tb2.Text;
            int lv = tb2.TextLength;
            do {
                lv--;
            } while (!(lv < 0 || S[lv] == ' '));
            if (lv >= 0) {
                S = S.Remove(lv, 1); // Remove the space we found.
            } else {
                MessageBox.Show("No space bar found in second textbox.");
            } // End of the if statement
            tb2.Text = S; // Return the string to the textbox.
        } // End of btn 6's click procedure.
Like this. In addition, you cannot move the while part of the loop to the top and keep the do there. This functionality is equivalent to the while loop which already exists. The do loop is less versatile in this regard, but the functionality is still available to do what you could have done in VB.NET.
Notice that do goes directly into the do block. No condition is required to enter a do loop. In my experiences, do loops of this nature are much less common than the while loop. And it is technically possible to use a for loop or a while loop in place of a do loop, since the code in a do loop can be placed outside and before the loop itself to be executed.
        private void btn7_Click(object sender, EventArgs e) {
            foreach (Control ctl in this.Controls) {
                ctl.Text = "Test";
            } // End of foreach loop
        } // End of btn 7's click procedure.
The code above changes the text on all of the controls on the form to Test. The foreach loop looks similar to the while loop except it does what the For Each Loop does in VB.NET: it loops through the items in a list and runs the code in the foreach block everytime it gets an item. The main difference in VB.NET is that you must define what type of object will be used to loop through the list. In the above example, you must have Control in the parentheses for the loop to loop through control in the form's Controls list. If you declare Control ctl outside of the foreach block, you will get an error when you try to reuse ctl in the foreach loop, so use it in the loop.
Also, this in C# is equivalent to Me in VB.NET.

Strings

I suppose now is a good time to talk about strings in C#. You may know that in VB.NET, if you want a quote character to appear in a string, you have to double up the quotes:
"She had a ""wardrobe malfunction""."
To do the same in C#, you use a backslash followed by a quote to place a quote character in the string.
"She had a \"wardrobe malfunction\"."
Which raises the next question: how do you put a backslash character in a string? Use two backslashes.
"Go to C:\\Windows\\System128\\"
Since computer paths use so many slashes, you can also write the previous example using at-string:
@"Go to C:\Windows\System128\"
Placing @ in front of a string constant like the ones just above essentially causes them to be parsed like VB.NET strings. This means that, with @ at the front of the string, a quote character can be put into the string by typing two "" quotes.
@"Go to C:\""Windows""\System128\"
This makes writing filepaths less burdensome, but you lose out of the other special escape sequences that C# offers:
"First line.\r\nSecond line." Namely, C# has special characters for making new lines. A proper new line consists of a carriage return \r and a line feed \n. Of course, there's always the option of using System.Environment.Newline for the most proper new line construct.
String concatenation in C# uses the + operator, since the & operator is used for bitwise operations.

Functions and Subroutines

        private float thrownheight(float verticalspeed, float g) {
            // Calculates the maximum height reached by an object thrown at a specified speed using the
            // specified acceleration due to gravity.
            // Vf - Vo = g * t => t = -Vo/g => d = vo*t + 0.5*g*t*t => d = -vo*vo/g + 0.5*vo*vo/g
            // d = vo*vo/2*g
            return verticalspeed * verticalspeed / g / 2f;
        } // End of thrownheight function.
This is a function that takes two floats and returns one float. The formula is above. The focus here is what is different in making the function in C# than in VB.NET. The first thing is that there is no function keyword. Instead, the only way to identify that the above block of code is a function is to realize that after private is the word 'float', followed by two arguments and braces. So, instead of:
Private Function ThrownHeight(VerticalSpeed As Single, G As Single) As Single
You have:
private float thrownheight(float verticalspeed, float g) { return something };
Which brings me to the next part: it is vitally important to return a value from a function, otherwise you'll probably get an error in Visual Studio stating that not all paths return a value. You also cannot return a value from a function by assigning the value to the function's name. Remember to resist the urge to put "as float" after your function.
Calling the function is just as easy as it is in VB.NET.
        private void btn8_Click(object sender, EventArgs e) {
            float high;
            high = thrownheight(45f, 9.8f);
            MessageBox.Show(high.ToString());
        } // End of btn 8's click procedure.
This makes it considerably easy to use the available functions. As long as the data types required are present, there's no other tricky keywords required to call functions in C#. Notice the semicolons are still required.
We've already seen subroutines in C#. The btn8_Click procedure above is a subroutine. The difference between in functions and subroutines in C# is the return value (remember that the return value for functions is on the left of the function name). In a subroutine, you have void instead of float or whatever the return type. Void just means that no data type will be returned from this block... so value is returned. This is the same as a subroutine in VB.NET: no value is returned from a subroutine.
        private void setmytext(float setting) {
            this.Text = setting.ToString(); // This does nothing more than puts a float's value into the form's text.
        } // End of setmytext subroutine.
This is an example of a subroutine that is not an event handler.
        private void btn8_Click(object sender, EventArgs e) {
            float high;
            high = thrownheight(45f, 9.8f);
            setmytext(high);
        } // End of btn 8's click procedure.
Subroutines in C# are also called the same way that they are in VB.NET. You also have the option of ignoring the returned values of functions in C# and calling the functions as if they were subroutines as well.
        private void clearmytext() {
            this.Text = "";
        } // End of clearmytext subroutine.
An example of a subroutine that does not return a value.
        private void btn7_Click(object sender, EventArgs e) {
            clearmytext();
        } // End of btn 7's click procedure.
Called like this.