Presentation is loading. Please wait.

Presentation is loading. Please wait.

COP 2360 – C# Programming Exam 1 Review. Programming Language Basics A way to store and retrieve information to and from memory. A way to communicate.

Similar presentations


Presentation on theme: "COP 2360 – C# Programming Exam 1 Review. Programming Language Basics A way to store and retrieve information to and from memory. A way to communicate."— Presentation transcript:

1 COP 2360 – C# Programming Exam 1 Review

2 Programming Language Basics A way to store and retrieve information to and from memory. A way to communicate with the "outside world" A way to compute basic mathematics and store results A way to compare information and take action based on the comparison A way to iterate a process multiple times A way to reuse components.

3 A way to store and retrieve information to and from memory. Variables – A variable is a memory location whose contents may change during program execution. – C# has two different "Types" of Variables Value Types – The variable represent a place in memory that actually holds the value of the variable. Reference Types – The variable represents a place in memory that holds the ADDRESS of the value of the variable.

4 Value Variable Types The variable location IS the value Integral Data Type – int = Integer = 4 Bytes (+- 2 billion) – short = Integer = 2 Bytes (+- 32K) – long = Integer = 8 Bytes (64 bits) 16 digit precision – char = 16 bits (2 Bytes - Unicode) - Discuss – bool = Boolean (True/False) = (Not sure of length) Floating Point Data Types – Double precision (double) gives you 52 significant bits (15 digits), 11 bits of exponent, and 1 sign bit. (Default for literals) – Single precision (float) gives you 23 significant bits (7 digits), 8 bits of exponent, and 1 sign bit. (Literals need to have "F" appended) – WARNING WILL ROBINSON – Storing information as a Float will store an approximation of the number, not potentially the correct number..

5 Value Variable Types The variable location IS the value Decimal Types – New – Up to 28 digits of precision (128 bits used to represent the number) – Decimal place can be included But unlike Float or Decimal, there is no conversion The Precision and the Decimal place go together For literals, put an “M” at the end to state that the number is a decimal Boolean – Value of either true or false – You must use true or false, not 0, 1 or -1 Char – Single Unicode Character (2 Bytes) Unicode is the Universal Character Codes – up to 65,536 different values In Assignment, Single Quotes are used – Char bChar = ‘B’;

6 Variable/Identifier Names Numbers, Letters (upper or lower case) and the underscore (_) Must begin with either a letter or an underscore. Cannot be a reserved word Should be indicative of what the variable is storing Capitalization Counts!!! – Variable1, variable1 and VARIABLE1 are three different variables!!! Try not to use run on variable names – costofliving – use cost_of_living or costOfLiving – currentinterestrate – use current_interest_rate or currentInterestRate

7 String Type A string is a sequence of zero or more characters. Strings in C# are enclosed in double quotes – char on the other hand are enclosed in single quotes The character number in a string starts with 0 and goes to the length of the string -1. Spaces count!!

8 Mixed Expressions What if you don’t like the rules casting is a feature that can change the type of data so that the calculation performs as you want, not as the computer wants. (int) (expression) calculates the expression, then drops any digits to the right of the decimal (double) (expression) calculates the expression, then stores whatever the answer is in a floating point number

9 Named Constants Remember, numeric and character literal constants (3, “G”, “Stuff”, 3.1413) are usually not a good idea. – They hide what is being done – They are hard to understand by others – Whenever possible, use named constants where the name means what the constant is/does

10 A Word About a Variable’s Scope A variable “lives” in the curly braces in which it was created and “dies” when the flow of control goes beyond those curly braces. Once a variable is defined at a parent level, C# will not allow a child block to have a variable declared with the same name

11 Scope of Variables Global/Class – Variables defined before any method definitions are made – Should be used VERY SPARINGLY – Can be accessed by any method at any level within a class. Local/Method – Variables defined within a method (but not inside an if, while, do, for or any other type of block.) – Can only be accessed by that method. Another method cannot “see” the variables in the first method. – Once the method returns, all local variables are destroyed. – Parameters create local variables – Local Variables can hide Global Variables, but the Global Variables can be accessed by prefacing them with :: Block – Variables defined within an if, while, do, for or any other type of block. – they exist only for the life of the block, and are destroyed when the block is completed. – C# will not let Block Variables hide Local Variables

