Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise:...

111
Exercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads two doubles as input from the user 2)Calls a method that computes the hypotenuse of a right triangle with those 2 entered numbers as sides. (The function should return a double) 3)Print the result Hint: The square root method can be found in a class java.lang.Math

Transcript of Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise:...

Page 1: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Exercise: Computing the Pythagorean theorem

Write a program that does the following:

1)Reads two doubles as input from the user2)Calls a method that computes the hypotenuse of a right triangle with those 2 entered numbers as sides. (The function should return a double)3)Print the resultHint: The square root method can be found in a classjava.lang.Math

Page 2: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Exercise: Computing the Pythagorean theorem

import java.util.Scanner;import java.lang.Math;public class Pythagorus {

public static void main(String[] argv) {System.out.println(“Enter 2 numbers”);Scanner s = new Scanner(System.in);double side1 = s.nextDouble();double side2 = s.nextDouble();System.out.print(“The hypotenuse length is”);System.out.println(calcHypotenuse(side1,side2));

}.....

Page 3: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Exercise: Computing the Pythagorean theorem

public static double calcHypotenuse(double s1, double s2) {

return Math.sqrt(Math.pow(s1,2) + Math.pow(s2,2) );

}}

Page 4: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Exercise: Absolute valueWrite a program that does the following:

1)Reads an integer from the user2)Calls a method that computes the absolute value of the integer.3)Calls the absolute value method defined in java.lang.Math on the integer4)Print the result of each method and make sure they are the same

Page 5: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Exercise: Computing the Absolute Value

import java.util.Scanner;import java.lang.Math;public class Pythagorus {

public static void main(String[] argv) {System.out.println(“Enter 2 numbers”);Scanner s = new Scanner(System.in);int x = s.nextDouble();System.out.println(“The abs value is ” +

Math.abs(x));System.out.println(“It is also ” + myAbs(x));

}.....

Page 6: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Exercise: Computing the Absolute Value

public static double myAbs(double x) {if (x < 0) {

return -x;}else return x;

}}

Page 7: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Testing our exercise:What would be a good way to test that we coded something correctly?

Page 8: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Testing our exercise:What would be a good way to test that we coded something correctly?

Try to think of all possible inputs to the program and figure out how to generalize them into “classes” (not Java classes) or “categories”

Page 9: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Last Class

• If statements• Boolean expressions• Learning how to rtfm

Page 10: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

public class January26{public static void main(String[] args) {

concludeIfStatements();someNestedIfStatements();while (stillIsTime()) {

introduceLooping();}

}}

Page 11: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

More on if statements

Page 12: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Example: Bad Style

•• boolean tall = height > 6.0;• if(tall == true) x = 5;

Page 13: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Example: Bad Style Leads to a Common Error

• boolean tall = height > 6.0;• if(tall = true) x = 5;

Page 14: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Example: Bad Style Leads to a Common Error

•• boolean tall = height > 6.0;• if(tall = true) x = 5;

This sets tall to true, so “x = 5” always executes, regardless of the value of height. This is a logical error: compiler will not detect it!

Page 15: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Example: Good Style Eliminates Possibility of Common Error

•• boolean tall = height > 6.0;• if(tall) x = 5;

Page 16: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Summary: if-else statement

• if (condition)• One statement or block of

statements• else• One statement or block of

statements

Page 17: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Each e l s e paired with most recent uninterrupted i f in same block

•if(x != 0) width = x + 5;x = 2;else { width = x + 10; x = x + 1;}

Page 18: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

•if(x != 0) width = x + 5;x = 2;else { width = x + 10; x = x + 1;}

Compile-time error: e l s e isn't associated with any i f statement.

x = 2; “interrupts” the if on the first line.

Each e l s e paired with most recent uninterrupted i f in same block

Page 19: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

if(width > 0) { if(x != 0) width = x + 5; x = 2;}else { width = x + 10; x = x + 1;}

Each e l s e paired with most recent uninterrupted i f in same block

Page 20: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

if(width > 0) { if(x != 0) width = x + 5; x = 2;}else { width = x + 10; x = x + 1;}

Each e l s e paired with most recent uninterrupted i f in same block

Page 21: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

if(width > 0) { if(x != 0) width = x + 5; X = 2;}else { width = x + 10; x = x + 1;}

This i f and this e l s e are in different blocks, so they are not paired together.

Each e l s e paired with most recent uninterrupted i f in same block

