Descision making in C#
Decisions allow the program to produce different results when the program is run reacting to different situations and inputs.
The C# programming language enables you to write code that do different things based on expressions.
Using expressions
Expressions are pieces of code that evaluate to true or false. Expressions can say 'if user pressed A then do this, else do that'. The false keyword is a literal of type bool representing the boolean value false. Similarly the true keyword is a literal of type bool representing the Boolean value true.
Program 1 An if statement and a simple decision statement
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string theAnswer;
Console.WriteLine("Do you use C# ?");
theAnswer = Console.ReadLine();
if (theAnswer == "y")
{
Console.WriteLine("Good");
}
else
{
Console.WriteLine("o dear");
}
}
}
}
This example shows how to use an if statement to test the value of a variable. Note the use of the double-equals for comparison of values.
Single equals will not work here as single equals is used for equating values. Decisions using numbers The if statement can also be used to test numeric values as shown below :
Program 2 Numeric testing with if statement
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int theAnswer;
Console.WriteLine("How many fingers on one hand ?");
theAnswer = Convert.ToInt16(Console.ReadLine());
if (theAnswer == 5)
{
Console.WriteLine("Good");
}
else
{
Console.WriteLine("o dear");
}
}
}
}
In this example, the user enters a number.
Note that the int value data type does not require double quotes around it in the if statement as it is not a character.
Note also that the input has to be converted to an integer value using Convert.Int16
Exercise
Using if statements, write a program for the following :
A program is needed that asks the user five multiple choice questions. The user must be presented with a list of possible answers, A to D. If the correct answer is selected, the score is incremented. At the end of the 5 questions, the program should display the score.
More complex decision making in C#
The examples so far have used simple decisions between one item and another. More complex decisions allow you to do things such as checking if A or B has been choosen.
Program 3 using a more complex expression
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string theAnswer;
Console.WriteLine("Do you use C# ?");
theAnswer = Console.ReadLine();
if (theAnswer == "y" || answer = “Yâ€)
{
Console.WriteLine("Good");
}
else
{
Console.WriteLine("o dear");
}
}
}
}
The above example uses the OR statement which evaluates to true if y or Y were typed by the user.