12 Bradley’s Variable Name Rules All local variables (except simple loop variables like i or n) will start with a prefix letter followed by a proper cased variable name or an all cap constant name. – n = integerf = floatd = decimal – c = characterb = boolean – s = string nCounterbContinuesLastName cLetterGradefVALUE_OF_PI All global variables and constants will preface the above with the letter “g” followed by the variable name. gnLineCountergsAUTHORS_NAME All parameter variables should preface the above with the letter “p”. pnLengthpsGrade Block variables should only be used for intermediate results that are not needed to be retained, or for looping. They should not include any prefix for variable type. A lot of computer shops frown on Bradley’s rules, and others have implemented more stringent rules.

13 A way to communicate with the "outside world" Console.ReadLine() – Reads a String from the console and puts it into a String variable. – Once in the variable, parsing functions can be applied to cast the string as something else. String sInput = Console.ReadLine(); int nNumber = int.Parse(sInput); Also – Console.ReadKey() // reads one character – Console.Read() // Returns one character in it’s numeric equivalent

14 A way to communicate with the "outside world" Console.WriteLine(Expression) – Outputs the value of Expression to Console Console.WriteLine(“Format Codes {0} {1}”,Expression1, Expression 2) – Outputs the value of Expression1 and Expression 2 based on formatting specifics and text