Page 22: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Nested if Statements (2)•One can write nested if-else statements like this:

if ( condition1 )if ( condition2 )

statement1;else

statement2;else

if ( condition3 )statement3;

elsestatement4;

Page 23: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Nested if Statements (2)Scanner s = new Scanner(System.In);int x = s.nextInt();int y = s.nextInt();

if (x > 0) {if (y >0) {

System.out.println(“In the first quadrant”);}else if (y < 0) {

System.out.println(“in the 4th quadrant”)

}else if (x < 0) {

if ( y > 0 ) System.out.println(“In the 3 rd quadrant”);else if (y < 0) System.out.println(“In the 4 th quadrant”);

}

Page 24: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Exercise:Expand the example on the previous slide to include cases where the points are on the axis

Be sure to include:

-a check for the origin (i.e. x and y are both zero)-a check for the x-axis-a check for the y-axis

Make sure that your program prints exactly one thing in each case.

Page 25: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Testing our exercise:What would be a good way to test that we coded something correctly?

Try to think of all possible inputs to the program and figure out how to generalize them into “classes” (not Java classes) or “categories”

Page 26: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Testing our exercise:For example, in the coordinate example, it would be good to make sure the program works in the following cases:

x and y are both 0x and y are both positivex and y are both negativex is positive but y is negativex is negative but y is positivex is positive but y is 0x is negative but y is 0x is 0 and y is positivex is 0 and y is negative

Page 27: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Nested if Statements: Exercise•Complete the main() method of the MinOfThree class by adding code which determines which of the three numbers entered by the user is the smallest number, and displays that number•Write this in 2 different ways:••1)Without using nested if statements, but using && or || or !•2)Using nested if statements and no &&, ||, or buts...errrrr !s

Page 28: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

MinOfThree.java• import java.util.Scanner;•• public class MinOfThree {• public static void main(String[] args) {• Scanner keyboard = new Scanner(System.in);• int num1, num2, num3, min;• • System.out.print("Enter a number: ");• num1 = keyboard.nextInt();• System.out.print("Enter another number: ");• num2 = keyboard.nextInt();• System.out.print("Enter a third number: ");• num3 = keyboard.nextInt();• • // Add your code here• }• }

Page 29: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Part 3: Advanced Conditional Statements

1) The switch statement2) The conditional operator

Page 30: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

The “switch” statement: example• int x,y;• switch(x+y){• case 5: System.out.print(“A”);• case 8: System.out.print(“B”);• System.out.print(“F”);• case 1: System.out.print(“C”);• default: System.out.print(“D”);• }•Strangely, once one case is true, it will do the results of EVERY case

until it sees the command “break;” In this case, then if x+y==5, it will print ABFCD

Page 31: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

The “switch” statement

• int x,y;• switch(x+y){• case 5: System.out.print(“A”);• case 8: System.out.print(“B”);• case 1: System.out.print(“C”);• default: System.out.print(“D”);• }

Case values must be literals or constants; all of same type as “test expression”.

Page 32: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

What will this display?● int section = 4;●

● switch(section) {● case 1:● System.out.println("A");● default:● System.out.println("B");● case 2:● case 3: ● System.out.println("C");● System.out.println("4");● }

Page 33: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

“switch” statement with “break”• int x,y;• switch(x+y){• case 5: System.out.print(“A”);• break;• case 8: System.out.print(“B”);• System.out.print(“F”);• case 1: System.out.print(“C”);• break;• default: System.out.print(“D”);• }

Page 34: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

What will this display?int section;

System.out.print("Enter your COMP-202 section: ");section = keyboard.nextInt();

switch(section) { case 1: System.out.println("Your section number is not prime."); break; case 2: case 3: System.out.println("Your section number is prime."); break; default: System.out.println("There must be lots of students!");}

Page 35: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

What will this display?int section;

System.out.print("Enter your COMP-202 section: ");section = keyboard.nextInt();

switch(section) { default: System.out.println("There must be lots of students!"); case 1: System.out.println("Your section number is not prime."); break; case 2: case 3: System.out.println("Your section number is prime."); break;}

Page 36: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Summary of switch Statements•The expression of a switch statement must evaluate to a value of type char, byte, short or int; it cannot be a floating point value, a long, a boolean, or any reference type, including String

•Note that the implicit boolean expression in a switch statement is equality–The switch statement tries to match the expression with a value (it is never <, <=, >, nor >=)

