Top Banner
COP 3530 – C# Programming Chapter 5 – Jan 28, 2015
39

COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Dec 21, 2015

Download

Documents

Darcy Byrd
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

COP 3530 – C# Programming

Chapter 5 – Jan 28, 2015

Page 2: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Programming Language Basics

A way to store and retrieve information to and from memory.

A way to compute basic mathematics and store results

A way to communicate with the "outside world" 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 3: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Announcements

We’re Skipping Chapter 4 for a couple of weeks.

Page 4: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

What have we been doing

Simple "sequential" programs– The program starts at the beginning and goes to

the end.– No choices, branches, decisions, just top to

bottom

Page 5: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Control Structures - Selection

Tonight we introduce condition statements– Statements that evaluate an expression and then perform one

action if the expression is true and another if the expression is false

– The main way of doing this is with an "if" statement– Some Examples (in pseudo code)

If hours is not equal to 0 thenThe employee’s Hourly_Rate is Gross_Pass / hours

If hours less than or equal to 40 thenEmployee_Pay = Hourly_Rate * Hours

OtherwiseEmployee_Pay = Hourly_Rate * Hours

If weather is raining thenTake your umbrella with you

Page 6: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Logical Boolean Expressions Relational Operators

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

Page 7: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

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

Page 8: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Logical Boolean Expressions Simple Data Types - Char

Comparison of Char values is done based on the ASCII value of the character.– Notice that lower case letters are "greater than"

upper case letters!!– Also realize that the CHAR of a number is way

different than the number itself ‘8’ == 8 ?

– This will be allowed since (remember) we can do math with chars, but what is the result?

Page 9: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

ASCII Character Chart

Page 10: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Logical Boolean Expressions Strings

Strings are compared character by character using the ASCII codes we just looked at.

– OK. I’m lying. C# maintains strings Unicode characters, not ASCII characters, but the

The only direct operator available though is "==". 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"

– What About "BEFORE" and "Before"??

Page 11: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Logical Boolean Expressions Strings

To determine if one string is "Greater Than" another, they wrote a static function called String.Compare

– int nCompare = String.Compare("Be","Before")– String.Compare returns 0 if the two strings are the same, 1

if string1 is "bigger than" string 2, and -1 if string1 is "less than" string 2

– When one string is a substring of another starting with the left character, the longer substring is "greater than" the shorter one.

– This whole mess of "greater" or "less" probably doesn’t make sense when playing with Strings, but who knows.

Page 12: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

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

Page 13: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

New Order of Precedencewith 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?? If you have operators at the same order, what is done first? What happens with multiple "=".

1. This is a weird one. Multiple = are computed RIGHT TO LEFT!!

Page 14: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Logical Boolean Operators

Logical and Arithmetic Operators can appear in the same statement and are then evaluated based on the order of precedence

Unlike C and C++, Numbers and char variables cannot appear in statements with logical operators. This is due to the fact that C# assigns the value of a Boolean as either True or False while C and C++ use 1 and 0.

Page 15: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Let’s play some

bool found =true;int age = 20;double hours = 45.30;double overTime = 15.00;int count = 20;char ch = 'B‘;

!found

hours > 40.00

!age

!found && (age >= 18)

!(found && (age >= 18))

(ch == ‘C’) || (int == 0)

hours + overTime <= 75.00

(count >= 0) && (count <= 100)

('A' <= ch && ch <= 'Z')

(ch == ‘C’) && (int == 20)

Page 16: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Just to make sure we are clear

All this stuff we just went through can be used in assignment expressions.

We talked before that– If any float is involved in an expression, then it is going to a

float at the end.– The only way an integer is going to be returned is if ALL the

variables and constants are an integer. Now we have a new rule

– If a logical operator is used anywhere in the expression, and the statement does not cause a syntax error, the statement will return either true or false

Page 17: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

OK – Enough Preliminary Stuff

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.

Page 18: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Let’s Look At The Simple Case

int nScore = 85;char sGrade = ‘F’;if (nScore > 79)

sGrade = ‘B’;

Console.Writeline ("Your Grade Is: {0}",sGrade);In this case, the boolean expression is

nScore > 79once the comparison is done, either a value of true or false will be

returned. If the value is true, the next statement is executed. If it is false, the next statement will be skipped.

Page 19: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Now that you’ve seen the basics….Never do that again.

int nScore = 85;char sGrade = ‘F’;if (nScore > 79)

sGrade = ‘B’;

Console.Writeline ("Your Grade Is: {0}",sGrade); What’s wrong??? Bradley vs. the Book. The book is quite happy with this syntax,

Bradley is not. What follows an if statement can be one statement or a group

of statements. ALWAYS CODE YOUR ifs LIKE WHAT IS GOING TO

FOLLOW IS A GROUP OF STATEMENTS!!!

Page 20: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Instead, do this

int nScore = 85;

char sGrade = ‘F’;

if (nScore > 79)

{sGrade = ‘B’;

}

Console.Writeline ("Your Grade Is: {0}",sGrade); And why do I care. With the above statement I am only doing one

thing. Let’s say that I am asked to also add 1 to the number of Bs given. Let’s go back to the other way (without the curly braces)

Page 21: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

And this is why…..

int nScore = 85;

char sGrade = ‘F’;

int nNumber_of_Bs = 0;

if (nScore > 79) sGrade = ‘B’;

nNumber_of_Bs = nNumber_of_Bs + 1;

Console.Writeline ("Your Grade Is: {0}",sGrade);

So, what happened here??

Page 22: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

OK – No More ranting and raving

BUT YOU WILL ALWAYS USED THE CURLY BRACES EVEN IF IT IS ONLY ONE STATEMENT ON AN if!!!

