loops isys 350. three types of loops while loop do while loop for loop

Post on 21-Dec-2015

252 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Loops

ISYS 350

Three Types of Loops

• while loop• do while loop• for loop

Murach’s Java SE 6, C4 © 2007, Mike Murach & Associates, Inc.Slide 3

The syntax of the while loop

while (booleanExpression) { statements }

An Infinite Loopwhile (true){ System.out.println("enter loan:"); double loan=sc.nextDouble(); System.out.println("enter rate in %:"); double rate=sc.nextDouble(); System.out.println("enter term in year:"); double term=sc.nextDouble(); double monPayment=(loan*rate/100/12)/(1-(Math.pow(1+rate/100/12,-12*term)));

System.out.println("Monthly payment is: =" + monPayment);

}

Using a FlagString flag="Y"; while (flag.equalsIgnoreCase("Y")){ System.out.println("enter loan:"); double loan=sc.nextDouble(); System.out.println("enter rate in %:"); double rate=sc.nextDouble(); System.out.println("enter term in year:"); double term=sc.nextDouble(); double monPayment=(loan*rate/100/12)/(1-(Math.pow(1+rate/100/12,-12*term))); System.out.println("Monthly payment is: =" + monPayment); System.out.println("Do you want to continue? (Y/N):"); flag=sc.next(); } System.out.println("Thank you for using payment calculator!");

Note: Flag may be declared as a boolean.

Flag Declared as boolean

boolean repeatFlag=true;//while (repeatFlag) while (repeatFlag==true){ System.out.println("enter loan:"); double loan=sc.nextDouble(); System.out.println("enter rate in %:"); double rate=sc.nextDouble(); System.out.println("enter term in year:"); double term=sc.nextDouble(); double monPayment=(loan*rate/100/12)/(1-(Math.pow(1+rate/100/12,-12*term))); System.out.println("Monthly payment is: =" + monPayment); System.out.println("Do you want to continue? (Y/N):"); String YON=sc.next(); if (YON.equalsIgnoreCase("N")) repeatFlag=false; }

Accumulator

Find the sum of all numbers between 1 and N.

Scanner sc=new Scanner(System.in); System.out.println("enter an integer:"); int N = sc.nextInt(); int Sum=0; while (N>0) { Sum=Sum+N; --N; } System.out.println("The sum of all numbers is: " + Sum);

Exit Loop with the break statementScanner sc=new Scanner(System.in);while (true){ System.out.println("enter loan:"); double loan=sc.nextDouble(); System.out.println("enter rate in %:"); double rate=sc.nextDouble(); System.out.println("enter term in year:"); double term=sc.nextDouble(); double monPayment=(loan*rate/100/12)/(1-(Math.pow(1+rate/100/12,-12*term))); System.out.println("Monthly payment is: =" + monPayment); System.out.println("Do you want to continue? (Y/N):"); String YON=sc.next(); if (YON.equalsIgnoreCase("N")) break; } System.out.println("Thank you for using payment calculator!");

While Loop ExampleN Factorial, N!

Scanner sc=new Scanner(System.in); System.out.println("enter an integer:"); int N = sc.nextInt(); int factorial=1; while (N>0){ factorial=factorial*N; N=N-1; } System.out.println("factorial= " + factorial);

Compute N! or Stop when the product greater than 100(Determine if it is a normal exit or earlier exit)

Scanner sc=new Scanner(System.in); System.out.println("enter an integer:"); int N = sc.nextInt(); boolean exitEarlier = false; int factorial=1; int Count = 1; while (Count<=N){ factorial=factorial*Count; if (factorial >= 100){ exitEarlier = true; break; } Count++; } if (exitEarlier==false) System.out.println("factorial= " + factorial); else System.out.println("Reach 100 when N = " + Count);

Use continue statement to jump to the beginning of a loop

Find the sum of all even numbers between 1 and N but ignore numbers ending with 6 .Scanner sc=new Scanner(System.in); System.out.println("enter an integer:"); int N = sc.nextInt(); int Sum=0; while (N>0) { if (N % 10 == 6){ --N; continue; } if (N % 2==0) Sum=Sum+N; --N; } System.out.println("The sum of all even numbers ignoreing 6 is: " + Sum);

Murach’s Java SE 6, C4 © 2007, Mike Murach & Associates, Inc.Slide 12

