### Create a StudySoup account

#### Be part of our community, it's free to join!

Already have a StudySoup account? Login here

# Foundations in Programming CS 160

CSU

GPA 3.51

### View Full Document

## 44

## 0

## Popular in Course

## Popular in ComputerScienence

This 68 page Class Notes was uploaded by Betty Kertzmann on Tuesday September 22, 2015. The Class Notes belongs to CS 160 at Colorado State University taught by Staff in Fall. Since its upload, it has received 44 views. For similar materials see /class/210192/cs-160-colorado-state-university in ComputerScienence at Colorado State University.

## Popular in ComputerScienence

## Reviews for Foundations in Programming

### What is Karma?

#### Karma is the currency of StudySoup.

#### You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 09/22/15

data types cs1 60 2006 Chapter Preview In this Chapter we will discuss Integers and Division Primes Greatest Common Divisor Integers and Algorithms data types cs160 2006 Of course you already know what the integers are and wnat diVision IS But There are some specific notations terminology and theorems associ ith these concepts which you may not know These form the basics of number theory Vital in many important algorithms today hash functions cryptography digital signatures Side by Michael F ank Division data types cs160 2006 Division If a and b are integers with a a6 0 we say that a divides b if there is an integer c such that b ac When a divides b we say that a is a factor of b and b is a multiple of a The notation a b denotes that a divides b Examples Letx5y 10z2 W 15 v40 DoesX y In other words does 5 10 Yes DoesX W In other words does 5 15 Yes Does z x In other words does 2 5 NO noninteger result data types cs160 2006 Division Theorem Theorem Let a b and c be integers Then ifandthen ifa b then a bc for all integers c I ifaluandulvthenalv data types cs160 2006 Division Theorem Theorem Let a b and c be integers Then ifabandacthenabc Examples Letx5y10z2w15v40 Doesx y In other words does 5 10 Yes Does X w In other words does 5 15 Yes Since Xdivides both yand w then X must also divide y w In other words 5 must divide 10 15 25 which it does data types cst 60 2006 Division Theorem Theorem Let a b and c be integers Then I if a b then a bc for all integers c Examples Letx5y 10z2 W 15 v40 Does X y In other words does 5 10 Yes Since X y then X must divide yc where c is any integer in 2 Thus X must divide yz or 5 must divide 102 20 which it does data types cs160 2006 Division Theorem Theorem Let a b and c be integers Then I I I ifuluandulvthenulv Examples Letx5y 10z2 W 15 v40 Doesx y In other words does 5 10 Yes Does y W In other words does 10 40 Yes Since X yand y v then X must divide v In other words X must divide v or 5 must divide 40 which it does data types cs160 2006 Division Theorem Corollary a b and c be integers such that I and a c then a mb nc whenever m and n are integers Examples Letx5y10z2w15v40 Since X y and X w then X must divide my nw for any integers m and n In other words if we choose m 3 and n4 then X must divide 3y 4w or 5 must divide 35 415 15 60 75 which it does data types cs160 2006 Primal Fear of Primes data types cs160 2006 Primes integer greaterthan 1 that is divisium only by 1 and itself Examples 2 3 5 7 11 13 17 19 23 29 O There are infinitely many pn39mes data types cs160 2006 Primes A nonprm It i we n1 called composite An integer n is composite if and only if there exists an integer a such that a n and 1 lt a lt n Examples 9 is composite because it is divisible by 3 If n is a composite integer then n has a pIime divisor less than or equal to Vn data types cs160 2006 Primes The Fundamental Theorem ofArithmetic Every positive integer greaterthan 1 can be written uniguely as a prime or as the product of two or more primes where the prime factors are written in order of nondecreasing size Examples 100 2255 2252 182 2 7 13 298202235771 641 641 999 33 37 1024 210 data types cs160 2006 Showing a numbe s prime Show that 113 is prime Solution The only prime factors less than V113 1063 are 2 3 5 and 7 I None OT tnese GIVIOe 39I39Id evenly Thus by the fundamental theorem of arithmetic 113 must be I rime data types cs160 2006 Showing a number is composite Show that 899 is prime Solution Divide 899 by successively larger primes lt l899 starting with 2 I We find that 29 and 31 divide 899 FUN FACT On a unix system enter factor 899 Promptgt factor 899 899 29 31 Matiathe max nm herUNIXfcan factor data types cs160 2006 The prime number theorem T e radio of the number of primes not exceeding X and XInX approaches 1 as X grows without bound Rephrased the number of prime numbers less than x is approximately xlnx Rephrased the chance of an number x being a prime number is 1 nx Oo l 39 th I Consider ZOOdigit prime numbers nathZlsogj x In 10200 n 460 The chance ofa 200 digit number being prime is 1460 Ifwe only choose odd numbers the chance is 2460 1230 Slide by Aaan Bloom eld 3333 Greatest Common Divisors and Least Common Multiples data types cs160 2006 Division Algorithm The Division Algorithm Let a be an integer and da positive integer Then there are unigue integers q and r with 0 s rlt d such that a dq r d is called the divisor a is called the dividend q is called the quotient ris called the remainder Exam gles DE 101 11 9 2 101 11813 11 34 1 11 332 data types cs160 2006 l Given a lo and u hr what are the values of q and r Since 134 3 14 we know that q13div43and r13mod41 O div is the same as the integer O mod is the same Given a 96 and d 15 what are the values of q and r Since 9715 6 715 we know that q97div156and r97mod157 data types cs160 2006 Greatest Common Denominator GCD Examples The greatest common divisor of two integers a and b is the largest integer d such that d a and d b Denoted by gcdab q Easy way to find gcd Find all positive common divisors of both integers then take the largst gcd 24 36 12 gcd 1722 1 gcd100171 data types cs160 2006 Relatively Prime Two numbers are relative rime if they don t have any common factors other than 1 Rephrased a and b are relatively prime if gcd ab 1 gcd 25 39 1 so 25 and 39 are relatively prime data types cs160 2006 Pairwise relative prime A et of integers a a2 an are pairwise relativel I rime if tor all I airs of numbers the are relatively prime Formally The integers a1 a2 a7 are pairwise relatively prime if gcda a 1 whenever1 S i ltjs n Example are 10 17 and 21 pairwise relatively prime gcd10171gcd17211andgcd21101 Thus they are painvise relatively prime Example are 10 19 and 24 pairwise relatively prime Since gcd1024 5 1 they are not data types cs160 2006 The least common multiple of the positive integers a and b is the smallest positive integer that is divisible by both a and b Denoted by lcm a b lcmab plmmth bl gwb h Wantquot Example lom10 25 50 What is lcm 95256 432 95256 233572 4322433 Icm 233572 2433 2max343max537max20 243572 190512 How solve Start by listing pn39me factots data types cs160 2006 Let a and b be positive integers Then ab gcdab Icmab Example gcd 1025 5 Icm 1025 50 1025 550 gcd 95256 432 216 Icm 95256 432 190512 95256432 216190512 data types cs160 2006 Hello World 15 An Application of Primes RSA Encryption data types cs160 2006 An Application of Primes When you visit a secure web site https address indicated by padlock icon in may wu n Netscape the browser and web site may be using a technology called RSA encryption This publickey cryptography scheme involves exchanging public keys containing the product pq of two random large primes p and q a private key which must be kept secret by a given party 80 the security of your daytoday web transactions depends critically on the fact that all known factoring algorithms are intractable Note There is a tractable quantum algorithm for factoring so if we can ever build big quantum computers then RSA is not secure Side by Michael F ank Encrypting with public key I can enerate public and private ke s I publish my public key You can turn a message into a number and encrypt it Only I who also know the private key can decrypt it This solves one of the ancient proble v cryptography going back to Greeks etc how to first get the encryption secret from the recipient to the sender in a secure way Slide by Andrew McNab Simple application secuet Clllallb Internet email is pretty insecure Anyone wno can listen on the networK can see what s In the emails as they go past But using public and private keys people can encrypt a message and include it in an email Keys and messages are base64encoded blobs of text like this iiiiiBEGIN RSA PRIVATE KEYiiiii MIIBPAIBAAJBAOdBZstqePkag4T8e3tDAr3ykv79ErTvERwFlO646IA5KkpMK FizFR3thnC8lrS5DItxdeUo7y03mMMUsCAwEAAQJBAKQVOqA62cHJGcthHl3 pr0rEgOanvablRnCSnggo4Banb7akZaQrvaoyt4Y60PE6yvagiy6eqM dECIQD8888CszDoNfojcereSZZcAZdeoL9l79guWUMOthAOo78FEVh45 DagJRqXWNoSlSplfk5LaIkaXx2akh6pAiEAj2PCeH22Kl4cdtlMDHceivOdrTR dek6tno9ExPlUCIQCthHeKjyPCpoa596y7a2afCOgaQUYQaukSXquQIg ZQFJimvH4ZZjErleQKsmy12NuTk2EDQxbnpyN35g END RSA PRIVATE KEYiiiii Slide by Andrew McNab Connecting with a key ssh uses RSA and similar algorithms Server generates a key pair to identify itself Users can generate key pairs to use instead of passwords At CERN SLAC etc put your public key in sshauthorizedkeys When ou connect ssh checks if server ke pair is the same as last time but the first time it has to take it on trust would be betterto use a signed certificate rather than just a public key Slide by Andrew McNab Connecting with a certificate You re probably familiar with https websites eg for credit card orders from Easyjet These use RSA etc to secure the connection Hosts have certificates rather than ust ublic keys in cert name have CNwwweasyjetcom 80 web browser can verif ou re reall ivin your credit card number to Easyjet Also if you put a user certificate into the browser webserver can verify who you are Slide by Andrew McNab RSA Guessing the Secret Key Key Size Number Time at Time at bits Of Keys 1 us each 1 ps each 32 43x109 358 min 215 ms 56 72x1016 1142 yr 10 hr 128 34x1o38 54x1o24 yr 54x1o18 yr 168 J lX l U50 0dX39IU36 yr 03x1 U30 yr Slide by Waller c Daugherily The RSA Algorithm Select two primes p and q Iferq is very big I calculate n p q 0 O Icurl femly nd prime numbers Calculate z p1q1 W hml Select e such that 1 lt e lt z and gcdze 1 relatively prime e has no common factors with 2 Choose dsuch Calculate u 4 mod 2 0 o thatedIIiis I exactliflzvmble Private key KR dn 0 ifIdon Iknow p undq I cartigezd Slide by Walter c Daugherily compute e such that ic Example Select two primes p7 and q17 Calculate n p q Calculate z p1q1 oeuecr e sucn met 39I lt e lt z and gcdze 1 Calculate d e391 mod 2 Public key KU en Private key KR dn Slide by Walter c Daugherily intrcde ed p 801 KipW6 ed 1 mod 2 1lt111 1 1 n119 z96 e5 d77 5119 77119 p7 and q17 n 119 z 96 e 5 d 77 Public key KU en 5119 Private key KR dn 77119 Plaintext M 19 e was 5 To encrypt Ciphertext C Me mod n 195 mod 119 66 decrypt Plaintext M Cd mod n 66d mod 119 c me mod n remainder when m is divided by n Slide by Waller c Daugherily Cracking RSA Factor n which is I ublic ieldinv I and I Calculate z p1q1 Calculate cl e391 mod 2 e is public Private key KR dn Cracking RSA Example Factor 119 which is public yielding 7 and 17 Calculate 119 71171 96 Calculate 5391 77 mod 96 Private key KR 77119 Example continued I Plaintext M 19 Ciphertext C Me mod n 195 mod w 66 Plaintext M Cd mod n 6677 mod 119 19 Slide by Waller c Daugherily So How Hard is Factoring Year Decimal Digits MIPYears 1964 20 0000009 1974 45 0001 1984 71 01 1994 129 5000 2000 A 09 Slide by Waller c Daugherily Modular Arithmetic If a and b are integers and m is a positive integer then a is congruent to b modulo m if m divides ab Notation a E b mod m Rephrased m ab Rephrased a mod m b If they are not congruent a E b mod m Example Is 17 congruent to 5 modulo 6 Rephrased 17 E 5 mod 6 As 6 divides 175 they are congruent Example Is 24 congruent to 14 modulo 6 Rephrased 24 E 14 mod 6 As 6 does not divide 2414 10 they are not congruent data types cs160 2006 More on congruence Let a and b be integers and let m be a positive integer hen a E b mod m ifand only ifamodmbmodm a mbm m The parenthesis are required to specify modulus Example Is 17 congruent to 5 modulo 6 Rephrased does 17 E 5 mod 6 17 mod65mod 6 mod andm the same Exam Ie Is 24 congruent to 14 modulo 6 Rephrased 24 E 14 mod 6 24mod6 14mod6 m pd In is NOT the same as data types cs160 2006 The Caesar cipher Julius Caesar used this to encrypt messages A function fto encrypt a letter is defined as fp p3 mod 26 Where p is a letter 0 is A 1 is B 25 is Z etc Decryption f1 p p3 mod 26 This is called a substitution cipher You are substituting one letter with another data types cs160 2006 Algorithms 39algorithm39 refers to a set of steps In programming we use algorithms to de ne our programs An algorithm is also used to covert decimal numbers to binary or hexadecimal numbers and viceversa Since today39s computers store values in binary it helps if computer scientists can interpret binary values directly Both octal and hexadecimal representations act as shortcuts toward this oa b rovidin alternate methods for readin binary values data types cs160 2006 Numerical Representations Since today 393 com uters store values in binary it helps if computer scientists can interpret binary values directly Both OCtaI anu hexadecimal representations act as shortcuts toward this goal by providing alternate methods for reading binary values data types cs160 2006 Representatuuu of Integers Let b be a positive integer greaterthan 1 Then if n is a positive integer it can be expressed uniquely in the form n akbk ak1bk1 a1b1 a0 where k is a nonnegative integer a0 a1 ak are nonnegative integers less than b and ak a6 0 Example base 10 496 41029101610 data types cs160 2006 Decimal Value Emmy Repl39eseman39ml Binary Value Binary Expansmn o a 1 12 12 2 12140 9 102 3 1211 2 112 A binary expanSIon 1 39 5 1tzlo2l12 1012 of an Integer happens 6 I 39 7 1 211 21i2 1112 when the Integer b In 8 the definition above 9 10 123o2112102 10102 has the value 2 n 12 123121o21o2 11002 13 1gt 231270 lt2a 27D 7E2 14 1 23121121o2 mo 15 12312712112Dr 111127 16 12 o23o27o21oaqu 10000 17 12 o2302102112 10001 18 12 o23o2112 02 100102 data types cs160 2006 Derilnal Val Hexadecimal Value Hello Hexadecimal Representation World 0 OHS 016 15 Hex Expansion 1 ms 6 2 215 15 I 3 315quot 316 I 4 ms 415 A hexadeCImal 5 expansion of an j 1 intever ha I ens s when the integer b in 1 1 Z the definition above 11 12 3 C15 has the value 16 B 1 14 1416 Em 15 15x15 F16 16 116 o16 10m 17 1161116 1115 18 1151216 1215 data types a I uv vau Practice Using integer division provide both the guotient and the remainder when 98 is divided by 10 70 is divided by 22 Are these integers prime 111 113 data types cs160 2006 Practice Provide the prime factorization for each of these integers 15 97 24 I Find the greatest common divisor for each pair of integers 15 60 3264 data types cs160 2006 Practice Find the least common multiple for each pair of integers 3 4 30 45 u 3 9 21 Convert these integers from decimal notation to binary notation 13 67 data types cs160 2006 Practice Convert these integers from binary notation to decimal notation 101100 I 10001 data types cs160 2006 Division Prime Greatest Common Divisor Least Common Multiple Congruence Caesar Cipher Binary Conversions Hexideoimal Conversions data types cs160 2006 Hello World FIOW 0f Contm39 and Logic Decision Making in Programs LGWlS et al Ch 41 42 43 44 39 and Appendix D Rosen 11 I I Need decision points that are based on data Linear code leads to little difference between program invocations Relational and logical operators Java if and switch statements Boolean expressions Comparing objects what s in memory Integer selector variables Based on a condition that evaluates to either t rue O r f a l s e control cs160 2006 1 control cs160 2006 2 I61 Called flow of control because which statements the flow of the program are actually executed may change each time a program is run Hello World Example e Suppose CSU wanted to list all students with a Hello GPA greater than 375 as they might be eligible for a special scholarship I How might this be done in a Java program I For each student compare his GPA to 375 and print out his name if his GPA is greater if statement control cs160 2006 361 control cs160 2006 4 Hello World 1 f Statement Ensures that a statement is executed only when some condition is Conditions typically involve comparison of variables or quantities for equality or inequality Example control cs160 2006 561 Hello 41 The if Statement The if statement has the following syntax The condi tion must be a boolean expression It must evaluate to either true or false if is a Java reserved word J T If the condi tion is true the statement is executed If it is false the statement is skipped Copyright 2007 Pearson Education Inc Publishing as Pearson AddisonWesley 6 61 Hello World Numeric Relational Operators Math Java description lt Lessthan gt Greater than 3 Less than or equal to 2 Greater than or equal to Equal to 7 Not equal to control cs160 2006 761 Hello World if Statement with else An if statement may have an optional else clause that will only be executed when the condition is false Example if wages lt 57600 tax 0124 wages control cs160 2006 861 Hello World xd Defining Blocks To execute more than one statement conditionally use to define a block aka compound statement for the sequence of statements Example if firstNumber lt secondNumber quotient secondNumber firstNumber remainder secondNumber firstNumber else quotient firstNumber secondNumber remainder firstNumber secondNumber control cs160 2006 961 Hello World Cascading if else Statements Example if conditionl statementl else if conditionZ statementZ else statementB control cs160 2006 10 61 Hello World Code written if conditionl Dangling else Which if does the else finish if conditionZ statementl else statementZ control cs160 2006 11 61 Hello World Fix dangling else Use Blocks to Specify Code written if conditionl if conditionZ statementl control cs160 2006 12 61 Hello World x61 boolean expressions control cs160 2006 13 Hello World boolean Data Type boolean A primitive data type that can be set to I true false Example boolean correct true control cs160 2006 14 61 Hello World x61 Boolean Expressions Conditions are expressions that have a truth value Arithmetic relational operators produce a truth value eg control cs160 2006 1561 Hello World 1amp7 boolean Operators Logical and conjunction Java symbol Math symbol true only when both expressions are true Logical inclusive or disjunction Java symbol Math symbol true when either or both expressions are true wages lt MINIMUMWAGE wages gt MAXIMUMWAGE control cs160 2006 16 61 Hello World 8 boolean Operators cont Logical exclusive or Java symbol Math symbol true when exactly one of the expressions is true Logical not negation Java symbol Math symbol 1MINIMUMWAGE wages control cs160 2006 1761 Hello World Propositional Logic Theory again control cs160 2006 18 Hello World Propositional Logic Theory again Before we go much further with these operations ampamp 1 and A let s step back and look at these operations from a more theoretical viewpoint This should give us a better understanding of how to use these operations control cs160 2006 1961 Hello World Propositional Logic Theory again A proposition is a declarative sentence that is either true or false Example What is the truth value Counter examples control cs160 2006 20 61 Hello Hello World World 13 Propositions cont Negation We represent a proposition as a variable such Letp be a proposition asp or q u The negatiorlofp is 1 39p I As in Java we can combine propositions with denoteg by 9r quot1 T operators for and or not and exclusive or 39 In Engl39Sh nth39S 39f the F statement not p I We can show all the possible values of a I We Show the possible Truth Table proposition or of an expression containing values of and the propositions in a corresponding values of 39lp in a truth table control cs160 2006 21 61 control cs160 2006 22 61 Other propositional operators Exclusive Or XOR operator 39 Letp and q be prOpOS39tlonS Letp and q be propositions In English this is the statement p and q mathematically by I In English this is the statement I The dISJIJnCtIOI I ofp and q IS denoted by I In English this is the statement p or q u The next slide provides a truth table for these operators control cs160 2006 2361 control cs160 2006 24 61 iii Conjunction Disjunction Exclusive Or and Negation 11M pvq p q nn I Ie 39n I39n Iamp Mathematical representation N o t J av control cs160 2006 2561 Hello World x8 Propositional Logic vs Java Boolean Operators As we saw previously in this lecture Java uses much the same operators but with different symbols Following is the truth table on the previous slide translated into Java Boolean operators and values Both A and B are boolean variables control cs160 2006 26 61 Hello World Java Operator Truth Table A B A hampB 1AHI3 AAB A true true true false false true false false Ct Java representat39on control cs160 2006 2761 Hello World Other Logic Operators not in Java The conditional statement p e q means I Not the same as Java s if Note the false case Paq nn e 39I39I I I39I lamp Mathematical representation N o t J av 2861 control cs160 2006 Hello Hello World World Other Logic Operators not in Java Other Logic Operators cont The biconditional I It Should be dear ggennslent 1 94 p q p961 thatthe p q p961 p q T T biconditional T T T F statement 1 a q T F IS the negation F T or the inverse of F T Note the false F F the exclusive or F F 03898 statement 2 69 q control cs160 2006 2961 control cs160 2006 30 61 Proofs of Equivalence Compound Logic Expressions Truth tables can be used to show the equivalence of two logical expressions The last two columns have the same values so the expressions are equivalent p q p q p961 e pv q pAq pv qpAq 39n39I39I I I39u I39I I I39I Iamp nn Ie I39I I39I39I Iamp W j Mathematical representation N tJaV control cs160 2006 31 61 control cs160 2006 I61 Hello World Bit Operations Recall that a bit is either a 0 or 1 Bit Operations A bit string is a sequence of zero or I more bits The length of the string is the number of bits in the string Bitwise AND OR XOR are operations Logic Symbols v A Gr Java Symbols amp quot control cs160 2006 33 control cs160 2006 34 61 Meaning of Bit Operations Bit String as a data type I PerfOrm the IOQical OperatiOHS 0 Bit strings are actually manipulated as corresponding bits in Java integers in Java I Example int ql 5 q2 6 00111010amp00010001 int j ql amp 12 00111010 00010001 int k ql I C12 00111010 A 00010001 What are the values ofj and k control cs160 2006 36 61 control cs160 2006 3561 Hello Java Logical and Arithmetic Operator Precedence Rules Hell Java Logical and Arithmetic 1 unary if Operator Precedence Rules 2 I I 3 4 lt lt gt gt 5 I 6 A amp 7 ampamp 8 Contro39 CS160 2006 37 control cs160 2006 3861 Complicated Boolean Expressions 15 Combining Relational Operators boolean isLeapYear 2 year 4 2 Unlike some other operators relationals ampamp year 100 l 0 cannot be combined in Java Year 400 0 Example 61 lt b lt C Interpretation Does not mean a lt b and b lt c It produces a compiletime error cannot compare a boolean return value of lt operator with a number How should this be done control cs160 2006 3961 control cs160 2006 40 61 Hello World Memory models and Types Recall fill Ch k f I int has a fixed range and is represented in 90 mg or aqua 39ty binary as 2scomplement double has a fixed range and is represented with sign mantissa and exponent String is a sequence of characters An object is represented by its reference an address in memory How do we test equality Contro39 C5160 2006 41 control cs160 2006 42 61 Equality of Numbers Recall Object in memory int is easy as long as within the range morte String morte new Stringlt mequotgt 1f X Stng String sporte morte double IS a problem because of the ImpreCIse object representation l0501050l050 0600 yields false Instead use snorte MathabsX y lt epsilon where epsilon is its tolerance which indicates how far apart they can be and still be considered to be equaL control cs160 2006 4361 control cs160 2006 44 61 Hello World tests whether the object references are the same Sometimes we want to test whether two objects have the same value eg copies in two locations but this method is class specific Equality of Objects control cs160 2006 4561 Hello World x6 Recall Object in memory Strin morte new Strin morte g g Strin I g String sporte new Str1ng object sporte control cs160 2006 mel I Inez 4661 Hello World String Equality String is a class So compares object references I equals is class specific on how it works defined by the class what it means that two objects are equal For strings it compares each character and their sequence in the string Example String name George if control cs160 2006 4761 Hello Comparing Strings Greater thanLess than Compare strings characterbycharacter left to right the first character that differs dictates which string is smaller What if one string is a prefix of the other The prefix is smaller than the longer string How do upper and lowercase characters compare If a casesensitive comparison is used uppercase is always less than lower case How do special characters eg compare Decided by the character ASCII representation control cs160 2006 4861 Hello Hello Comparing Strings 39 Greater thanLess than 39 Java String Class Comparison Methods Compare strings characterbycharacter left to right Example Explanation the first character that differs dictates which string is smaller excographicaIy int compareToString a Compares two strings lexicographically returns Example lt0 0 gt0 values int compareTognoreCaseString a Compares two strings Strlng namej Brownlng lexicographically ignoring String nameZ BrownI case considerations 39 boolean equalsString a Returns true if the strings String name3 Broy are equal and false othenNise boolean equalslgnoreCaseString a Returns true if the strings are equal ignoring case Which String is smallest Which is largest and false othenNise control cs160 2006 4961 control cs160 2006 50 61 Hello World switch Statement Used to accomplish multiway branching based on the Hello value of an integer selector variable world switch Example switch numberOfPassengers I i case 0 System0utprintn The Harley break case 1 System0utprintn The Dune Buggy break default System0utprintln The Humvee control cs160 2006 51 control cs160 2006 52 61 Hello World Systemout Why is break used in switch statements Consider the code fragment below int i switch case case case case 1 i U k F4 CD System System System System println outprintln 0 outprintln l outprintln 2 outprintln 3 Without breaks what is the output note it is legal to leave out the breaks and sometimes desired Hello World x8 Why allow for executing multiple cases Consider if you want a base level with addons for increasing numbers as in switch zoomemberlevel case 50 Systemoutprint Free admissionl case 100 Systemoutprint Free t shirt case 500 Systemoutprint Meet a tiger default Systemoutprintln Example of when we want to leave off the break statements to allow execution to follow through control cs160 2006 5361 control cs160 2006 54 61 Hello Hello World World Symbolic Constants in switch Statements Multiple case Labels in switch Statements final int switch d SUNDAY l MONDAY 2 TUESDAY 3 case MONDAY WEDNESDAY 4 THURSDAY 5 FRIDAY 6 case WEDNESDAY SATURDAY 7 case FRIDAY int d Systemoutprintln CS meets at 900 today Systemoutprintln Math meets at 1000 today switch d break case SUNDAY Systemoutprint Sunday break case TUESDAY case MONDAY Systemoutprint Monday break case THURSDAY case TUESDAY Systemoutprint Tuesday break Systemoutprintln English meets at 900 today case WEDNESDAY Systemoutprint Wednesday break Systemoutprintln Chemistry meets at 1000 today case THURSDAY Systemoutprint Thursday break break case FRIDAY Systemoutprint Friday break case SUNDAY case SATURDAY Systemoutprint Ski day break case SATURDAY Systemoutprintln Enjoy the weekend control cs160 2006 5561 control cs160 2006 56 61 Hello World switch example Display the students grade based on entering their grade as an int between 0 and 100 90 A 8089 B 7079 C Hello World h fW39tcl l Compare If and sWItch case 10 case 9 I Systemoutprintln A break case 8 Systemoutprintln B break case 7 Systemoutprintln C break default Systemoutprintln F control cs160 2006 5761 Contro39 C5160 2006 58 Hello Hello Comparing switch and if statements a Comparing switch and if statements Print out whether the char ch is a vowel or not I switch Statement I if equivalent switch statement if equivalent 39t h tt l l switch expression switchValue expression WIC 6 er lflettTrtt A EettTrtt i if switchValue value1 case A case a Ittl Illefteirzg case value1 statementl statemenm case E case Ie H IetterOHletterO break else if switchValue value2 casellcase etter1y etter u I 2 tt t2 case 0caseo H H case va ue saemen Statementz Gase wcasev S t t tl I break ys emou prln n vowe Systemoutprintln vowel else 1 39f switchValue valueX break case vaueX statementX e se 1 default Systemoutprintln consonant statementX I break 1 Systemoutprintln consonant default statementY e 5e statementY control cs160 2006 5961 control cs160 2006 60 61 Hello World Summary Flow of control Equality if statements Comparisons boolean expressions switch statement if else statements Prepositional logic Bit operations I Order of operations Relational operators control cs160 2006 61 61

### BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.

### You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

## Why people love StudySoup

#### "There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

#### "I bought an awesome study guide, which helped me get an A in my Math 34B class this quarter!"

#### "There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

#### "Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

### Refund Policy

#### STUDYSOUP CANCELLATION POLICY

All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email support@studysoup.com

#### STUDYSOUP REFUND POLICY

StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here: support@studysoup.com

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to support@studysoup.com

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.