Variables and Expression COSC Fall 2014 Bridget Blodgett
Basic C# Syntax C# compliers ignore whitespace in your code – Make good use of this to improve the readability of your code for yourself and others The code is made up of statements which are terminated with a semi-colon – If someone doesn’t compile double check your semi-colons! All statements are part of a block of code marked by curly brackets
Comments Besides using whitespace to make your code more understandable, comments can aid in comprehension { ; /* The above is an example of a statement */ /* The above is an example of a comment */ } The /* can be used for comments which span multiple lines. – C# will assume the comment keeps going until it sees the close comment mark */ If your comment is only one line you can also use //
Comments If you use /// in your code the C# compiler will read them just like a normal comment (i.e. ignore them when it compiles the code) – However, you can configure visual studio to extract this type of comment and make a documentation file It is also important to note that C# is case sensitive – So you need to make sure that you are using the correct case when calling functions or variables
Variables Variables are concerned with data storage. – The type of variable tells you what form of information it holds. To use a variable you must officially declare it and assign it a name and type – ; Failing to declare a variable that you are trying to use will cause your code to not compile.
Simple Types There are several simple types that are usually numbers and do not have any children or attributes (we’ll get to this later) – There are three ways of storing various integers: byte short int long – Floating-point values can be stored as: float double decimal
Simple Types There are also three non-numeric simple types available: TypeAlias ForAllowed Values charSystem.CharSingle Unicode character, stored as an integer between 0 and boolSystem.BooleanBoolean value, true or false stringSystem.StringA sequence of characters
static void Main(string[] args) { int myInteger; string myString; myInteger = 17; myString = “\”myInteger\” is”; Console.WriteLine(“{0} {1}.”. myString, myInteger); Console.ReadKey(); }
Variable Assignment Within this example you are assigning literal values to your variables. The = is the assignment operator You must also avoid certain words and characters. – The escape sequence ( \” ) is needed in this example to include the quotation marks around the string’s value – If you need to add a line break \n will do so in a string
Variable Naming When assigning names to variables it is important to select unique and relevant names. – If you have several different pieces of code all with a variable named myInteger it will quickly become confusing and useless to you Variable naming rules: – The first character must be a letter, an underscore ( _ ), or the at symbol ) – Subsequent characters may be letters, underscore characters, or numbers
Naming Examples myBigVar VAR1 _test 99BottlesofBeer namespace It’s-All-Over myVariable MyVariable MYVARIABLE
Additional Variable Info You can declare multiple variables of a type in one line – int highScore, lowScore; You can also declare and initialize a variable in the same line – int age = 25; Or declare and initialize multiple variables – int highScore = 25, lowScore = 0;
Expressions Expressions are the basic building blocks of computation – To form an expression combine an initialized variable with a literal value and operator Three categories: – Unary – Binary – Ternary Cover basic mathematical actions – +, -, *, /, %, signs
Expressions Only the + operator may be used with a string variable and bool will not allow you to use any You can also increment and decrement values with operators OperatorExample ExpressionResult ++var1 = ++var2;var1 is assigned the value of var var2 is incremented by 1. --var1 = --var2;Var1 is assigned the value of var2 – 1. var2 is decremented by 1. ++var1 = var2++;Var1 is assigned the value of var2. var2 is incremented by 1. --var1 = var2--;Var1 is assigned the value of var2. var2 is decremented by 1.
Assignment Operators Assignment operators result in the variable on the left side of the = being assigned the value of the operands and operators on the right – e.g. =, +=, -=, *=, /=, %=
Operator Precedence Operators follow a standard order of precedence – ++ (prefix), --, (), signs – *, /, % – +, - – =, *=, /=, %=, +=, -= – ++, -- (suffix)
More About Variables COSC Fall 2011 Bridget Blodgett
Type Conversion When dealing with simple types we’ve only used variables that contain the correct form of data for that type However, often you need to convert data between different types. – Implicit Conversion – Explicit Conversion
Explicit Conversion When you need to formally ask or tell the compiler to do a conversion it is an explicit conversion – The compiler will fail with an error about type conversion if you try to implicitly convert a variable that requires an explicit conversion Casting a variable into the type you want often fulfills this requirement – eg. (byte)sourceVar
Overflow If you attempt to cast a variable which is too large for the type you have selected it will often still compile – However, information will be lost in the process – This is called overflow You can set overflow checking context for an expression to: checked or unchecked – checked((byte)sourceVar); – The default behavior of the compiler can be changed to always check
Using Convert Commands We have used Convert.ToDouble() and Convert.ToInt32() several times – These commands work for strings which contain numbers as their input – The number must also fit within the type you are converting to These convert commands are always overflow checked
Complex Variable Types Beyond the simple types there are three complex types within C# – Enumerations (enums) – Structs (structures) – arrays
Enumerations Accepts one of a finite set of defined values as input You must declare the type and the acceptable values enum { } Declare variables like normal – ; Assign them values in a slightly different manner – =. ;
Enumerations By default the values in an enumeration are stored as int s – Specify a different type during the declaration: – enum : … Each value is assigned a underlying type value automatically in order of definition starting at 0 You can use the assignment operator to override the default and assign custom values
Structs Structs are data structures composed of several pieces of data Allows programmers to define types of variables that follow this structure struct { ; } Call data members within the struct using the period. = ;
Arrays[] Arrays[] allow you to store multiple values within a single variable Arrays are indexed lists of variables stored in a single array type variable – You call an individual value by specifying their index in the array – friendNames[ ]; – The index is a int starting with 0 and counting up until the last value in the array is stored All the values saved in an array shared a base type
Arrays[] Any simply type may be made into an array by appending the [] to the end of the type declaration – int[] myIntArray; – myIntArray[10] = 5; – Int[] myIntArray = {5,9,10,2,99}; – Int[] myIntArray = new int[5]; – Int[] myIntArray = new int[arraySize]; The variable which defines the array size must be declared a constant (include const in its declaration)
Loops and Looping Looping refers to the repeated execution of statements – It reduces the amount of code that needs to be written to repeat operations Also allows for specific conditions which will end the loop behavior
do Loops The code within the loop is executed until the bool test evaluates to false do { ; } while ( ); This is when the increment/decrement operators are the most useful ( ++ / -- ) Console.WriteLine(“In {0} year{1} you’ll have a balance of {2}.”, totalYears, totalYears == 1 ? “”: “s”, balance); Required!
if and do Wrapping a do loop in an if statement ensures that the do loop will only run if certain conditions are met – Otherwise the loop will always execute once – Not the most efficient way to perform this job
while Loops The boolean test is performed at the start of a while loop not at the end If the test evaluates to false the loop is not executed – The program goes onto the next piece of code after the loop while ( ) { ; } What happens when we try example 5 without validation?
for Loops Unlike other loops for loops execute a certain number of times before automatically exiting – The loop maintains its own counter For ( ; ; ) { ; } Specifying all the details of the loop in a single location make it easier to read/understand – This includes initializing the counter variable – Incrementing occurs after the code is executed!
foreach Loops Foreach loop enables each element in an array to be accessed foreach( in ) { //use for each element }
Interrupting Loops Knock, Knock…Who’s there?... Interrupting Cow…. Interrupting Cow- Moo! break – loop ends immediately continue – current loop ends and continues with next loop goto – jumps out of a loop to a specific position return – exits loop AND containing function
Infinite Loops Good for locking up computers! Occurs occasionally through errors that are legitimate Must force the program to quit manually (why break statements are good!) int i = 1; while (i<= 10) { If ((I %2) == 0) Continue; Console.WriteLine(“{0}, i++); }
Why Use Functions? Functions are pieces of code which can be used and reused many times Use instead of copying and pasting the same piece of code into your program each time it is needed Reduce the size of the program Increase ease of making changes Can perform the same operation on many different inputs (output)Can be used and manipulated like a variable
Defining a Function class Program { static void Write() { Console.WriteLine(“Text output from function.”); } static void Main(string[] args) { Write(); Console.ReadKey(); }
Function Definition Keywords: static – accessed from the class that defines them void – function does not return a value The Main() Function The basic function that is needed in every C# program for it to compile and execute Often calls the other functions, cases, or files to be used in the program
Returning Values A function which can be called is useful but doesn't add much to a program Sending and receiving variables or values increases the functionality Functions which return values may be used in expressions as if they were the value that they return string myString;double myVal; myString = GetString();double multiplier = 5.3; MyVal = GetVal()*multiplier;
Functions and Returns To return a value: Specify the type of value in the declaration (omit void) Use the return keyword to end the Function and transfer the value and control back to the calling code static double GetVal() { If (checkVal < 5) //stuff happens return 4.7; return 3.2; }
Taking Input When a Function accepts parameters (input) specify: The list of accepted parameters and their types Matching list of parameters in each function call static double Product(double param1, double param2) { return param1*param2; }
Variable Scope Scope is limited to the block in which they are defined and any sub-blocks Local variables are limited in scope to one function Global variables cover multiple functions These are defined outside of a function The static (or const) keyword is required The variable must be called with the. when there are multiple variables with the same name