The syntax of the do-while loop do { statements } while (booleanExpression); Note: Statements will execute at least once.

Accumulator

Find the sum of all numbers between 1 and N using do loop.

Scanner sc=new Scanner(System.in); System.out.println("enter an integer:"); int N = sc.nextInt(); int Sum=0; do { Sum=Sum+N; N=N-1; //Sum+=N; //--N; } while (N>0); System.out.println("The sum of all numbers is: " + Sum);

Do while loop example

String flag; do { System.out.println("enter loan:"); double loan=sc.nextDouble(); System.out.println("enter rate in %:"); double rate=sc.nextDouble(); System.out.println("enter term in year:"); double term=sc.nextDouble(); double monPayment=(loan*rate/100/12)/(1-(Math.pow(1+rate/100/12,-12*term))); System.out.println("Monthly payment is: =" + monPayment); System.out.println("Do you want to continue? (Y/N):"); flag=sc.next(); } while (flag.equalsIgnoreCase("Y"));

Murach’s Java SE 6, C4 © 2007, Mike Murach & Associates, Inc.Slide 15

The syntax of the for loop for(initializationExpression; booleanExpression; incrementExpression) { statements }

Sum of 1 to N

Scanner sc=new Scanner(System.in); System.out.println("enter an integer:"); int N = sc.nextInt(); int Sum=0; int i=0; for (i=0; i<=N;++i){ Sum=Sum + i; } System.out.println("The sum is: " + Sum);

Increment smaller than 1

Scanner sc=new Scanner(System.in); System.out.println("enter an integer:"); int N = sc.nextInt(); double Sum=0; double i; for (i=0; i<=N; i += 0.5){ Sum=Sum + i; System.out.println("loop i is " + i); } System.out.println("The sum is: " + Sum);

Note: What is wrong if I and Sum are declared as integer? Infinite loop

For loop with break: Compute N! or Stop when the product greater than 100

(Determine if it is a normal exit or earlier exit)Scanner sc=new Scanner(System.in); System.out.println("enter an integer:"); int N = sc.nextInt(); boolean exitEarlier = false; int factorial=1; int Count = 1; for (Count=1;Count<=N;++Count){ factorial=factorial*Count; if (factorial >= 100){ exitEarlier = true; break; } } if (exitEarlier==false) System.out.println("factorial= " + factorial); else System.out.println("Reach 100 when N = " + Count);

For loop with the continue statementFind the sum of all even numbers between 1 and N but ignore numbers ending with 6 .

Scanner sc=new Scanner(System.in); System.out.println("enter an integer:"); int N = sc.nextInt(); int Sum=0, Count; for (Count=N;Count>0;--Count) { if (Count % 10 == 6) continue; if (Count % 2==0) Sum=Sum+Count; } System.out.println("The sum of all even numbers ignoreing 6 is: " + Sum);

Murach’s Java SE 6, C4 © 2007, Mike Murach & Associates, Inc.Slide 20

A for loop that adds the numbers 8, 6, 4, and 2 int sum = 0; for (int j = 8; j > 0; j -= 2) { sum += j; }

Murach’s Java SE 6, C4 © 2007, Mike Murach & Associates, Inc.Slide 21

How to code for loops A for loop is useful when you need to increment or decrement a

counter that determines how many times the loop is executed.

Within the parentheses of a for loop, you code:

an initialization expression that gives the starting value for the counter

a Boolean expression that determines when the loop ends

an increment expression that increments or decrements the counter

The loop ends when the Boolean expression is false.

You can declare the counter variable before the for loop. Then, this variable will be in scope after the loop finishes executing.

Formatting Numeric Print OutputSystem.out.format

• System.out.format(String format, variables separated by commas);

• Java Tutorials/Numbers and Strings/ Numbers/Formatting Numeric Print Output– int i = 461012; – System.out.format("The value of i is: %d%n", i);

The output is: The value of i is: 461012

Printing more than one variables

Control decimal places: $%.2fPrint with $ and start a new line: $%.2f%n

System.out.format(" %d $%.2f%n", Year,FV);

DecimalFormat Class

• Use DecimalFormat class to define a format:– Format: “###,###.###”

• 123,456.789

– Format: “###.##”• 123456.79

– Format: “000000.000”• 000123.780

– Format: “$###,###.###”• $12,345.67

DecimalFormat Example

DecimalFormat myFormatter = new DecimalFormat("00");Int i=2, j=3, product;product=i*j; String output = myFormatter.format(product);

Future Value=Present Value*(1+Rate)Year

Scanner sc=new Scanner(System.in); System.out.println("enter present value:"); double PV = sc.nextDouble(); System.out.println("enter rate:"); double Rate = sc.nextDouble(); System.out.println("enter ending year:"); double endYear = sc.nextDouble(); double FV; int Year; for (Year=5;Year<=endYear;Year+=5) { FV=PV*Math.pow(1+Rate,Year); //System.out.format("year = %d, FV = %f%n", Year,FV); System.out.format(" %d $%.3f%n", Year,FV); }

Given PV and Rate, compute the FV starting from year 5 until specified year with a step of 5

Nested Loop

String line=""; int i,j,product; for (i=1;i<=3;++i){ for (j=1;j<=4;++j){ product=i*j; line=line+ "( " + i + ", " + j +") "; } System.out.println(line); line=""; }

( 1, 1) ( 1, 2) ( 1, 3) ( 1, 4) ( 2, 1) ( 2, 2) ( 2, 3) ( 2, 4) ( 3, 1) ( 3, 2) ( 3, 3) ( 3, 4)

Note: Use a while loop to produce the same output.

Nested LoopMultiplication Table

1 2 3 4 5 6 7 8 91 01 02 03 04 05 06 07 08 09 2 02 04 06 08 10 12 14 16 18 3 03 06 09 12 15 18 21 24 27 4 04 08 12 16 20 24 28 32 36 5 05 10 15 20 25 30 35 40 45 6 06 12 18 24 30 36 42 48 54 7 07 14 21 28 35 42 49 56 63 8 08 16 24 32 40 48 56 64 72 9 09 18 27 36 45 54 63 72 81

First Try

String line=""; int i,j,product; for (i=1;i<=9;++i){ for (j=1;j<=9;++j){ product=i*j; line=line+product + " "; } System.out.println(line); line=""; }

Second Try

DecimalFormat myFormatter = new DecimalFormat("00"); String line=""; int i,j, product; System.out.println(" 1 2 3 4 5 6 7 8 9"); for (i=1;i<=9;++i){ line=line+ i + " "; for (j=1;j<=9;++j){ product=i*j; String output = myFormatter.format(product); line=line+output + " "; } System.out.println(line); line=""; }

Future Value=Present Value*(1+Rate)Year

Given PV, compute the FV starting from year 5 until specified year with a step of 5 and rate from 3% to specified rate with a step of 0.5%

Rate/Year 5 10 15 20 3.00% $1,159.27 $1,343.92 $1,557.97 $1,806.11 3.50% $1,187.69 $1,410.60 $1,675.35 $1,989.79 4.00% $1,216.65 $1,480.24 $1,800.94 $2,191.12 4.50% $1,246.18 $1,552.97 $1,935.28 $2,411.71 5.00% $1,276.28 $1,628.89 $2,078.93 $2,653.30

Code example Scanner sc=new Scanner(System.in); System.out.println("enter present value:"); double PV = sc.nextDouble(); System.out.println("enter ending rate:"); double endRate = sc.nextDouble(); System.out.println("enter ending year:"); double endYear = sc.nextDouble(); double FV, Rate; int Year; String line=""; DecimalFormat dollarFormatter = new DecimalFormat("$###,###.00"); DecimalFormat percentFormatter = new DecimalFormat("###.00%"); line="Rate/Year "; for (Year=5;Year<=endYear;Year+=5) line=line + Year + " "; System.out.println(line); line=""; for (Rate=0.03;Rate<=endRate;Rate+=0.005){ line=line+ percentFormatter.format(Rate)+ " "; for (Year=5;Year<=endYear;Year+=5) { FV=PV*Math.pow(1+Rate,Year); line=line+ dollarFormatter.format(FV) + " "; } System.out.println(line); line="";}

Exercise

Monthly payment table

term 30Loan

rate 100,000 150,000 200,000 250,0005% $536.82 $805.23 $1,073.64 $1,342.05 5.25% $552.20 $828.31 $1,104.41 $1,380.51 5.50% $567.79 $851.68 $1,135.58 $1,419.47 5.75% $583.57 $875.36 $1,167.15 $1,458.93 6% $599.55 $899.33 $1,199.10 $1,498.88

Create a monthly payment table for loans with term specified by user and rate range from 5% to any specified rate with an increment of .25% and loan from 100,000 to any specified loan with an increment of 50000.

Murach’s Java SE 6, C4 © 2007, Mike Murach & Associates, Inc.Slide 34

A labeled break statement that exits the outer loop

outerLoop: for (int i = 1; i < 4; i++) { System.out.println("Outer " + i); while (true) { int number = (int) (Math.random() * 10); System.out.println(" Inner " + number); if (number > 7) break outerLoop; } }

How to code labeled break statements To jump to the end of an outer loop from an inner loop, you can

label the outer loop and use the labeled break statement.

Murach’s Java SE 6, C4 © 2007, Mike Murach & Associates, Inc.Slide 35

The syntax of the continue statement continue;

A continue statement that jumps to the beginning of a loop

for (int j = 1; j < 10; j++) { int number = (int) (Math.random() * 10); System.out.println(number); if (number <= 7) continue; System.out.println("This number is greater than 7"); }

How to code continue statements To skip the rest of the statements in the current loop and jump to

the top of the current loop, you can use the continue statement.

Murach’s Java SE 6, C4 © 2007, Mike Murach & Associates, Inc.Slide 36

The syntax of the labeled continue statement continue labelName;

The structure of the labeled continue statement labelName: loop declaration { statements another loop declaration { statements if (conditionalExpression) { statements continue labelName; } } }

Murach’s Java SE 6, C4 © 2007, Mike Murach & Associates, Inc.Slide 37

A labeled continue statement that jumps to the beginning of the outer loop

outerLoop: for(int i = 1; i < 20; i++) { for(int j = 2; j < i-1; j++) { int remainder = i%j; if (remainder == 0) continue outerLoop; } System.out.println(i); }

Murach’s Java SE 6, C4 © 2007, Mike Murach & Associates, Inc.Slide 38

The basic syntax for coding a static method {public|private} static returnType methodName([parameterList]) { statements }

Murach’s Java SE 6, C4 © 2007, Mike Murach & Associates, Inc.Slide 39

A static method with no parameters or return type private static void printWelcomeMessage() { System.out.println("Hello New User"); // This could be a lengthy message }

A static method with three parameters that returns a double value

public static double MPayment(double loan,double rate,double term){ double monPayment=(loan*rate/100/12)/(1-(Math.pow(1+rate/100/12,-12*term))); return monPayment; }

Murach’s Java SE 6, C4 © 2007, Mike Murach & Associates, Inc.Slide 40

The syntax for calling a static method that’s in the same class

methodName([argumentList])

A call statement with no arguments and no return value

printWelcomeMessage();

A call statement that passes three arguments and return a value

double monPayment=MPayment(loan,rate,term);

Monthly Payment Methodpublic static void main(String[] args) {Scanner sc=new Scanner(System.in); String flag="Y"; while (flag.equalsIgnoreCase("Y")){ System.out.println("enter loan:"); double loan=sc.nextDouble(); System.out.println("enter rate in %:"); double rate=sc.nextDouble(); System.out.println("enter term in year:"); double term=sc.nextDouble(); double monPayment=MPayment(loan,rate,term); System.out.println("Monthly payment is: =" + monPayment); System.out.println("Do you want to continue? (Y/N):"); flag=sc.next(); } System.out.println("Thank you for using payment calculator!"); } public static double MPayment(double loan,double rate,double term){ double monPayment=(loan*rate/100/12)/(1-(Math.pow(1+rate/100/12,-12*term))); return monPayment; }

Murach’s Java SE 6, C4 © 2007, Mike Murach & Associates, Inc.Slide 42

How to code and call static methods To allow other classes to access a method, use the public access

modifier. To prevent access, use the private modifier.

To code a method that returns data, code a return type in the method declaration and code a return statement in the body of the method. The return statement ends the execution of the method and returns the specified value to the calling method.

Within the parentheses of a method, you can code an optional list of one or more parameters that consist of a data type and name. These values that must be passed to the method when it is called.

The name of a method along with its parameter list form the signature of the method, which must be unique.

When you call a method, the arguments in the argument list must be in the same order as the parameters in the parameter list and they must have compatible data types. However, the names of the arguments and the parameters don’t need to be the same.

top related