As shown in the original example, an "if" can have an "else"

Let’s change our little program to pass/fail

Page 23: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

if…..else

int nScore = 85;char sGrade;int nNumber_of_Ps = 0;int nNumber_of_Fs = 0;if (nScore >= 70) {

sGrade = ‘P’;nNumber_of_Ps = nNumber_of_Ps + 1;

Console.Writeline ("WOOHOO…You Passed!!");

}else

{sGgrade = ‘F’;nNumber_of_Fs = nNumber_of_Fs + 1;Console.Writeline (" Oh Well – You FAILED!!");}

Page 24: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

if..else vs. if..else if..else

if (nBalance > 50000.00) {nInterestRate = 0.07; }

else if (nBalance >= 25000.00)

{nInterestRate = 0.05; }else

if (nBalance >= 1000.00) {nInterestRate = 0.03;} else {nInterestRate = 0.00; }

if (nBalance > 50000.00)

{nInterestRate = 0.07; }

else if (nBalance >= 25000.00)

{nInterestRate = 0.05; }

else if (nBalance >= 1000.00)

{nInterestRate = 0.03;}

else

{nInterestRate = 0.00; }

Both series of statements do exactly the same thing, but the one on the right is easier to read and understand with less indentation.

Page 25: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

A Dangling Else

const int nVERY_RICH = 1000000;const int nKINDA_RICH = 100000;int nSalary;Console.WriteLine( "Enter Your Salary: ");String sSalary = Console.Readline();nSalary = int.Parse(sSalary);if (nSalary > nKINDA_RICH)

if (nSalary > VERY_RICH){

Console.WriteLine ("I hear you\'re very rich");}

else {

Console.WriteLine ("I hear you\'re poor");}

What happens when we run this. What is wrong with the semantics?

Page 26: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Another issue of semantics.

const int nVERY_RICH = 1000000;const int nKINDA_RICH = 100000;int nSalary;Console.WriteLine( "Enter Your Salary: ");String sSalary = Console.Readline();nSalary = int.Parse(sSalary);if (nSsalary > KINDA_RICH)

{ Console.WriteLine ("I hear you\’re kinda rich");}

else if (salary > VERY_RICH){Console.WriteLine ("I hear you\'re very rich");

}else {

Console.WriteLine ("I hear you\'re poor");}

What’s wrong with the above??

Page 27: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

What About FloatsChecking for Tolerance

As we have seen, floating point numbers may not be 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)

Page 28: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Don’t Think You Can Do This

One may be tempted to write an if statement like this:if (0 <= num <= 10){

Console.WriteLine ("{0} is within range of 0 to 10", num);}else{

Console.WriteLine ("{0} is NOT within range of 0 to 10", num);

}

Page 29: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

One More Time = does not equal ==

Just to make sure you get this– = is used for assignment– == is used for comparison

You will screw this up at least 10 times before getting it right!!

Page 30: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Switch Statement(Another way to do if…else if)

Allows one to assign an action to separate values of variable

Includes a default case used when none of the other cases are appropriate.

Page 31: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Basic switch statement

switch (expression){case value1;

statementscase value 2;

statementscase value n;

statementsdefault;

statements}

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.

Page 32: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

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;

}

Page 33: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

The switch expression can be

an integer a char a boolean

– but check for values of true or false in the case statements

a String an expression that resolves to one of these

Page 34: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

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

Let’s play with this some.

Page 35: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

File I/O (From Chapter 13)

We’ve played around with reading from and writing to the console, but it gets old having to reenter stuff over and over

Near the end of this class we’ll go into using a database to hold stuff, but for now we’re going to play around with writing to and reading from a file.

Page 36: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

StreamWriter and StreamReader

C# makes use of two classes that are part of the System.IO library– StreamWriter has the ability to write information

out to a file on disk.– StreamReader has the ability to read information

in from disk.

Page 37: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

StreamWriter

To write information to a file, we first need to associate it with a variable in our program:

– String sFileName = "DemoFile.txt";– StreamWriter ioOutFile = new StreamWriter(sFilename);

A word about the new crap Once we have it created, we write to it just like we would to the

console, except instead of using the nound "Console" we use the name we gave the stream:

– ioOutFile.WriteLine("{0} {1}","One","Two");– ioOutFile.WriteLine("{0} {2}","Three","Four");– ioOutFile.WriteLine("{0} {3}","Five","Six");

When you are done writing you close the file:– ioOutFile.Close();

Let’s do this and see what happens.

Page 38: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

StreamReader

Once a file exists, one can open it and read it in. Unfortunately, C# doesn’t have a nice input conversion ability like C and C++

– String sFileName = "DemoFile.txt";– StreamReader ioInFile = new StreamReader(sFilename);

Let’s just read the file in that we just made and display it on the Console:String sInLine;while ((sInLine = ioInFile.ReadLine()) != null){

Console.WriteLine(sInLIne);

}ioInFile.Close()

We just introduced a loop. We’ll cover this in a lot more detail next week. Let’s pull this over and run it to see what happens. Let’s see where the program is putting the file.

Page 39: COP 3530 – C# Programming Chapter 5 – Jan 28, 2015.

Decoding What Is In The sInLine

So, we can read in each line, but in our example, each line has two fields separated by a space.

We can use a method that was inherited by our String to Split the input into separate fields.

– Another new thing we will get into a lot more later is an Array. – The Split method separates a string into individual fields and

places each field into an array member: String[] sFields = sInLine.Split(' '); For our example

– sFields[0] contains the first field and sFields[10] contains the second.– Let’s go look at this in action– Once you have the line split, you can then parse the fields if you need to.