15 Write and WriteLine Methods Simple format for a single variable: – Console.WriteLine (Variable Name) Also – Console.WriteLine (Format String, Variable List) – The two different formats means that the WriteLine method is Overloaded!! Write and WriteLine do the same thing – The only difference is that the WriteLine method includes a CRLF (Carriage Return/Line Feed) at the end of the variables. Remember, the Format String is any text (or other string variables) you want to print out along with format codes – {#,W:F} – # = variable number, W = width (optional) F = Format

16 A way to compute basic mathematics and store results Assignment Statements – Variable = Expression With assignment statements, the expression on the right side of the equal signs is completely computed, and the result is then stored in the variable on the left hand side. The equal sign does NOT mean that the two sides are equal. It is telling the compiler to do the computation, take the final value and place it in the variable. – number = number + 1

17 A way to compute basic mathematics and store results There are two main variable types that we have used so far – Integral – Exact representation of a number of a single character – Float/Double – Approximate representation of a number using an exponent and a mantissa? If Anything on the right side of a assignment statement includes a float, the result will be a float. Only if ALL of the variables on the right side are integral will the result be integral. Even with that said, pieces of the expression may be one or the other depending upon variable types BUT – regardless of what happens on the right side of an assignment statement, the final variable type is dependant on the variable type on the left of the assignment statement: – Int stuff; – Stuff = 3.0 * 4.3 * 2.0 / 1.1 Stuff = 23.45455 which is truncated to 23 C# MAY require you to cast an int to a double to show that you understand you may be loosing precision.

18 A way to compare information and take action based on the comparison A "logical Boolean expression" is a C# statement that has a value of either true or false Boolean Expressions compare two or more variables/objects and determine the relationship between the variable. Comparisons are based on relational operators: – == equals!=not equal – < less than<=less than or equal – > greater than>=greater than or equal Notice that "equal to" is TWO equal signs – a = b is as assignment statement. The value of b is stored in address b. – a == b is a conditional statement. If a is the same as b, the statement evaluates to true otherwise false

19 Logical Boolean Expressions Simple Data Types - Integers Numbers are pretty straight forward – 5 < 7 ? – 6 != 3+3 ? – 2.5 > 5.8 ? – 5.9 <= 7.5 +2 ? Notice a Boolean Expression can have other expressions (arithmetic for example) embedded within the expression. We’ll talk about float numbers in a little bit. You have to be careful!!

20 Logical Boolean Expressions Strings Strings are compared character by character using the Unicode characters The only direct operator available though is "==“ and “!=“. As soon as there is a difference between the two strings, that character is going to determine the logical relationship between the two strings. – "Bee" == "Before" ?? The determination is made on the third character. "e" Not = "f"

21 Logical Boolean Operators Logical Expressions can be connected together with Logical Operators. – ! is not – reverse the Boolean value of an expression (unary operator) – && is and – The entire expression is true if and only if both sides of the && are true (a > b) && (a > c) implies than – Both b and c are less than a What does (a >b) && (a==b) imply? – || is or – The entire expression is true if the left side is true or the right side is true (a > b) || (a > c) implies that – a is greater than b or a is greater than c or a is greater than both of them

22 New Order of Precedence with Logical Operators 1. Unary operators (- + ! ++ --) 2. Multiplication/Division (/ * %) 3. Addition/Subtraction (+ -) 4. Relational GT/LT( >=) 5. Relational Equals (== !=) 6. And (&&) 7. Or (||) 8. Assignment (=) What takes precedence over all of these? (Parenthesis) If you have operators at the same order, what is done first? (left to right) What happens with multiple "=". 1. This is a weird one. Multiple = are computed RIGHT TO LEFT!!

23 Basic “if” statement The syntax for "if" statements in C# is: – if (logical Boolean expression) – { C# commands – } – Else – { More C# Commands – { A "logical Boolean expression" is a C# statement that has a value of either true or false.

24 What About Floats Checking for Tolerance As we have seen, floating point numbers may not always actually "be" what they "seem" Unlike integers, one may want to consider a tolerance for when one can say that two floats are the "same". – For example, if we are dealing with money, maybe we can say that two floats (X AND Y) are the same if their difference is less than.0001 if (fabs(x - y) < 0.0001)

25 Basic switch statement switch (expression) { case value1; statements break; case value 2; statements break; case value n; statements break; default; statements break; } Although multiple statements can be placed after each case statement without requiring curly braces, each case statement must end with the break command OR the next command will also be executed until a break is hit.

26 Typical switch command switch (nGradePoints/10) { case 0: case 1: case 2: case 3: case 4: case 5: Console.WriteLine ("You Failed"); break; case 6: Console.WriteLine ("gotta D"); break; case 7: Console.WriteLine ("gotta C"); break; case 8: Console.WriteLine("gotta B"); break; case 9: case 10: Console.WriteLine("gotta A"); break; default: Console.WriteLine ("bad grade"); break; }

27 A way to iterate a process multiple times Control Structures - Repetition – Two Main Methods “for” loop – iterate based on modifying a variable so that the loop is performed a certain number of times “while” loop – iterate based on the value of an expression or variable

28 Let’s look at the “for” loop for (initial statement; loop condition; update statement) { statements to execute } This is another instance when a single statement can be specified without the curly braces, but (as you already know) ALWAYS USE THE CURLY BRACES!!

29 Some comments on “for” if the initial condition is false, then for statement is skipped. C# allows the use of float variables for the for loop variables, but it is recommend that these not be used? Why? If the loop condition of a “for” statement is left blank, then it is assumed to be true. (As a matter of fact, all three pieces of a “for” can be left blank…What do you think this does?) for (;;) { Console.WriteLine(“Help Me!!!”); } The three pieces of the “for” do not necessarily have to reference the same variable: – for (i=1;j<10;k++) is valid, but it assumes that something in the body of the “for” handles the updating of “j” so that the loop will stop;

30 While Loops Come in two different flavors: – Pre-test loops – a condition is checked BEFORE any statements are executed. – Post-test loops – a condition is checked AFTER the statements are executed.

31 Let’s Look at the Pre-Test while while (conditional expression) { statement1; statement2; statementn; } many times while loops make use of a “loop control variable” – The variable would be initialized before starting the while loop. – It would be referenced in the conditional expression. – It would then be modified in the body of the while.

32 The post-test while loop do { statement1; statement2; statement3; } while (conditional expression) Using this format of the while, the condition is tested AFTER the commands are executed. This means that the statements are executed at least one time regardless of the conditional.

33 break and continue sometimes you may want to “get out of a loop” because of an error, or some other condition is met. break – completely stops the current loop – Often times done to report an error. – Many times used when doing a look-up. Once the value is found, stop looking. More on this when we get into arrays. – Control starts after the end of the current block of code (“}”) continue – returns control back to the beginning of the loop – while would NOT have their condition updated (unless it was done before the continue) – for would have the condition updated since it is part of the for syntax

34 A way to reuse components. Methods A method is a group of code that (may or may not) accept parameters and (may or may not) produce a result We have been writing a Method static void Main(string[] args)method which – Accepts a parameter named args that is a string array – Returns nothing – Is a Static Method – Is the starting place for our programs Another name for “Method” could be: – Function (what a method is called in C and C++) – SubProgram (what a method with nothing to return is called in VB.Net)

35 The Concept of Methods Methods are usually blocks of code that are accessed multiple times in a program. – So they allow for code to be reused – They accept parameters so that their results are flexible. Methods with the same name can have different sets of parameters and can return different types. This feature is called overloading. Methods are members of Classes. Methods that return a value can be used as a variable on the right side of an expression (like a constant)

36 Classes Classes are structures that combine data and processing into one component and are the basis of object oriented programming All data types in C# are really instances of classes. – Strings are a good example of the abilities of classes with all of the methods available to anything that is typed a String Classes are composed of Variables (Nouns), Properties (Adjectives) and Methods (functions and subroutines/Verbs.)


Download ppt "COP 2360 – C# Programming Exam 1 Review. Programming Language Basics A way to store and retrieve information to and from memory. A way to communicate."

Similar presentations


Ads by Google