1 / 51

COP 2360 – C# Programming

COP 2360 – C# Programming. Chapter 2 – Sept 2, 2015. Some Announcements. Don’t forget all of the Powerpoints can be found at: www.wodwhere.com/COP2360

dharrod
Download Presentation

COP 2360 – C# Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

  2. Some Announcements • Don’t forget all of the Powerpoints can be found at: • www.wodwhere.com/COP2360 • November 11 is a holiday (Veteran’s Day – I thought it was on Monday). So, the exam I had scheduled for November 11 will be rescheduled for November 4.

  3. Computer System Basics • Computers are comprised of: • Central Processing Unit(s) • Main Memory • Secondary Storage • Peripheral Devices

  4. Central Processing Unit • Is where all the “magic” happens • But it isn’t really a lot of magic • It’s a little magic that happens very quickly • Basically, the only “things” that a CPU can actually do are: • Move data from memory to a register, from a register to memory or from a register to a register • Simple arithmetic • Logical comparisons (which is really done based on arithmetic) • Basic looping (which is really just setting the program counter to a value, so is really included in “Things 1 and 2”)

  5. Central Processing Unit • The basis from many CPUs today is my old friend the 8080 processor. • In the “day” we had seven “free” 8 bit registers: • A (the accumulator) • B and C (could act individually or as one 16 bit register) • D and E (also could act as two or one) • H and L (read above!! – Plus certain instructions allowed these two to be used for a memory address called M) • We also have an 8 bit register called the “Flag” register that contains specific bits for overflow, zero indicators and other stuff. • We also had a 16 bit Program Counter (that kept track of what instruction we were on) and a 16 bit stack register, used to figure out where to store stuff into memory.)

  6. Central Processing UnitExample Assembly/Machine Language ; memcpy -- ; Copy a block of memory from one location to another. ; ; Entry registers ; BC - Number of bytes to copy ; DE - Address of source data block ; HL - Address of target data block ; ; Return registers ; BC - Zero 1000 org 1000h ;Origin at 1000h 1000 memcpy public 1000 78 loop mov a,b ;Test BC, 1001 B1 ora c ;If BC = 0, 1002 C8 rz ;Return 1003 1A ldax d ;Load A from (DE) 1004 77 mov m,a ;Store A into (HL) 1005 13 inx d ;Increment DE 1006 23 inx h ;Increment HL 1007 0B dcx b ;Decrement BC 1008 C3 00 10 jmp loop ;Repeat the loop 100B end

  7. Central Processing Unit • Today, there are a lot more instructions and registers • The register size has been increased from 8 to 32 or 64 • The CPU had been built to be able to combine simple math and logic into more complex instructions • by physically adding the pathways and gates to implement a more complicated instruction • to have instructions that are made up of micro-instructions so that a single machine language instruction is really many lower level instructions • But the basics are the same. The damn thing can only move stuff, and add stuff.

  8. Central Processing Unit • Oh, did I mention it can do that stuff 10,000,000,000 times per second!! • That’s 10 billion • So, it can’t do much, and it can’t do it to a lot, but it can do a little to a little very, very quickly!!

  9. Main Memory • Volatile electronic circuitry used to store programs and data for the CPU to access and process against. Stored as a series of 1’s and 0’s (or really, as whether or not a specific location in the memory is positively or negatively charged.) • In the old days, data was directly read and written to main memory by the CPU. • Although main memory is fast, accessing main memory is about 100 times slower than accessing the same information in a CPU register. (Which meant that although the computer might be able to do 10,000,000,000 instructions per second, if it had to do stuff with memory, it was reduced to only 100,000,000. • Let’s be honest, back then we weren’t at 10,000,000,000 ips • Cache (expensive very fast storage) was introduced to help with this. Basically, cache provides for almost register speed of access (if the data the CPU wants is in cache). • Bottom line though, the CPU accesses information from Main Memory, and the information must be in Main Memory for it to be able to process.

  10. CPU and Main MemoryA Pretty Picture

  11. Secondary Storage • Because currently Main Memory and Cache are volatile, they loose their data when the system is turned off. • Also, although we have very large main memories available now, they still do not come close to the total amount of data that we are used to manipulating. • Secondary Storage (disc drives and solid state disks) allow information from main memory to be permanently stored, but with a catch. • To access a single byte of information on a disk drive takes 10,000 ns (or basically is 10,000 times slower) than main memory access.

  12. Here’s a picture of Storage Media (If I had time, I would have put it to scale!!) But then either tapes would have been way to big, or you would not have been even to even see registers, cache or main memory

  13. OK – Enough about hardware • Let’s get into C# Programming

  14. C# Basic Structure usings (with semi-colon) namespace FirstProgram { class FirstProgram { static void Main(string[] args) { //Do some stuff } } } • C# programs are collections of classes. Classes are comprised of Attributes, Properties and Methods. One class is identified as the "Start Up Class" for the program • Main is a method that is usually always found in the start-up class for a program. • C# itself has really only simple math, assignment and logic statements actually included within the language. Just about everything else is handled by class libraries that contain additional methods. • Each command in a C# program must end with a semi-colon

  15. Let’s "Code" the ObligatoryHello World program // This is traditionally the first program written. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HelloWorldProgram { class HelloWorld { static void Main(string[] args) { Console.WriteLine("What Up Dude!"); int nStop = Console.Read(); } } }

  16. OK – That is out of the way Let’s Move on • All programming languages are really very similar • Once you understand how to design and program, it becomes more of a translation exercise. • But, you need to get the basics first….

  17. 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.

  18. 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.

  19. Variables - A Pretty Picture

  20. Value Variable TypesThe 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. (5.0 × 10^−324 to 1.7 × 10^308. Default for literals) • Single precision (float) gives you 23 significant bits (7 digits), 8 bits of exponent, and 1 sign bit. 1.5 × 10^−45 to 3.4 × 10^38 with a precision of 7 digits.(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. Let’s see this in action. Why do you think this is the case??

  21. Value Variable TypesThe 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 • Unless you really need to use very very big number or very very small numbers, suggest you use Decimal instead of Double of Float • But you’ll still be responsible for understanding the different!! • Boolean • Value of either true or false • You must use true or false, not 0, 1 or -1 • Char • Single Unicode Character (2 Bytes) • What is Unicode?? • In Assignment, Single Quotes are used • Char bChar = ‘B’;

  22. Reference Variable Types • Remember, the Value of the variable is the Address of the variable • Strings • During Assignment – Double Quotes are Use • String sMyName = "Louis Bradley" • Objects (Classes)

  23. A Word on Variable Types • In C# • All Variable Types are actually Classes • Which implies that when you define a variable you are really creating an Instance of an Class • We will go over this in excruciating detail next week.

  24. 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

  25. Constants • Constants are anything entered into a "C#" program that cannot be changed. • Numbers, strings • Named Constants are also unchangeable, but instead of just being a number or string, they have a name. • Why would we want to do this? • Traditionally Named Constants are written in all upper case. (Nothing is going to stop you from mixed case. It’s just good practice!!)

  26. Variable/Identifier Names • So, what does this program do?: • const double a = 2.54; • double y = 12; • double x; • x = y * a;

  27. Variable/Identifier Names • What about now? • const double CENTIMETERS_PER_INCH = 2.54; • double centimeters = 12; • double inches; • inches = centimeters * CENTIMETERS_PER_INCH;

  28. Comments and Structure • Comments add readability to the code and explain what you are trying to do • Single Line comments begin with two slashes //this is a line comment • Multi Line comments begin with /* and end with */ /*this is a multi-line comment and this is line two of the comment */ • Program Structure relates to the use of white space and indentation. • Anything within a Curly Brace should be indented • Concepts should be separated with a blank link • Comments should explain what you are doing • Variable names should be indicative of what they are used for.

  29. Reserved Words • C# has a list of "words" that cannot be used a variable or method/class names because they are part of the "C#" language • Ones that we know about now include: • int, float, double, char, const, void, string to name a few

  30. Arithmetic Operators • +, -, /, * and % (Modulas/Remainder) • Exponentiation is a handled through method calls • / with integral data will truncate the remainder • Standard order of precedence • Parenthesis then • Unary operators (-) then • * / % from left to right then • + - from left to right

  31. Mixed Expressions • If all operators are the same, then that data type will be returned. • If one operator is floating point and the other is integral, the integral is converted (cast) to floating point and the expression evaluated. • This is done one expression at a time in order or precedence. • Let’s do some for practice….

  32. Mixed ExpressionsWhat 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

  33. Casting a Char • (int)‘A’ is 65 (the ASCII equivalent of the symbol ‘A’ • (char) 66 is ‘B’

  34. 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!!

  35. String Type Concatenation • The "+" sign is used to combine strings into longer strings • sFirstName = "Louis"; • sLastName = "Bradley"; • sFullName = sFirstName + " " + sLastName

  36. Syntax vs. Semantics If the problem was to add five to two and then multiple the sum by 3, which is correct? int demo; demo = 3 * 5 + 2; demo = 3 * (5 + 2);

  37. Assignment Statements • The stuff on the right of the "=" is completely computed, and then put into the memory location on the left of the "=".

  38. Initialization • When a variable is declared, it is assigned a memory location. • That location probably already has stuff it in • A variable can be initialized in three different ways: • At the same time it is declared • int nNumber = 0; • In a separate assignment statement after it is declared • int nNumber; • nNumber = 0; • It can be read from the console or from a file.

  39. Displaying information to the Outside World Console.Write/Console.WriteLine • Simple format for a single variable: • Console.WriteLine (Variable Name) • Also • Console.WriteLine (Format String, Variable List) • Write and WriteLine do the same thing • WriteLine includes a CRLF (Carriage Return/Line Feed) at the end of the variables. • We can do that with an "escape sequence" as well and we’ll talk about that later!!

  40. Format String Syntax • The Format String is the first parameter to the Write/WriteLine Method • It is a single string. Each set of curly brackets represents the format of one variable (left most variable is {0}, then {1}, etc.) • The string can also have regular text embedded within in for context (similar to the C fprint command • const int INCHES_PER_FOOT = 12; • int nFeet = 3; • int nInches = nFeet * INCHES_PER_FOOT; • Console.WriteLine ("{0} Feet = {1} Inches",nFeet,nInches);

  41. Console Write Statement Examples

  42. Formatting Output

  43. Formatting Output (continued)

  44. Formatting Output (continued) • FYI. I never remember all of these codes. So, they won’t be on the test, but the concept will be!! • There is also the ability to make up your own. • There is also a “width” indicate that goes after the variable number • Console.WriteLine(“{0,5:F0}{1,-8:C}”,9,14 • The 9 will be right justified and five characters long, the 14 will be left justified, 8 characters long with dollar sign.

  45. Escape Sequences • \n = newline (same as endl) • \t = tab • \b = backspace • \r = return (no line feed) • \\ = just the backslash • \’ = print a single quote (otherwise thinks it is a char) • \" = print a double quote (otherwise thinks it is a string) • These are active on string assignment statements unless the literal is preceded by an @: • String sString1 = “This \t is \t a \t String”; • String sString2 = @” This \t is \t a \t String”;

  46. Reading information in from 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);

  47. Some Weird Stuff I Don’t LikeIncrement and Decrement Operators • Pre-increment/decrement – before you do anything else, add (or subtract) one from the variable • ++variable --variable • a = 5; • b = 2 + (++a); • After the statement is execute, b = 8 and a = 6 • Post-increment/decrement – after everything else is done, add (or subtract) one from the variable. • Variable++ variable-- • a = 5; • b = 2 + (a++); • After the statement is execute, b = 7 and a = 6 • I Do Not Like This (Sam I Am) (except for one place we will get into later!!)

  48. Some More Weird Stuff I Don’t LikeCompound Assignment Statements C# allows one to replace: x = x + y; with x += y; Can do similar crazy stuff with *, / and – Let’s Not Do This!! The book says it is concise. I think it is confusing!! And I’m passing out the grades

  49. VS2012 Tutorial • Creating Solutions • Projects in VS2012 = One Program • Adding Source Code • Compiling – Syntax Check • Running – Executable Location • Add another Project • Debugging Specific Project • Some Debugging Abilities

  50. Let’s Write the “Paint Calculator” Together

More Related