C Sharp/Conditions

From Wikiversity
Jump to navigation Jump to search

Lesson Goals[edit | edit source]

This lesson will focus on basic conditonal flow of programming in C# including branching via the console. At the end of this lesson you should be able to:

  • Understand how to use basic conditional statements.
  • Explain the order in which switch cases work.
  • Use the console to read in user input and based on that decide to flow to a particular branch of code.
  • Understand how to use the more complex decision making programs and their logic.

Types of Condition[edit | edit source]

There are mainly 4 types of conditional statements in C#.

  • If-Else block
  • Switch case
  • C# branching statements

If-Else block being the easiest one with a variant of nested If-Else.

Condition flow chart[edit | edit source]

Following is a flow chart showing Conditional Dichotomy. It is a typical example of if-else block. The example here shows the common transaction in an ATM machine. Here an User is trying to withdraw $200.00 from the machine. The machine checks the balance first. Then if balance permits (if fund present?) then it disburses the money else it rejects the request. More of this elaborated below.

This second image for Switch-case is a simple example where based on the day of the current date it prints the day of the week Saturday and Sunday taken as the Weekend by default. Do note that this is how a switch-case normally gets defined. With specific declarations for each case, here day of the week, it also consists of a default value, in this case its the weekend. This default argument takes into effect only when all other conditions fails. More of this elaborated below.

If-Else Block[edit | edit source]

This is the most commonly used conditional statement. It is widely used in almost all programming language. The construct looks as follows, -

if(<boolean expression>)
{
 //section to 
 //execute on
 //'True'.
}
else
{
 //section to 
 //execute on
 //'False'.
}

The else part is optional. Note that the two execution section is mutually exclusive. Meaning only one of the two sections can execute at a time based on the result of the boolean expression. The boolean expression is simply an expression which evaluates to boolean results of true or false. Examples of boolean expression,-

Expression Result
1==1 True
1<=0 False
c==12-rate True (when c=5 and rate=7)

c==12-rate True (when c=5 and rate=7) Notice that, in the first example (1==1) we are compairing,and hence 'double' equal sign is used. This is an example of Operator overloading. == is used to compare both sides of the operator. Whareas, = is used to assign values, essentially from right to left. Please note that the boolean expression can be a boolean variable as well. And if the block does not contain an else statement and the if block has an one liner execution statement then it can be without the curly braces as follows, -

if(boolean expression) execution statement;

As you can notice, there has to be a semi-colon in the end of the statement.

Nested IF-Else[edit | edit source]

Here one If-else block is nested within another. One has to be careful in closing the inner if before closing the outer if.

if(<boolean expression 1>)
{
 <execution statement(s) 1>
 if(<boolean expression 2>)
 {
  <execution statement(s) 2>
 }
 else
 {
  <execution statement(s) 3>
 }
}
else
{
 <execution statement(s) 4>
}

Here if the boolean expression 1 is true then after executing the execution statement(s) 1 code flows to the boolean expression 2 check. Based on the result either execution statement(s) 2 or execution statement(s) 3 gets executed.

IF-Else if Ladder[edit | edit source]

This is the complex nested form of If-Else block. Here the erstwhile else statement gets replaced by one or many else if statement and there could be an optional ending else statement.

if(<boolean expression 1>)
{
 <execution statement(s) 1>
}
else if(<boolean expression 2>)
{
 <execution statement(s) 2>
}
...
else
{
 <execution statement(s) n>
}

The order of the code flow is first it checks boolean expression 1 and if it is true then it executes the execution statement(s) 1. Else it again evaluates boolean expression 2 and if it is true then execution statement(s) 2 gets executed. At the end if none of these If or else if block works then the last else block executes and code flows out of the IF-Else block. Important: Only one execution statement(s) 1 gets executed in this block of code. This apporach is very clumsy and error prone. The better way is to represent it in switch case. though sometimes its unavoidable, especially when the boolean expression 1 and boolean expression 2 are way too different.

Switch case[edit | edit source]

Typically this is required when based on different values of a particular expression, different actions need to be performed. The basic construct of a switch case looks as follows, -

switch (expression)
{
  case constant-expression:
     statement
     jump-statement
  [default:
     statement
     jump-statement]
}

Here the expression result can have multiple values. Essentially string or integer. Case section with constant-expression can have the value as constant or an expression that results in a constant. This decides to which case statement control will transfer. The default section is optional and only gets executed when none of the constant-expression matches with the expression. The jump-statement must be there at the end of each block to step out of the switch case once a particular statement sections gets executed.

C# branching statements[edit | edit source]

There are number of branching statements or jump-statements available in C#.

Branching Statements Description
break Exits the current block of code.
continue Only used in a loop statement. Skips remaining logic in enclosing loop, and goes back to the loop conditon to check if the loop should be executed again from the begining.
goto Jumps to the <labelname>: line of the code.
return Used in methods to return a value.
throw Used to throw an exception.

C# Ternary Operator[edit | edit source]

This is a short way of representing conditional statement in C#. Ternary operator has one boolean expression and can return one of possible two values. Here is the syntax.

some-variable=(<boolean expression>)? <true-value> : <false-value>

Now lets take a look at an example:

 using System;
 namespace TernaryOperatorExample
 {
    class Program
    {
        static void Main(string[] args)
        {
            int a = 1;
            string b = (a < 2) ? "true" : "false";
            Console.WriteLine(b);
            Console.Read();
        }
    }
 }

Output[edit | edit source]

true

Since (a < 2) evaluates to true, true is printed. If (a < 2) evaluated to false then false would be the result.

Practice Exercises[edit | edit source]

  • Create a program that prints the day of the week by taking input as any date. Which conditional statement you will prefer and why? What are the jump statements you used? Make lots of explanatory console outputs so that you can better understand what is going on at each step of your code.
  • You are supposed to create an ATM system. The following two sets of information are available to you, -

accountHolderName=john Doe accountNumber=001 account balance=$3000.00

accountHolderName=Mary Ann accountNumber=002 account balance=$10000.00

Now validate an account holder as per name and account number. On validation let the account holder do the transactions, like, withdraw sum, deposit sum, transfer amount to another account, etc. Do all the validations and use lots of messages to the end user.

-- Pasaban 07:20, 28 December 2009 (UTC)

Where To Go Next[edit | edit source]

Topics in C#
Beginners Intermediate Advanced
Part of the School of Computer Science