Lesson 5 - Conditions (branching) in C# .NET
In the previous exercise, Solved tasks for C# .NET lesson 4, we've practiced our knowledge from previous lessons.
Lesson highlights
Are you looking for a quick reference on conditions (branching) in C# .NET instead of a thorough-full lesson? Here it is:
Controlling the program's flow using the
if
keyword:
{CSHARP_CONSOLE}
Console.WriteLine("Enter your name:");
string name = Console.ReadLine();
if (name == "Peter")
Console.WriteLine("Hey, I'm Peter too!"); // printed only when Peter is entered
Console.WriteLine("Thanks for your name!"); // printed always
Console.ReadKey();
{/CSHARP_CONSOLE}
Reacting to both situations (when the condition is met and
when not) using else
and wrapping branches with
multiple commands in {}
:
{CSHARP_CONSOLE}
Console.WriteLine("Enter your name:");
string name = Console.ReadLine();
if (name == "Peter")
{
Console.WriteLine("Hey, I'm Peter too!"); // printed only when Peter is entered
Console.WriteLine("Nice to meet you!"); // printed only when Peter is entered
}
else
Console.WriteLine("Nice to meet you, I'm Peter!"); // printed for any other name
Console.WriteLine("Thanks for your name!"); // printed always
Console.ReadKey();
{/CSHARP_CONSOLE}
Using the &&
(the "and" operator) and
||
(the "or" operator) and eventually additional
()
/if
/else
statements:
{CSHARP_CONSOLE}
Console.WriteLine("Enter your name:");
string name = Console.ReadLine();
if (name == "Peter")
{
Console.WriteLine("Hey, I'm Peter too!"); // printed only when Peter is entered
Console.WriteLine("Nice to meet you!"); // printed only when Peter is entered
}
else {
if (name == "Mike" || name == "Michael")
Console.WriteLine("My brother's name is Michael too!"); // printed only when Michael is entered
Console.WriteLine("Nice to meet you, I'm Peter!"); // printed for any other name than Peter
}
Console.WriteLine("Thanks for your name!"); // printed always
Console.ReadKey();
{/CSHARP_CONSOLE}
Reacting to multiple states of one variable
using a switch
statement:
{CSHARP_CONSOLE}
Console.WriteLine("Welcome to our calculator");
Console.WriteLine("Enter the first number:");
double a = double.Parse(Console.ReadLine());
Console.WriteLine("Enter the second number:");
double b = double.Parse(Console.ReadLine());
Console.WriteLine("Choose one of the following operations:");
Console.WriteLine("1 - addition");
Console.WriteLine("2 - subtraction");
Console.WriteLine("3 - multiplication");
Console.WriteLine("4 - division");
int option = int.Parse(Console.ReadLine());
double result = 0;
switch (option)
{
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
}
if ((option > 0) && (option < 5))
Console.WriteLine("Result: {0}", result);
else
Console.WriteLine("Invalid option");
Console.WriteLine("Thank you for using our calculator. Press any key to end the program");
Console.ReadKey();
{/CSHARP_CONSOLE}
Would you like to learn more? A complete lesson on this topic follows.
In the previous lesson, Solved tasks for C# .NET lesson 4, we discussed C# .NET data types in details. We need to react somehow to different situations if we want to program something. It may be, for example, a value entered by the user, according to which we would like to change the program flow. We metaphorically say that the program branches, and for branching we use conditions. We will pay attention to those in today's article. We're going create a program which calculates square roots, and we're going to improve our calculator.
Conditions
In C#, conditions are exactly the same as in all C-like languages, either way, I will explain everything for beginners. Advanced programmers will probably be bored for a moment
We write conditions using the if
keyword, which is followed by a
logical expression. If the expression is true, the following statement will be
executed. If it's not true, the following statement will be skipped, and the
program will continue with the next statement. Let's try it out:
{CSHARP_CONSOLE}
if (15 > 5)
Console.WriteLine("True");
Console.WriteLine("The program continues here...");
Console.ReadKey();
{/CSHARP_CONSOLE}
The output:
Console application
True
The program continues here...
If the condition is true, the command which writes text to the console will be executed. In both cases the program continues. Of course, a variable can also be part of the expression:
{CSHARP_CONSOLE}
Console.WriteLine("Enter a number");
int a = int.Parse(Console.ReadLine());
if (a > 5)
Console.WriteLine("The number you entered is greater than 5!");
Console.WriteLine("Thanks for the input!");
Console.ReadKey();
{/CSHARP_CONSOLE}
Let's look at the relational operators which we can use in expressions:
Meaning | Operator |
---|---|
Equal to | == |
Greater than | > |
Less than | < |
Greater than or equal to | >= |
Less than or equal to | <= |
Not equal | != |
Negation | ! |
We use the ==
operator for equality to avoid confusing it with a
normal assignment to a variable (the =
operator). If we want to
negate an expression, we enclose it in parentheses and write an exclamation mark
before the expression. If we want to execute more than one command, we have to
insert commands into a block of curly brackets:
{CSHARP_CONSOLE}
Console.WriteLine("Enter some number and I'll calculate a square root:");
int a = int.Parse(Console.ReadLine());
if (a > 0)
{
Console.WriteLine("The number you entered is greater than 0, so I can calculate it!");
double root = Math.Sqrt(a);
Console.WriteLine("The square root of " + a + " is " + root);
}
Console.WriteLine("Thanks for the input");
Console.ReadKey();
{/CSHARP_CONSOLE}
The output:
Console application
Enter some number and I'll calculate a square root:
144
You've entered a number greater than 0, I can calculate it!
Square root of 144 is 12
Thanks for the input
The program retrieves a number from the user, and if it's greater than
0
, it calculates the square root. We have used the
Math
class, which contains plenty of useful mathematical methods.
At the end of this course, we'll learn more about them. Sqrt()
returns the value as a double
data type. It'd be nice if our
program warned us if we entered a negative number. With what we know up until
now, we could write something like this:
{CSHARP_CONSOLE}
Console.WriteLine("Enter a number and I'll get its square root:");
int a = int.Parse(Console.ReadLine());
if (a > 0)
{
Console.WriteLine("The number you entered is greater than 0, so I can calculate it!");
double root = Math.Sqrt(a);
Console.WriteLine("The square root of " + a + " is " + root);
}
if (a <= 0)
Console.WriteLine("I can't calculate the square root of a negative number!");
Console.WriteLine("Thanks for the input!");
Console.ReadKey();
{/CSHARP_CONSOLE}
We must keep in mind the case where a == 0
, but also when it's
less than 0
. The code can be greatly simplified by using the
else
keyword which executes the following
statement or block of statements if the condition was not
true:
{CSHARP_CONSOLE}
Console.WriteLine("Enter a number and I'll get its square root:");
int a = int.Parse(Console.ReadLine());
if (a > 0)
{
Console.WriteLine("The number you entered is greater than 0, so I can calculate it!");
double root = Math.Sqrt(a);
Console.WriteLine("The square root of " + a + " is " + root);
}
else
Console.WriteLine("I can't calculate the square root of a negative number!");
Console.WriteLine("Thanks for the input!");
Console.ReadKey();
{/CSHARP_CONSOLE}
The code is much clearer, and we don't have to make up the negate condition
which could be very difficult with complex conditions sometimes. In the case of
multiple commands, there would be a { }
block again after the
else
keyword.
We also use the else
keyword when we need to modify the variable
used in a condition so we can't evaluate it later again. The program remembers
that the condition didn't apply and it'll move to the else
branch.
Let's look at an example: Consider a
number which value will be
either 0
or 1
and we'll be asked to swap those values
(if there is 0
, we put a 1
there, and the other way
around). Naively, we could write a code like this:
{CSHARP_CONSOLE}
int a = 0; // the variable is initialized with a value of 0
if (a == 0) // if the value is 0, we change its value to 1
a = 1;
if (a == 1) // if the value is 1, we change its value to 0
a = 0;
Console.WriteLine(a);
Console.ReadKey();
{/CSHARP_CONSOLE}
It doesn't work, does it? Let's take a closer look at the program. At the
very beginning, a
contains the value 0
, the first
condition is undoubtedly fulfilled and it assigns 1
into
a
. Well, suddenly, the second condition becomes true as well. What
should we do? When we swap the conditions, we'll have the same problem with
1
. Now, how do we solve this? You guessed it, using
else
!
{CSHARP_CONSOLE}
int a = 0; // the variable is initialized with a value of 0
if (a == 0) // if the value is 0, we change its value to 1
a = 1;
else // if the value is 1, we change its value to 0
a = 0;
Console.WriteLine(a);
Console.ReadKey();
{/CSHARP_CONSOLE}
Conditions can be composed by using two basic logical operators:
Operator | C-like syntax |
---|---|
Logical AND | && |
Logical OR | || |
Let's take a look at the example:
{CSHARP_CONSOLE}
Console.WriteLine("Enter a number between 10-20:");
int a = int.Parse(Console.ReadLine());
if ((a >= 10) && (a <= 20))
Console.WriteLine("The condition has been met.");
else
Console.WriteLine("You did it wrong.");
Console.ReadKey();
{/CSHARP_CONSOLE}
Of course operators can be combined with parentheses:
{CSHARP_CONSOLE}
Console.WriteLine("Enter a number between 10-20 or 30-40:");
int a = int.Parse(Console.ReadLine());
if (((a >= 10) && (a <= 20)) || ((a >=30) && (a <= 40)))
Console.WriteLine("The condition has been met.");
else
Console.WriteLine("You did it wrong.");
Console.ReadKey();
{/CSHARP_CONSOLE}
Switch
switch
is a construct taken from the C language, like most of C#'s syntax. It
allows us to relatively simplify the usage of if-else command sequences. Let's
remember our calculator from the first lesson, which had read two numbers and
calculated all 4 operations. Now, we want to choose the operation. Without the
switch
, we'd write the code like this:
{CSHARP_CONSOLE}
Console.WriteLine("Welcome to our calculator");
Console.WriteLine("Enter the first number:");
double a = double.Parse(Console.ReadLine());
Console.WriteLine("Enter the second number:");
double b = double.Parse(Console.ReadLine());
Console.WriteLine("Choose one of the following operations:");
Console.WriteLine("1 - addition");
Console.WriteLine("2 - subtraction");
Console.WriteLine("3 - multiplication");
Console.WriteLine("4 - division");
int option = int.Parse(Console.ReadLine());
double result = 0;
if (option == 1)
result = a + b;
else
if (option == 2)
result = a - b;
else
if (option == 3)
result = a * b;
else
if (option == 4)
result = a / b;
if ((option > 0) && (option < 5))
Console.WriteLine("Result: {0}", result);
else
Console.WriteLine("Invalid option");
Console.WriteLine("Thank you for using our calculator. Press any key to end the program.");
Console.ReadKey();
{/CSHARP_CONSOLE}
The output:
Console application
Welcome to our calculator
Enter the first number:
3.14
Enter the second number:
2.72
Choose one of the following operations:
1 - addition
2 - subtraction
3 - multiplication
4 - division
2
Result: 0.42
Thank you for using our calculator. Press any key to end the program.
Notice that we've declared the variable result
at the beginning,
so we could later assign something to it. If we declared it at every assignment,
C# would not compile the code and report an error since the variable would be
already declared. A variable can be declared only once. C# is not able to tell
whether a value has been already assigned to the result
variable.
It would report an error on the line where we're printing to the console because
C# doesn't like the fact that the variable being printed is not guaranteed to
contain a value. For this reason, we have to assign zero to the
result
variable at the beginning. Another trick is validating the
user's choice. The program should still work the same even without all the
else
s (but why keep on asking if we already have a result).
Now here's the same program using a switch
:
{CSHARP_CONSOLE}
Console.WriteLine("Welcome to our calculator");
Console.WriteLine("Enter the first number:");
double a = double.Parse(Console.ReadLine());
Console.WriteLine("Enter the second number:");
double b = double.Parse(Console.ReadLine());
Console.WriteLine("Choose one of the following operations:");
Console.WriteLine("1 - addition");
Console.WriteLine("2 - subtraction");
Console.WriteLine("3 - multiplication");
Console.WriteLine("4 - division");
int option = int.Parse(Console.ReadLine());
double result = 0;
switch (option)
{
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
}
if ((option > 0) && (option < 5))
Console.WriteLine("Result: {0}", result);
else
Console.WriteLine("Invalid option");
Console.WriteLine("Thank you for using our calculator. Press any key to end the program");
Console.ReadKey();
{/CSHARP_CONSOLE}
As you can see, the code is a bit clearer now. If we needed to execute
multiple commands in any branch of the switch
, surprisingly, we
wouldn't write it into the {}
block, but just under the first
command. The {}
block is replaced by a break
command
that causes a jumping out from the entire switch
. Beside of
case x:
, the switch
can also contain the
default:
branch, which will be executed if neither of the
case
s applied. It's up to you whether you use a switch or not.
Generally, it's useful only for a larger amount of branches and you always could
always it with an if
-else
sequence. Don't forget about
break
s. Obviously, you can use a switch
for
string
variables as well.
That is all for today. In the next lesson, Solved tasks for C# .NET lesson 5, we'll take a look at arrays and loops, i.e. finish up with the absolute basics of the C# language. Look forward to it
In the following exercise, Solved tasks for C# .NET lesson 5, we're gonna practice our knowledge from previous lessons.
Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.
Download
By downloading the following file, you agree to the license terms
Downloaded 39x (67.87 kB)
Application includes source codes in language C#