Docsity

Control Structures - Java Programming Language - Lecture Slides, Slides of Computer Science

Partial preview of the text

Download Control Structures - Java Programming Language - Lecture Slides and more Slides Computer Science in PDF only on Docsity!

Contents: Control Structures

  • Decision Using if and if...else Nested if Statements Shortcut if Statements Using switch Statements
  • Repetition Looping: for, while, and do Nested loops Using break and continue

Decisions

if Statements

switch Statements

Shortcut if Statements

The if...else Statement

  • Format: if (booleanExpression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; }

if...else Example

if (radius >= 0) { area = radiusradiusPI; System.out.println("The area for the circle of radius " + radius + " is " + area); } else { System.out.println("Negative input"); }

Shortcut if Statements

if (x > 0) y = 1

else y = -1;

is equivalent to

y = (x > 0)? 1 : -1;

switch Statements

switch (year) { case 7: interestRate = 7.25; break; case 15: interestRate = 8.50; break; case 30: interestRate = 9.0; break; default: System.out.println( "Wrong Year, enter 7, 15, or 30"); }

Repetitions

for Loops while Loops do Loops break and continue

for Loops

  • Format: for (control-variable-initializer; continue-condition; adjustment-statement) { //loop body; }
  • Example: int i; for (i = 0; i<100; i++) { System.out.println("Welcome to Java!” + i); } // for (int i = 0; i<100; i++)

for Loop Examples

Examples for using the for loop:  Example 3.2: TestSum.java TestSum TestMulTable  Example 3.3: TestMulTable.java Run Run

while Loops

  • Format: while (continue-condition) { // loop-body; }
  • Example 3.4: TestWhile.java TestWhile Run

do Loops

  • Format:

do

//loop body;

} while (continue-condition)

do Loop Flow Chart

false true Statement(s) Next Statement Continue condition?

The continue Keyword

false true Statement(s) Next Statement Continue condition? Statement(s) continue

Using break and continue

Examples for using the break and continue keywords:  Example 3.5: TestBreak.java  Example 3.6: TestContinue.java TestBreak TestContinue Run Run