Flow control in C#
In this part of the C# tutorial, we will talk about the flow control. We will define several keywords that enable us to control the flow of a C# program.In C# language there are several keywords that are used to alter the flow of the program. When the program is run, the statements are executed from the top of the source file to the bottom. One by one. This flow can be altered by specific keywords. Statements can be executed multiple times. Some statements are called conditional statements. They are executed only if a specific condition is met.
The if statement
Theif
statement has the following general form: if (expression)The
{
statement;
}
if
keyword is used to check if an expression is true. If it is true, a statement is then executed. The statement can be a single statement or a compound statement. A compound statement consists of multiple statements enclosed by the block. A block is code enclosed by curly brackets. using System;We have a num variable. It is assigned 31. The
public class CSharpApp
{
static void Main()
{
int num = 31;
if (num > 0)
{
Console.WriteLine("num variable is positive");
}
}
}
if
keyword checks for a boolean expression. The expression is put between square brackets. 31 > 0 is true, so the statement inside the block is executed. $ ./ifstatement.exeThe condition is met and the message is written to the console.
num variable is positive
using System;More statements can be executed inside the block, enclosed by curly brackets.
public class CSharpApp
{
static void Main()
{
int num = 31;
if (num > 0)
{
Console.WriteLine("num variable is positive");
Console.WriteLine("num variable equals {0}", num);
}
}
}
We can use the
else
keyword to create a simple branch. If the expression inside the square brackets following the if keyword evaluates to false, the statement following the else
keyword is automatically executed. using System;We have a sex variable. It has "female" string. The boolean expression evaluates to false and we get "It is a girl" in the console.
public class CSharpApp
{
static void Main()
{
string sex = "female";
if (sex == "male") {
Console.WriteLine("It is a boy");
} else {
Console.WriteLine("It is a girl");
}
}
}
$ ./branch.exeWe can create multiple branches using the
It is a girl
else if
keyword. The else if
keyword tests for another condition, if and only if the previous condition was not met. Note, that we can use multiple else if
keywords in our tests. using System;We have a numerical variable and we test it, if it is a negative number or positive or if it equals to zero. The first expression evaluates to false. The second condition is met. The program prints 'a equals to zero' to the console. The rest of the branch is skipped. If the previous conditions were not met, than the statement following the
public class CSharpApp
{
static void Main()
{
int a = 0;
if (a < 0) {
Console.WriteLine("a is negative");
} else if (a == 0) {
Console.WriteLine("a equals to zero");
} else {
Console.WriteLine("a is a positive number");
}
}
}
else
keyword would be executed. The switch statement
Theswitch
statement is a selection control flow statement. It allows the value of a variable or expression to control the flow of program execution via a multi way branch. It creates multiple branches in a simpler way than using the combination of if
, else if
statements. We have a variable or an expression. The
switch
keyword is used to test a value from the variable or the expression against a list of values. The list of values is presented with the case
keyword. If the values match, the statement following the case
is executed. There is an optional default
statement. It is executed, if no other match is found. using System;In our program, we have a domain variable. We read a value for the variable from the command line. We use the
public class CSharpApp
{
static void Main()
{
string domain = Console.ReadLine();
switch (domain) {
case "us":
Console.WriteLine("United States");
break;
case "de":
Console.WriteLine("Germany");
break;
case "sk":
Console.WriteLine("Slovakia");
break;
case "hu":
Console.WriteLine("Hungary");
break;
default:
Console.WriteLine("Unknown");
break;
}
}
}
case
statement to test for the value of the variable. There are several options. If the value equals for example to "us" the "United States" string is printed to the console. $ ./selectcase.exeWe have entered "hu" string to the console and the program responded with "Hungary".
hu
Hungary
The while statement
Thewhile
statement is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. This is the general form of the
while
loop: while (expression)The
{
statement;
}
while
keyword executes the statements inside the block enclosed by the curly brackets. The statements are executed each time the expression is evaluated to true. using System;In the code example, we calculate the sum of values from a range of numbers.
public class CSharpApp
{
static void Main()
{
int i = 0;
int sum = 0;
while (i < 10)
{
i++;
sum += i;
}
Console.WriteLine(sum);
}
}
The
while
loop has three parts. Initialization, testing and updating. Each execution of the statement is called a cycle. int i = 0;We initiate the i variable. It is used as a counter.
while (i < 10)The expression inside the square brackets following the
{
...
}
while
keyword is the second phase, the testing. The statements in the body are executed, until the expression is evaluated to false. i++;The last, third phase of the
while
loop. The updating. We increment the counter. Note that improper handling of the while
loops may lead to endless cycles. It is possible to run the statement at least once. Even if the condition is not met. For this, we can use the
do while
keywords. using System;First the iteration is executed and then the truth expression is evaluated.
public class CSharpApp
{
static void Main()
{
int count = 0;
do {
Console.WriteLine(count);
} while (count != 0);
}
}
The for statement
When the number of cycles is know before the loop is initiated, we can use thefor
statement. In this construct we declare a counter variable, which is automatically increased or decreased in value during each repetition of the loop. using System;In this example, we print numbers 0..9 to the console.
public class CSharpApp
{
static void Main()
{
for (int i=0; i<9; i++)
{
Console.WriteLine(i);
}
}
}
for (int i=0; i<9; i++)There are three phases. First, we initiate the counter i to zero. This phase is done only once. Next comes the condition. If the condition is met, the statement inside the for block is executed. Then comes the third phase; the couter is increased. Now we repeat the 2, 3 phases until the condition is not met and the for loop is left. In our case, when the counter i is equal to 9, the for loop stops executing.
{
Console.WriteLine(i);
}
The foreach statement
Theforeach
construct simplifies traversing over collections of data. It has no explicit counter. The foreach
statement goes through the array or collection one by one and the current value is copied to a variable defined in the construct. using System;In this example, we use the
public class CSharpApp
{
static void Main()
{
string[] planets = { "Mercury", "Venus",
"Earth", "Mars", "Jupiter", "Saturn",
"Uranus", "Neptune" };
foreach (string planet in planets)
{
Console.WriteLine(planet);
}
}
}
foreach
statement to go through an array of planets. foreach (string planet in planets)The usage of the
{
Console.WriteLine(planet);
}
foreach
statement is straightforward. The planets is the array, that we iterate through. The planet is the temporary variable, that has the current value from the array. The foreach
statement goes through all the planets and prints them to the console. $ ./planets.exeRunning the above C# program gives this output.
Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
The break, continue statements
Thebreak
statement can be used to terminate a block defined by while
, for
or switch
statements. using System;We define an endless
public class CSharpApp
{
static void Main()
{
Random random = new Random();
while (true)
{
int num = random.Next(1, 30);
Console.Write(num + " ");
if (num == 22)
break;
}
Console.Write('\n');
}
}
while
loop. We use the break
statement to get out of this loop. We choose a random value from 1 to 30. We print the value. If the value equals to 22, we finish the endless while loop. $ ./break.exeWe might get something like this.
29 21 26 6 29 3 10 3 18 6 3 22
The
continue
statement is used to skip a part of the loop and continue with the next iteration of the loop. It can be used in combination with for
and while
statements. In the following example, we will print a list of numbers, that cannot be divided by 2 without a remainder.
using System;We iterate through numbers 1..999 with the
public class CSharpApp
{
static void Main()
{
int num = 0;
while (num < 1000)
{
num++;
if ((num % 2) == 0)
continue;
Console.Write(num + " ");
}
Console.Write('\n');
}
}
while
loop. if ((num % 2) == 0)If the expression num % 2 returns 0, the number in question can be divided by 2. The
continue;
continue
statement is executed and the rest of the cycle is skipped. In our case, the last statement of the loop is skipped and the number is not printed to the console. The next iteration is started. In this part of the C# tutorial, we were talking about control flow structures.
0 comments:
Post a Comment