•You cannot perform relational checks with a switch statement•The value of each case must be a constant (either a literal or a final variable)–It cannot be a plain (that is, non-final) variable

Page 37: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

The conditional operator

Page 38: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

The Conditional Operator•

condition ? expression1 : expression2

•••If condition evaluates to true, then expression1 is evaluated; if it evaluates to false, then expression2 is evaluated

Page 39: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Conditional Operator Examples (1)•

larger = (num1 > num2) ? num1 : num2;••If num1 is greater that num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger

Page 40: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Conditional operator vs. if-else ●The conditional operator is like an if-else statement, except that instead of executing one of two possible branches, it evaluates to one of two possible values.

l ar g e r = ( num1 > num2) ? num1 : num2;

i f ( num1 > num2)l ar g e r = num1;

e l s e l ar g e r = num2;

...is the same as:

Page 41: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Conditional Operator Examples (2)•

System.out.println ("Your change is " +count + " dime" +((count == 1) ? "" : "s"));

•If count evaluates to 1, then "dime" is printed•If count evaluates to any value other than 1, then an "s" is added at the end of "dime"

Page 42: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

•Exercise: •Use the conditional operator to

•express “absolute value”.•

•Absolute value examples:•The absolute value of 6 is 6.•The absolute value of -1 is 1.

Page 43: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

About Constants

final double PI = 3.1416;

Page 44: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Review: Constants (1)•A constant is like a variable except that it holds one value for its entire existence•The compiler will issue an error if you try to assign a value to a constant more than once in the program

Page 45: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Advantages of Constants•Constants can make programs easier to understand•Constants facilitate changes to the code•Constants prevent inadvertent errors

Page 46: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Top-Down Program Development•Top-down development is a way of thinking when you try to solve a programming problem–It involves starting with the entire problem, and breaking it down into more manageable pieces–Each of these pieces can then be broken down again into smaller pieces–You then solve each of these pieces, and combine the solutions to these pieces to form the solution to the original problem

Page 47: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Top-Down Development: Steps•Applying top-down development consists of doing the following:1.First, read and understand the problem2.Then, subdivide the problem into pieces. Each chunk is one task, like initializing variables, getting inputs, generating outputs, if-statements and loops3.Then sort all these elements in the correct order.4.Last, only now start writing your code

•Steps 1-3 are either done in your head or on scrap paper. They are not done using the language editor or compiler. They do not even need to be in Java, they could be in simple English / French / your first language / ...

Page 48: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

COMP-202Unit 4: Programming With

Iterations

CONTENTS:The while and for statements

Page 49: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Repetition Statements•Repetition statements allow us to execute a (set of) statement(s) multiple times, repetitively; these statements are often called loops

Page 50: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Repetition Statements in Java•Java has two main kinds of repetition statements: the while loop and the for loop•“While” and “for” loops are equivalent

– However, in certain circumstances, choosing one of these statements over the other results in a program that is easier to understand.

Page 51: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Example of a “while” loop

int x = 0;

while (x < 4) { System.out.println(“I have to write “ + “this over and over.”); x++;}

Page 52: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Recall: increment/decrement operators

Remember that if you have an int variable, you can do

x++++xx----x

to increment or decrement the value stored in x

Page 53: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Recall: increment/decrement operators

for(int x = 0; x < 4; x++) { System.out.println(“I have to“ + “write this over and over”);}

Page 54: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Recall: “if” statementi f ( condition) One statement

Example:if(x != 0) width = x + 5;

i f ( condition) One block of statements

Example:if(x == 0){ z = x + 3; x = 5;}

Page 55: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

“while” loops are similar in structure to “if” statements

whi l e ( condition) One statement

whi l e ( condition) One block of statements

The difference is that when we reach the end of the one statement or block, we “go back” to the start of the while loop and re-test the condition

Page 56: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Example of a “while” loop

int x = 0;

while (x < 4) { System.out.println(“I have to write “ + “this over and over.”); x++;}

Page 57: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

x = 0;if (x < 4) { System.out.println(...); x++; if (x < 4) { System.out.println(...); x++; if (x < 4) { System.out..... } }}

