20
Logic Our programs will have to make decisions on what to do next we refer to the decision making aspect as logic Logic goes beyond simple if and if- else statements and includes nested if-else statements and loops (introduced later today) what if we have a list of possible actions to take based on an input or computed value? for instance, we ask the user to input their age before playing a game if they enter anything < 0, we want to output an error message if they enter between 1 and 8, we might say that they are too young to play this game if they enter between 18 and 24, we might tell them to grow up and quit playing games if they enter anything over 24, we might laugh at them

Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

Embed Size (px)

Citation preview

Page 1: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

Logic• Our programs will have to make decisions on what to do

next– we refer to the decision making aspect as logic

• Logic goes beyond simple if and if-else statements and includes nested if-else statements and loops (introduced later today)– what if we have a list of possible actions to take based on an

input or computed value?– for instance, we ask the user to input their age before playing a

game• if they enter anything < 0, we want to output an error message• if they enter between 1 and 8, we might say that they are too young to

play this game• if they enter between 18 and 24, we might tell them to grow up and quit

playing games• if they enter anything over 24, we might laugh at them• any other age is ok for our game

– how do we design the logic to handle such a situation?

Page 2: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

Nested Statements• Let’s try to implement the previous example:

– age < 0: error– age between 1 and 8: too young– age between 9 and 17: ok– age between 18 and 24: too old– age > 24: really really old

• Can we do this with an if statement or an if-else? No– we could solve this with 5 if statements, or with a nested if-

else statement• how do we test to see if an age is between 9 and 17? • the conditions we’ve already seen have only tested a variable to one

value, not two• this will take some modification

– or, we can use nested statements, this means that we have an if statement or an if-else statement as the statement inside of the if-clause or the else-clause or both

Page 3: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

Example

if (age < 0) output=“error”; else if(age<=8) output=“too young”;

else if(age<=17) output=“ok”; else if(age<=24) output=“too old”; else output=“really really old”;

if(age < 0) output=“error”;if(age<=8) output=“too young”;if(age<=17) output=“ok”;if(age<=24) output=“too old”;else output=“really really old”;

Nested approach

Note: indentation is not needed, its there for programreadability

Alternate approach – what isWrong with this code?

If you are 16, what will output be?

We could solve this problem by reordering theif statements in the opposite order, but thenew code would be inefficient – why?

Page 4: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

import java.util.*;public class MinOfThree; { public static void main(String[] args) { Scanner in=new Scanner(System.in); int num1, num2, num3, min = 0; System.out.println(“Enter three integers, one at a time”); num1 = in.nextInt( ); num2 = in.nextInt( ); num3 = in.nextInt( );

if (num1 < num2) if (num1 < num3) min = num1; else min = num3; else if (num2 < num3) min = num2; else min = num3; System.out.println("Minimum value is: " + min); }}

Another Example

Notice the logic here, if num1 < num2,

then we compare num1 and num3, to see which is smaller, if num1 < num3 then num1 is smallest (we already know num1is smaller

than num2)

if num1 is not less than num2, wecompare num2

and num3

Page 5: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

The Switch Statement• An alternate approach to using the nested if-else

structure is an instruction called switch• We will use the switch statement if we are testing

a single variable against a list of values• Structure:

– switch (variable) {

case val1 : statement1;case val2 : statement2;

case val3 : statement3; …

case vallast : statementlast;default : defaultstatement;}

Compare variable with val1, val2, … and pick which statement to execute based on which value the variable matches

Page 6: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

Switch Exampleswitch (grade){ case ‘A’ :

comment = "gold star"; break;

case ‘B’ : comment = "silver star"; break;

case ‘C’ : comment = "bronze star"; break;

case ‘D’ : comment = "no star"; break;

case ‘F’ : comment = "demerit"; break;

default : comment = "error, illegal letter grade! ";

}

In this example, comment is aString which is assigned a valuebased on the student’s letter grade

default is used as an error checking mechanism here – if reached, then the grade is an illegal grade

NOTE: the word break is usedto exit the switch statement,default is used as a final elseclause for the switch

Page 7: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

Which Statement Should You Use?

• When it comes to selection, you have five possibilities:– if statement– if-else statement– group of if statements– nested if-else

statement– switch statement

• If there is only one action, then use the if statement

• If two actions, one if the condition is true, one if the condition is false, then use the if-else statement

• If you have a series of possibilities, which should you use?– Switch statement if the

possibility is based on a single variable and the variable is an integral data type (integer, character or a user defined type that is ordinal)

– Otherwise, use the nested if-else statement

Page 8: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

Compound Conditions• Recall the code to the right, what is wrong

with it?– there is improper logic– we need to replace this condition with a

compound condition • test two things: if age > previous upper limit and

also if age <= current upper limit– we create compound conditions by connecting

them together with logic operators– there are 3 forms of logic operators used in

Java:• and (denoted as &&) – all conditions must be true

for the compound condition to be true• or (denoted as ||) – at least one condition must be

true for the compound condition to be true• not (denoted as !) – the item is inverted (true

becomes false, false becomes true)

if(age < 0) output=“error”;if(age<=8) output=“too young”;if(age<=17) output=“ok”;if(age<=24) output=“too old”;else output=“really really old”;

if (age > 8 && age <=17) output=“ok”;

Page 9: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

Repetition• What happens if we want to do some action multiple

times? – For instance, we want to count the number of times it takes

