exercise: computing the pythagorean theorem write a ...dpomer/comp202/unit4wedsection1.pdfexercise:...

Post on 22-May-2020

3 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

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

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

}.....

Exercise: Computing the Pythagorean theorem

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

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

}}

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

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

}.....

Exercise: Computing the Absolute Value

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

return -x;}else return x;

}}

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

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”

Last Class

• If statements• Boolean expressions• Learning how to rtfm

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

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

introduceLooping();}

}}

More on if statements

Example: Bad Style

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

Example: Bad Style Leads to a Common Error

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

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!

Example: Good Style Eliminates Possibility of Common Error

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

Summary: if-else statement

• if (condition)• One statement or block of

statements• else• One statement or block of

statements

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

•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

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

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

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

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;

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

}

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.

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”

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

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

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• }• }

Part 3: Advanced Conditional Statements

1) The switch statement2) The conditional operator

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

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

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");● }

“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”);• }

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!");}

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

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

The conditional operator

The Conditional Operator•

condition ? expression1 : expression2

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

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

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:

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"

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

About Constants

final double PI = 3.1416;

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

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

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

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

COMP-202Unit 4: Programming With

Iterations

CONTENTS:The while and for statements

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

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.

Example of a “while” loop

int x = 0;

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

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

Recall: increment/decrement operators

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

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

“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

Example of a “while” loop

int x = 0;

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

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

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

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."); }}

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."); }}

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

Components of a “while” loopcondition

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

Components of a “while” loop

loop body

Definition: “iteration”

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

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 .

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?

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?

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?

Logic of a while Statement

condition

statement

(rest of the program)

true

false

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!"); }}

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

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

SumSum: 1i: 2

Sum: 3i: 3

Sum: 6i: 4

Sum: 10i: 5

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

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

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

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

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

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

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."); }}

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

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."); }}

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

Part 2: The for Statement

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 .

“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

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

Components of a “for” loop

Logic of a for Statement

conditionevaluated

statement

(rest of the program)

truefalse

initialization

increment

Logic of a for Statement

x<5

{loop body}

(rest of the program)

truefalse

x=0

x++

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

initialization;while ( condition ) {

statement;increment;

}

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.

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

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."); }}

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.

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

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

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

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

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

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

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

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

// Add your code here }}

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?

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

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?

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

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

What shape does this program display?

Part 4: Exercises

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.

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:

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

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.

Assignment Operators (1)Example 1:

total += 5;is equivalent to

total = total + 5;

•Example 2: result *= count1 + count2;

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

top related