Lecture 2 - Murray State...
Transcript of Lecture 2 - Murray State...
Lecture 2Computational Constructs
Variables & Expressions
Boolean Logic
Conditionals: if & switch
Branching & Looping
Data Types & Type Conversion
Structs, Arrays & Strings
Basic C# Syntax
C# is similar to C++ and Java
C# ignores whitespace characters
C# is a block-structured language (code blocks are enclosed in curly brackets)
// comment line
{
<code line 1>;
{
<code line 2>;
<code line 3>;
}
<code line 4>;
}
/*
comment
block
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// Output text to the screen.
Console.WriteLine("The first app in Beginning C# Programming!");
Console.ReadKey();
}
}
}
C# Console Application Structure
Variables
Variables are named memory blocks that hold data
The variable type determines how much memory is allocated to the variable
Variable must be declared before they can be used
In a C# declaration the variable type is first followed by the variable name
Simple Types
Variable Naming
The first character of a variable must be either a letter, an underscore character or the at symbol.
Subsequent characters may be letters, underscore, characters, or digits.
There are some words, reserved for use for the language, that may not be used a variable names.
For example, the following variable names are fine:
myBigVar
VAR1
_test
These are not, however:
99BottlesOfBeer
namespace
It’s-All-Over
C# is case-sensitive so myVariable, MyVariable, and MYVARIABLE are all different variable names.
Literal Values
String Literals
The Unicode Value column of the preceding table shows the hexadecimal values of the characters as they
are found in the Unicode character set. As well as the preceding, you can specify any Unicode character
using a Unicode escape sequence. These consist of the standard \ character followed by a u and a four-digit
hexadecimal value (for example, the four digits after the x in the table above).
http://www.unicode.org/charts/
Samples of Unicode
You can also specify strings verbatim. This means that all characters contained between two double quotation
marks are included in the string, including end-of-line characters and characters that would otherwise need
escaping. The only exception to this is the escape sequence for the double quotation mark character, which
must be specified to avoid ending the string. To do this, place the @ character before the string:
@"Verbatim string literal."
This string could just as easily be specified in the normal way, but the following requires this method:
@"A short list:
item 1
item 2"
Verbatim strings are particularly useful in filenames, as these use plenty of backslash characters. Using normal
strings, you’d have to use double backslashes all the way along the string:
"C:\\Temp\\MyDir\\MyFile.doc"
With verbatim string literals you can make this more readable. The following verbatim string is equivalent to
the preceding one:
@"C:\Temp\MyDir\MyFile.doc"
Verbatim Strings
C# contains a number of operators for declaring and initializing variables. By combining operators with
variables and literal values (together referred to as operands when used with operators), you can create
expressions, which are the basic building blocks of computation.
Expressions
Mathematical Operators
Binary and Unary Operators
Assignment Operators
When an expression is evaluated, each operator is processed in sequence, but this doesn’t necessarily mean
evaluating these operators from left to right. As a trivial example, consider the following:
var1 = var2 + var3;
Here, the + operator acts before the = operator. There are other situations where operator precedence isn’t
so obvious, as shown here:
var1 = var2 + var3 * var4;
In the preceding example, the * operator acts first, followed by the + operator, and finally the = operator.
This is standard mathematical order, and it provides the same result as you would expect from working out
the equivalent algebraic calculation on paper. Similarly, you can gain control over operator precedence by
using parentheses
Operator Precedence
Before moving on, it’s worthwhile to consider one more important subject — namespaces. These are the .NET
way of providing containers for application code, such that code and its contents may be uniquely identified.
Namespaces are also used as a means of categorizing items in the .NET Framework.Most of these items are
type definitions, such as the simple types in this chapter (System.Int32 and so on).
C# code, by default, is contained in the global namespace. This means that items contained in this code are
accessible from other code in the global namespace simply by referring to them by name. You can use the
namespace keyword, however, to explicitly define the namespace for a block of code enclosed in curly
brackets. Names in such a namespace must be qualified if they are used from code outside of this namespace.
A qualified name is one that contains all of its hierarchical information, which basically means that if you have
code in one namespace that needs to use a name defined in a different namespace, you must include a
reference to this namespace. Qualified names use period characters (.) between namespace levels, as shown
here:
namespace LevelOne
{
// code in LevelOne namespace
// name "NameOne" defined
}
// code in global namespace
This code defines one namespace, LevelOne, and a name in this namespace, NameOne. Code written inside
the LevelOne namespace can simply refer to this name using NameOne — no classification is necessary. Code
in the global namespace, however, must refer to this name using the classified name LevelOne.NameOne.
Namespaces
Boolean Logic
Boolean Assignment Operators
More Operator Precedence
Conditionals: The if Statement
The simplest use of an if statement is as follows, where <test> is evaluated (it must evaluate to a Boolean
value for the code to compile) and the line of code that follows the statement is executed if <test> evaluates
to true:
if (<test>)
<code executed if <test> is true>;
After this code is executed, or if it isn’t executed due to <test> evaluating to false, program execution
resumes at the next line of code.
You can also specify additional code using the else statement in combination with an if statement. This
statement is executed if <test> evaluates to false:
if (<test>)
<code executed if <test> is true>;
else
<code executed if <test> is false>;
The switch statement is similar to the if statement in that it executes code conditionally based on the value
of a test. However, switch enables you to test for multiple values of a test variable in one go, rather than just
a single condition. This test is limited to discrete values, rather than clauses such as ‘‘greater than X,’’ so its
use is slightly different; but it can be a powerful technique.
switch (myInteger)
{
case 1:
<code to execute if myInteger == 1>
break;
case -1:
<code to execute if myInteger == -1>
break;
default:
<code to execute if myInteger != comparisons>
break;
}
Conditionals: The switch Statement
Looping refers to the repeated execution of statements. This technique comes in very handy because it
means that you can repeat operations as many times as you want (thousands, even millions, of times
without having to write the same code each time.
do loops - The code you have marked out for looping is executed, a Boolean test is performed, and the
code executes again if this test evaluates to true, and so on.When the test evaluates to false, the loop
exits.
while loops - The Boolean test in a while loop takes place at the start of the loop cycle, not at the end. If
the test evaluates to false, then the loop cycle is never executed. Instead, program execution jumps
straight to the code following the loop.
for loops - This type of loop executes a set number of times and maintains its own counter.
foreach loops - A foreach loop enables you to address each element in an array using this simple
syntax:
foreach (<baseType> <name> in <array>)
{
// can use <name> for each element
}
This loop will cycle through each element, placing it in the variable <name> in turn, without danger of
accessing illegal elements.
Looping
Type Conversion
Type conversion takes two forms:
•Implicit conversion: Conversion from type A to type B is possible in all circumstances, and the
rules for performing the conversion are simple enough for you to trust in the compiler.
•Explicit conversion: Conversion from type A to type B is possible only in certain circumstances or
where the rules for conversion are complicated enough to merit additional processing of some
kind.
Implicit Conversions
Explicit Conversions
Enumerations
An enumeration is a user-defined list (with an underlying data type - int by default) that is
matched to the users list in the order in which they are defined in the enum declaration.
namespace Ch05Ex02
{
enum orientation : byte
{
north = 1,
south = 2,
east = 3,
west = 4
}
class Program
{
static void Main(string[] args)
{
orientation myDirection = orientation.north;
Console.WriteLine("myDirection = {0}", myDirection);
Console.ReadKey();
}
}
}
The struct (short for structure) is just that. That is, structs are data structures are composed of several
pieces of data, possibly of different types. They enable you to define your own types of variables based
on this structure.
Structs
namespace Ch05Ex03
{
enum orientation: byte
{
north = 1, south = 2, east = 3, west = 4
}
struct route
{
public orientation direction;
public double distance;
}
class Program
{
static void Main(string[] args)
{
route myRoute;
int myDirection = -1;
double myDistance;
Console.WriteLine("1) North\n2) South\n3) East\n4) West");
do
{
Console.WriteLine("Select a direction:");
myDirection = Convert.ToInt32(Console.ReadLine());
}
while ((myDirection < 1) || (myDirection > 4));
Console.WriteLine("Input a distance:");
myDistance = Convert.ToDouble(Console.ReadLine());
myRoute.direction = (orientation)myDirection;
myRoute.distance = myDistance;
Console.WriteLine("myRoute specifies a direction of {0} and a " +
"distance of {1}", myRoute.direction, myRoute.distance);
Console.ReadKey();
}
}
}
Arrays
Arrays are indexed lists of variables stored in a single array type variable. The index is simply an integer,
starting with 0 for the first entry, using 1 for the second, and so on. Array entries are often referred to as
elements.
Arrays are declared in the following way:
<baseType>[] <name>;
Here, <baseType> may be any variable type, including the enumeration and struct types you’ve seen in
this chapter. Arrays must be initialized before you have access to them. You can’t just access or assign
values to the array elements like this:
int[] myIntArray;
myIntArray[10] = 5;
Arrays can be initialized in two ways. You can either specify the complete contents of the array in a literal
form or specify the size of the array and use the new keyword to initialize all array elements. Specifying
an array using literal values simply involves providing a comma-separated list of element values enclosed
in curly braces:
int[] myIntArray = { 5, 9, 10, 2, 99 };
The other method requires the following syntax:
int[] myIntArray = new int[5];
A multidimensional array is simply one that uses multiple indices to access its elements. For example,
suppose you want to plot the height of a hill against the position measured. You might specify a position
using two coordinates, x and y. You want to use these two coordinates as indices, such that an array called
hillHeight would store the height at each pair of coordinates. This involves using multidimensional arrays. A
two-dimensional array such as this is declared as follows:
double[,] hillHeight = new double[3,4];
Alternatively, you can use literal values for initial assignment. Here, you use nested blocks of curly braces,
separated by commas:
double[,] hillHeight = {{1,2,3,4},{2,3,4,5},{3,4,5,6}};
This array has the same dimensions as the previous one — that is, three rows and four columns. By
providing literal values, these dimensions are defined implicitly.
Multidimensional Arrays
String Manipulation
A string type variable can be treated as a read-only array of char variables. This means that you can access
individual characters using syntax like the following:
string myString = "A string";
char myChar = myString[1];
However, you can’t assign individual characters this way. To get a char array that you can write to, you can use
the following code. This uses the ToCharArray() command of the array variable:
string myString = "A string";
char[] myChars = myString.ToCharArray();
As with arrays, you can also get the number of elements using myString.Length. This gives you the number of
characters in the string:
string myString = Console.ReadLine();
Console.WriteLine("You typed {0} characters.", myString.Length);
Other basic string manipulation techniques use commands with a format similar to this <string>.ToCharArray()
command. Two simple, but useful, ones are <string>.ToLower() and <string>.ToUpper(). These enable strings to
be converted into lowercase and uppercase, respectively.