cop 2360 – c# programming chapter 2 – sept 2, 2015

51
COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

Upload: howard-powers

Post on 02-Jan-2016

222 views

Category:

Documents


3 download

TRANSCRIPT

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

COP 2360 – C# Programming

Chapter 2 – Sept 2, 2015

Page 2: 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

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.

Page 3: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

Computer System Basics

Computers are comprised of:– Central Processing Unit(s)– Main Memory– Secondary Storage– Peripheral Devices

Page 4: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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”)

Page 5: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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

Page 6: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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 1000h1000 memcpy public1000 78 loop mov a,b ;Test BC,1001 B1 ora c ;If BC = 0,1002 C8 rz ;Return1003 1A ldax d ;Load A from (DE)1004 77 mov m,a ;Store A into (HL)1005 13 inx d ;Increment DE1006 23 inx h ;Increment HL1007 0B dcx b ;Decrement BC1008 C3 00 10 jmp loop ;Repeat the loop100B end

Page 7: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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.

Page 8: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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

Page 9: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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.

Page 10: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

CPU and Main MemoryA Pretty Picture

Page 11: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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.

Page 12: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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

Page 13: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

OK – Enough about hardware

Let’s get into C# Programming

Page 14: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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

Page 15: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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(); } }}

Page 16: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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

Page 17: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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.

Page 18: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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.

Page 19: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

Variables - A Pretty Picture

Page 20: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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??

Page 21: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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’;

Page 22: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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)

Page 23: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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.

Page 24: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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

Page 25: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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!!)

Page 26: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

Variable/Identifier Names

So, what does this program do?:– const double a = 2.54;– double y = 12;– double x;– x = y * a;

Page 27: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

Variable/Identifier Names

What about now?– const double CENTIMETERS_PER_INCH = 2.54;– double centimeters = 12;– double inches;– inches = centimeters * CENTIMETERS_PER_INCH;

Page 28: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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

Page 29: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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

Page 30: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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

Page 31: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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

Page 32: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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

Page 33: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

Casting a Char

(int)‘A’ is 65 (the ASCII equivalent of the symbol ‘A’

(char) 66 is ‘B’

Page 34: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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

Page 35: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

String Type Concatenation

The "+" sign is used to combine strings into longer strings– sFirstName = "Louis";– sLastName = "Bradley";– sFullName = sFirstName + " " + sLastName

Page 36: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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);

Page 37: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

Assignment Statements

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

Page 38: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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.

Page 39: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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

Page 40: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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);

Page 41: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

Console Write Statement Examples

Page 42: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

Formatting Output

Page 43: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

Formatting Output (continued)

Page 44: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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.

Page 45: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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”;

Page 46: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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);

Page 47: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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!!)

Page 48: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

Some More Weird Stuff I Don’t LikeCompound Assignment Statements

C# allows one to replace:x = x + y;

withx += 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

Page 49: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

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

Page 50: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

Let’s Write the “Paint Calculator” Together

Page 51: COP 2360 – C# Programming Chapter 2 – Sept 2, 2015

Assignment 1!!