Page 58: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Cheating at rock paper scissorsScanner s = new Scanner(System.in);bool keepPlaying = true;while (keepPlaying) { System.out.println(“Enter Rock(r)” +“Scissor (s), Paper(p),or quit(q)”); char next = c.nextChar(); if (next == 'r')

System.out.println(“I play paper!”);if (next == 's') System.out.println(“I play rock!”);if (next == 'p') System.out.println(“I play scissor”);if (next == 'q') { System.out.println(“Giving up! LAME!);

keepPlaying = false;} }

Page 59: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

What does this display?

public class Counter { public static void main(String[] args) { final int LIMIT = 3; int count = 1;

while (count <= LIMIT) count = count + 1; System.out.println(count);

System.out.println("Done."); }}

Page 60: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

What does this display?

public class Counter { public static void main(String[] args) { final int LIMIT = 3; int count = 1;

while (count <= LIMIT){ System.out.println(count); count = count + 1; }

System.out.println("Done."); }}

Page 61: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

while (x < 4) { System.out.println(“I have to write “ + “this over and over.”); x++;}

Components of a “while” loopcondition

Page 62: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

while (x < 4) { System.out.println(“I have to write “ + “this over and over.”); x++;}

Components of a “while” loop

loop body

Page 63: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Definition: “iteration”

An iteration is a single execution of the instructions in the loop body.

Page 64: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

int x = 0;

while (x < 4) { System.out.println(“I have to write “ + “this over and over.”); x++;}

This loop consists of 4 iterations.

I have to wr i te thi s o v e r and o v e r .I have to wr i te thi s o v e r and o v e r .I have to wr i te thi s o v e r and o v e r .I have to wr i te thi s o v e r and o v e r .

Page 65: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

int x = 4;

while (x > 4) { System.out.println(“I have to write “ + “this over and over.”); x++;}

How many iterations does the following loop consist of?

Page 66: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

int x = 6;

while (x > 4) { System.out.println(“I have to write “ + “this over and over.”); x--;}

How many iterations does the following loop consist of?

Page 67: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

int x = 6;

while (x < 4) { System.out.println(“I have to write “ + “this over and over.”); x++;}

How many iterations does the following loop consist of?

Page 68: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Logic of a while Statement

condition

statement

(rest of the program)

true

false

Page 69: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

What is wrong here?public class Abyss { public static void main(String[] args) { int count = 1;

System.out.println("I'm going in..."); while (count <= Integer.MAX_VALUE) { System.out.println(count); count = count - 1; }

System.out.println("Found the bottom of the abyss!"); }}

Page 70: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Infinite Loops: A Common Logical Error

•An infinite loop executes until the user interrupts (terminates) the program.•This is what happens when the statements in the body of a while loop never update the loop condition to false

Page 71: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

What will be displayed? Why is it the wrong result?Correct the program so that it displays the right sum.

public class Sum { public static void main(String[] args) { final int MAX = 5; int sum = 0; int i = 1;

while(i < MAX) { sum = sum + i; System.out.println("Sum: " + sum); i = i + 1; System.out.println("i: " + i); System.out.println(); }

System.out.println("The sum of integers from 1 to " + MAX + " is: " + sum); }}

Page 72: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

SumSum: 1i: 2

Sum: 3i: 3

Sum: 6i: 4

Sum: 10i: 5

The sum of the integers from 1 to 5 is: 10

Page 73: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Off-By-One Errors•It is a common logical error to write loop conditions that result in the loop body being executed one time too few, or one time too many•You should always test your code to check that your loops conditions do not cause such errors

Page 74: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

What will be displayed? Why is it the wrong result?Correct the program so that it displays the right sum.

public class AnotherSum { public static void main(String[] argv) { final int MAX = 5; int i = 0; int sum = 0;

while(i <= MAX) { i = i + 1; System.out.println("i: " + i); sum = sum + i; System.out.println("sum: " + sum); System.out.println(); }

System.out.println("The sum of integers from 1 to " + MAX + " is: " + sum); }}

Page 75: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

i: 1sum: 1

i: 2sum: 3

i: 3sum: 6

i: 4sum: 10

i: 5sum: 15

i: 6sum: 21

The sum of the integers from 1 to 5 is: 21

Page 76: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

General loop tips•Try to think of exactly what it is that you want to do over and over again•Figure out the range of values you want to try again and again. Is the loop counter also used in the computation?•Make sure that your loop starts or initializes with the right result•Make sure that your loop terminates with the correct result

Page 77: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Nested Loops•Like if and if-else statements, loops can be nested as well•Every time the body of the outer loop is executed, the inner loop will go through its entire set of iterations

