Hi and welcome to the Lesson 3 – Flow Control in C# on our tutorial series Learning C# with Zenva.
Tutorial Source Code
All of the source code for this tutorial can be downloaded here.
Sometimes, a program needs to repeat a process until some condition is met. We call that “loop”. In this lesson, we will see how to work with some structures as for instance, if statement, switch statements, while, do while, for and foreach. Let’s begin.
IF STATEMENT
The instruction IF has the following syntax:
if(expression) { statement; }
The “if” statement determines which way the program will continue. With the “if” statement, the program has to decide if it will execute some code or not.
First example: Let’s write a code using the method “Compare” from the String class we learned in the last lesson.
Considering str1 = “Learning C# with” and str2 = “Zenva.”;
Start a new project, name it FlowControlIfExample and write or copy and paste the code below.
using System; namespace FlowControlIfExample { class Program { static void Main(string[] args) { const string str1 = "Learning C# with ", str2 = "Zenva"; if(string.Compare(str1, str2) == 0) { Console.WriteLine("The two strings are equal!"); } else { Console.WriteLine("The two strings are different"); } Console.Read(); } } }
Understanding new code:
const string str1 = “Learning C# with”, str2 = “Zenva.”; Here I am declaring two constants, type string and initializing its value. The word const before everything means that this constant will not be modified. The two constants are separable by the comma.
As we observe, the program has an If statement to decide which way to go. In our example, we are comparing two strings if they are equals. If the result is 0 or (true), the program executes the first statement, else (meaning not true or 1) the program executes the second statement.
Running our program we have that the two strings are not equal.
We can use a ternary operator (?:) too (if-then-else constructs).
int n1 = 5, n2 = 1; string result = n1 > n2 ? "N1 is greater" : "N2 is greater"; //result: N1 is greater
Second example: using the methods “Contains” and “Replace”
Considering str1 = “Alan bought a Ferrari”;
using System; namespace FlowControlIfExample { class Program { static void Main(string[] args) { // const string str1 = "Learning C# with ", str2 = "Zenva"; /* if(string.Compare(str1, str2) == 0) { Console.WriteLine("The two strings are equal!"); } else { Console.WriteLine("The two strings are different"); } */ const string str1 = "Alan bought a Ferrari."; //Verifying if the condition is NOT TRUE (!) if (!str1.Contains("bought")) { Console.WriteLine("The str1 does not contain the word bought."); } else if (str1.Contains("Ferrari.")) //if the condition is TRUE { Console.WriteLine("What word do you want instead of Ferrari? "); string str2 = Console.ReadLine(); //gets the string from the user string str3 = str1.Replace("Ferrari", str2); //declaring str3 to receive the str1 content replaced Console.WriteLine(str3); //showing the new sentence. } Console.Read(); } } }
To comment the code we can use “//” in front of the line or /* */ for a block. When we have commented code, our application will not execute that line or block.
So in this code, we verify, if the first condition is NOT TRUE, (remember the operator “!”), we show a message that the word we chose to check in contains method does not exist in the specified sentence. If the word exists, then we go and check if exists the word “Ferrari”. If exists we ask for the user what word he wants instead of Ferrari. We read what the user type and store in the variable str2 that we just created.
Using the method replace, we pass the str1 + the new word using the replace method to the str3 and show it in the console application.
SWITCH STATEMENT
This statement is another way to simulate the use of several if statements. When the condition is met, we use the word “break” to interrupt the program of keep looking for other condition inside this statement. All early types (int, string, double, etc.) can be used with the instruction “switch.”
The instruction SWITCH has the following syntax:
switch(expression) { case constant-expression: statement(s); break; default: default expression; }
Example: The program asks the user to type a value between 1 and 7 which determines the day of the week.
For this example, let’s create another project and give it a name FlowControlExamples.
using System; namespace FlowControlExamples { class Program { static void Main(string[] args) { Console.Write("Type a number 1 - 7 to see the day of the week corresponding to this number: "); //Converting string to Int32. int numberDayOfWeek = Convert.ToInt32(Console.ReadLine()); switch (numberDayOfWeek) //Checking the number the user typed. { case 1: Console.WriteLine("The day number "+ numberDayOfWeek +" is Sunday!"); break; case 2: Console.WriteLine("The day number " + numberDayOfWeek + " is Monday!"); break; case 3: Console.WriteLine("The day number " + numberDayOfWeek + " is Tuesday!"); break; case 4: Console.WriteLine("The day number " + numberDayOfWeek + " is Wednesday!"); break; case 5: Console.WriteLine("The day number " + numberDayOfWeek + " is Thursday!"); break; case 6: Console.WriteLine("The day number " + numberDayOfWeek + " is Friday!"); break; case 7: Console.WriteLine("The day number " + numberDayOfWeek + " is Saturday!"); break; default: Console.WriteLine("This number is invalid."); break; } Console.Read(); } } }
Understanding new code:
As everything the user writes is a string, a number written in the console application is a string that needs to be converted to int type when the user writes numbers.
The difference between int16, int32, and int64 is their length.
Int16 — (-32,768 to +32,767)
Int32 — (-2,147,483,648 to +2,147,483,647)
Int64 — (-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807)
Running our application:
Imagine that the user is a nice guy and writes only numbers. But, what if the user had written text instead of numbers? An exception will be triggered because we are trying to convert letters to an int type. In this case, we had a FormatException.
Handling exceptions will be discussed in Lesson 06.
While and Do/While statements
While: used to repeat a block of code until a condition is true. The condition to execute the loop must be a boolean value.
The instruction WHILE has the following syntax:
While (expression) { statements; }
Do/While: works as same as the while, but using this statement we have our code executed at least once.
using System; namespace FlowControlExamples { class Program { static void Main(string[] args) { #region int x = 0; //creating a variable int starting with 0 as value. //Here the program shows us 0 as result Console.WriteLine("The value of 'x' is: "+ x); //the program shows x incrementing one by one until 10. //++x means x = x + 1; while (x < 10) { Console.WriteLine("The value of 'x' is: " + ++x); } Console.Read(); } } }
As you can see, there is a different word in the code: #region. My last code is all commented inside this “region”.
Running our application:
FOR / FOREACH
Also used for loops, but the difference is that here we already know how many times the condition will repeat. We declare a counter variable, which is automatically increased or decreased in value during each repetition of the loop.
The instruction FOR has the following syntax:
for (initialisation, expression, variable update) { statements; }
foreach (element in collection) { statements; }
With the for statement we specify the loop bounds (minimum or maximum) while with the foreach statement we do not need to specify a boundary.
We will write some code using the command for and foreach in the next lesson!
This is the end of this tutorial. I hope you have enjoyed and I see you in the next lesson!
Thank you!