when rolling a 6-sided die until we roll a 6• We write a program that rolls the 6-sided die once and outputs the

result, and then we could run the program over and over until we get a 6, but this is both tiresome and requires that the user count the number of times we ran the program

– The better approach is to use a repetition statement which would keep running the same random number instruction over and over until it it a 6, so we will use a repetition control statement

– There are three forms of repetition statements in Java:• While loops• Do loops• For loops

Page 10: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

The While Statement• The while statement evaluates a

condition – if that condition is true, the body of the

while statement is executed and the process is repeated

– If the condition is false, the rest of the statement is skipped and control continues with the next instruction after the while statement

while ( condition ) statement;

while is areserved word

If the condition is true, the statement is executed.Then the condition is evaluated again.

statement

true

conditionevaluated

false

Page 11: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

Exampleimport java.util.Random;public class SixRoller {

public static void main(String[] args) {int count=1, die;Random g = new Random();die=g.nextInt(6)+1;System.out.println("The first roll is a " + die);while(die!=6) {

die=g.nextInt(6)+1;count++;System.out.println("The next roll is a " + die);

}System.out.println("It took " + count + " rolls to get a 6");

}}

Page 12: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

Example

• Let’s write a loop that will compute the powers of 2 that are less than 1000000– We start with a variable set

equal to 1– We loop while that variable

<=1000000– Inside the loop, we print the

value of the variable and then multiply it by 2• Notice that since the loop

“body” is more than a single statement, we enclose it in { } to make it a block

int value = 1;while (value < 1000000) { System.out.println(value); value *= 2; }

outputs:1248163264…524288

Page 13: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

Sentinel Values• In the two examples, we iterated until we reached some

value of interest (die == 6, value >= 1000000)• We will often use While loops to repeat some action

such as: input some value, perform a calculation, output a result, repeat until the user is done– How do we know if the user is done?– We could ask the user or we could base the decision on the

input value – this is known as a sentinel value

• Example: input a list of integers until the user enters a negative number, and compute the sum of these numbers

Page 14: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

Sum ExampleScanner in = new Scanner(System.in);int value, sum;…sum = 0;System.out.print(“Enter a positive integer, negative to quit: ”);value = in.nextInt( );while (value >= 0){ sum += value; System.out.print(“Enter another positive integer, negative to quit: ”); value = in.nextInt( );}System.out.println("The sum of the numbers you entered is " + sum);

value < 0 is oursentinel for the loop

Notice that we repeated theseInstructions – why?

Initialize sum before we enter the loop

Page 15: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

A slightly different versionint value, sum;…sum = 0;System.out.print(“Enter a positive integer, negative to quit: ”);value = in.nextInt( );while (value >= 0){ sum += value;}System.out.println("The sum of the numbers you entered is " + sum);

Notice in this version we don’t ask for the next value – this means that value never changes – if it never changes, then it is always the original value, if that value was >= 0, it will always be >= 0 and thus the loop will never stop – this is an infinite loop

Page 16: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

Infinite Loops• Careless (and even careful) programmers will write

infinite loops• This is a major problem when using the while loop

– The basic idea behind the loop is to continue executing while a condition is true• If that condition is based on an input value, then the program must

input a new value during each iteration so that the user can change the value to one that exits the loop

• Otherwise, the value never changes and the loop never stops!

• Exiting an infinite loop – if you suspect that your program is caught in an infinite

loop, about your only recourse is to stop the program • Press control-C on the keyboard

Page 17: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

Computing an Average

int number, count, sum;float average;sum = 0;count = 0;System.out.print(“Enter a number, 0 to end”);number = in.nextInt( );while (number > 0){ sum += number; count++; System.out.print(“Enter another number, 0 to end”); number = in.nextInt( );}average = (float) sum / count;System.out.print("The average of your " + count);System.out.println("numbers is " + average);

This program is similar to thesum program from before, butwe are also counting the numberof inputs using the count variable

0 (or any negative number) is our sentinel value

what happens if theuser enters 0 to begin with?

Page 18: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

The do Loop• The do loop is similar to the while loop

but is a post-test loop, the while loop is a pre-test loop

• The Do loop starts with the reserved word do followed by the loop body and then the reserved word while and the condition– The difference is the flow of control – here,

the condition is not evaluated until after the body of the loop executes

do{ statement;}while ( condition )

Uses boththe do andwhile

reservedwords

true

conditionevaluated

statement

false

Page 19: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

While vs. Do• The only difference between

these two statements is when the condition is evaluated– While: evaluated before

executing the loop body– Do: evaluated after executing

the loop body• If you want to automatically

execute the loop body at least once, use the Do loop

• If you don’t want to do the body if the condition is not true, use the While loop

statement

true

conditionevaluated

false

true

conditionevaluated

statement

false

Page 20: Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else

Using Loops to Verify Input• Consider a situation where we

want the user to input one of a set of values that constitute a legal input

• What if the user enters an illegal input?– Example: input a non-negative

integer and take the square root

– If x < 0, we would get a run-time error when the sqrt operation is invoked!

• A solution to this problem is to place the prompt and input statements inside a loop that only terminates once the user has entered the right value– We will use a do statement for

this since we will want the user to input the value at least one timeSystem.out.print(“Enter a non-negative number ”);

x = in.nextInt( );y = Math.sqrt((double) x); do

{ System.out.print(“Enter a non-negative number ”); x = in.nextInt( );} while (x < 0); y = Math.sqrt((double) x);