Page 78: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

What does this display?public class NestedLoop { public static void main(String[] args) { final int MAX = 4; int outerCount, innerCount; outerCount = 1; while(outerCount <= MAX) { innerCount = 1; while (innerCount <= MAX) { System.out.print("(" + outerCount + "," + innerCount + ") "); innerCount++; } System.out.println(); outerCount++; } System.out.println("Done."); }}

Page 79: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

(1,1) (1,2) (1,3) (1,4) (2,1) (2,2) (2,3) (2,4) (3,1) (3,2) (3,3) (3,4) (4,1) (4,2) (4,3) (4,4)Done.

Page 80: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

What does this display?public class AnotherNestedLoop { public static void main(String[] args) { final int MAX = 4; int outerCount, innerCount; outerCount = 1; while(outerCount <= MAX) { innerCount = 1; while (innerCount <= outerCount) { System.out.print("(" + outerCount + "," + innerCount + ") "); innerCount++; } System.out.println(); outerCount++; } System.out.println("Done."); }}

Page 81: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

(1,1) (2,1) (2,2) (3,1) (3,2) (3,3) (4,1) (4,2) (4,3) (4,4) Done.

Page 82: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Part 2: The for Statement

Page 83: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

for(int x = 0; x < 4; x++) { System.out.println(“I have to write “ + “this over and over.”);}

Example: a “for” loop

I have to wr i te thi s o v e r and o v e r .I have to wr i te thi s o v e r and o v e r .I have to wr i te thi s o v e r and o v e r .I have to wr i te thi s o v e r and o v e r .

Page 84: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

“for” loops are a little different, but still quite similar

for ( initialization; condition; follow-up action)

One statement

for ( initialization; condition; follow-up action)

One block of statements

Page 85: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

for(int x = 0; x < 4; x++) { System.out.println(“I have to write “ + “this over and over.”);}

Components of a “for” loop

Page 86: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads
Page 87: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Logic of a for Statement

conditionevaluated

statement

(rest of the program)

truefalse

initialization

increment

Page 88: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Logic of a for Statement

x<5

{loop body}

(rest of the program)

truefalse

x=0

x++

Page 89: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

for Loops as while Loops•A for loop is equivalent to the following while loop structure:

initialization;while ( condition ) {

statement;increment;

}

Page 90: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

for Loops as while Loops•A for loop is equivalent to the following while loop structure:

initialization;while ( condition ) {

statement;increment;

}

Excellent exercise to do at home!Find a for-loop example and:•Rewrite it as a while loop•Rewrite it as a series of if-else statements.

Page 91: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Execution of a for Loop•Like in a while loop, the condition of a for loop is tested prior to entering the loop body•If the condition of a for loop evaluates to false initially (that is, it evaluates to false the first time it is evaluated), the statement is never executed•Therefore, the body of a for loop will be executed zero or more times•A for loop is well suited for executing a specific number of times that can be determined in advance

Page 92: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

AnotherCounter.javapublic class AnotherCounter { public static void main(String[] args) { final int LIMIT = 3;

for (int count=1; count <= LIMIT; count++) { System.out.println(count); }

System.out.println("Done."); }}

Page 93: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

AnotherCounter.javapublic class AnotherCounter { public static void main(String[] args) { final int LIMIT = 3;

for (int count=1; count <= LIMIT; count++) { System.out.println(count); }

System.out.println("Done."); }}

What does this display?count:

LIMIT: 3

1 2 3 4

Console:1

2

3

Done.

Page 94: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

What shape does this display?public class Stars { public static void main (String[] args) { final int MAX_ROWS = 10;

for (int row = 1; row <= MAX_ROWS; row++) { for (int star = 1; star <= row; star++) { System.out.print("*"); } System.out.println(); } }}

Page 95: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

*******************************************************

Page 96: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

What Shape does this Display?public class WhatIsThis { public static void main(String[] args) { final int MAX_ROWS = 10; for (int row = 1; row <= MAX_ROWS; row++) { for (int space = 1; space <= MAX_ROWS - row; space++) { System.out.print(" "); } for (int star = 1; star <= row * 2; star++) { System.out.print("*"); } System.out.println(); } for (int base = 3; base > 0; base--) { for (int space = 1; space <= MAX_ROWS-1; space++) { System.out.print(" "); } System.out.println("**"); } }}

Page 97: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * *

Page 98: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Details on the for Statement•Each expression in the header of a for loop is optional–If the initialization portion is left out, no initialization is performed–If the condition portion is left out, it is always considered to evaluate to true, and therefore creates an infinite loop–If the increment portion is left out, no increment operation is performed

•Both semi-colons are always required in the for loop header

Page 99: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

for Loop: Exercise 1•Complete the main() method of the Multiples class by adding code that displays all the multiples of a number entered by the user that exist between 1 and an upper limit also entered by the user–The completed program MUST display 5 multiples of the number entered by the user per line, except for the last line, which may contain less–In addition, the completed program MUST display a tab character ('\t') between every multiple displayed on a line–Finally, the completed program MUST use a for loop to generate and display the multiples of the number entered by the user

Page 100: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Multiples.java (1 / 2)import java.util.Scanner;

public class Multiples { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); final int PER_LINE = 5; int value; int limit;

System.out.print ("Enter a positive value: "); value = keyboard.nextInt(); System.out.print ("Enter an upper limit: "); limit = keyboard.nextInt();

System.out.println ("The multiples of " + value + " between " + value + " and " + limit + " (inclusive) are:"); // Continued on next slide

Page 101: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Multiples.java (2 / 2) // Continued from previous slide

// Add your code here }}

Page 102: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

for Loop: Exercise 2•Complete the main() method of the Approximation class by adding code that approximates the number e (the basis of the natural logarithm). The number e can be approximated by the following sum: e = (1 / 0!) + (1 / 1!) + (1 / 2!) + (1 / 3!) + ...–The main() method of the Approximation class asks the user to enter the number of terms of be computed; your task is to add code which computes each of these terms and adds them together to form the approximation of e

•The obvious way of solving this problem involves using nested loops, where the inner loop computes the required factorial during every iteration of the outer loop. Can you find a way to solve this problem using only one loop?

Page 103: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Approximation.javaimport java.util.Scanner;

public class Approximation { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int n; System.out.print("Please enter the number of terms: "); n = keyboard.nextInt(); // Add your code here }}

Page 104: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Stars.javapublic class Stars { public static void main (String[] args) { final int MAX_ROWS = 10;

for (int row = 1; row <= MAX_ROWS; row++) { for (int star = 1; star <= row; star++) { System.out.print("*"); } System.out.println(); } }}

What shape does this program display?

Page 105: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

WhatIsThis.java (1 / 2)public class WhatIsThis { public static void main(String[] args) { final int MAX_ROWS = 10;

for (int row = 1; row <= MAX_ROWS; row++) { for (int space = 1; space <= MAX_ROWS - row; space++) { System.out.print(" "); } for (int star = 1; star <= row * 2; star++) { System.out.print("*"); } System.out.println(); }

for (int base = 3; base > 0; base--) { for (int space = 1; space <= MAX_ROWS-1; space++) { System.out.print(" "); } // Continued on next slide

Page 106: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

WhatIsThis.java (2 / 2) // Continued from previous slide System.out.println("**"); } }}

What shape does this program display?

Page 107: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Part 4: Exercises

Page 108: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Exercises (1)1.Write a program which consists of a single class called Factor that asks the user to enter a positive integer (including zero). The program then displays that number and its greatest prime factor. The program repetitively does this until the user inputs a negative number.

Page 109: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Exercises (2)2.Write a program which consists of single class called Boxes that asks the user for a positive integer number n. The program then displays a solid square with side length n next to a hollow square with side length n. The program does nothing if the user inputs 0 or a negative value. If example, if the user enters 4, the following will be displayed:

**** ******** * ***** * ***** ****

Page 110: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Exercises (3)3.One can approximate the square root of any number a using the following sequence:

x0 = a / 2

xi+1

= (xi + a / x

i) / 2

Write a program which consists of a single class called SquareRoot. This class defines a main() method that asks the user to enter a number a, and a number of iterations n, and reads these values from the keyboard. The program then computes the nth term in the above sequence, thus approximating the value of of the square root of a, and displays it to the screen.

Page 111: Exercise: Computing the Pythagorean theorem Write a ...dpomer/comp202/unit4wedsection1.pdfExercise: Computing the Pythagorean theorem Write a program that does the following: 1)Reads

Assignment Operators (1)Example 1:

total += 5;is equivalent to

total = total + 5;

•Example 2: result *= count1 + count2;

is equivalent toresult = result * (count1 + count2);