Docsity

Control Structures in Java: if, switch, and Loops, Schemes and Mind Maps of Computer Programming

Partial preview of the text

Download Control Structures in Java: if, switch, and Loops and more Schemes and Mind Maps Computer Programming in PDF only on Docsity!

Control Statements

Selection Statements

  • Using if and if...else
  • Using switch Statements
  • Conditional Operator Repetition Statements
  • Looping: while, do-while, and for

Selection Statements  if Statements  switch Statements  Conditional Operators

Caution

Adding a semicolon at the end of an if clause is

a common mistake.

if (radius >= 0);

area = radiusradiusPI;

System.out.println(

"The area for the circle of radius " +

radius + " is " + area);

This mistake is hard to find, because it is not

a compilation error or a runtime error, it is a

logic error.

Wrong

The if...else Statement

if (booleanExpression) { statements-for-the-true-case; } else { statements-for-the-false-case; }

Multiple Alternative if Statements if (score >= 90) grade = ‘A’; else if (score >= 80) grade = ‘B’; else if (score >= 70) grade = ‘C’; else if (score >= 60) grade = ‘D’; else grade = ‘F’;

switch Statements

switch (conditional variableName) {
case? : body statement 1 ;
break;

case? : body statement 2 ; break; case? : body statement 3 ; break;

...

default: body statement if all above cases
doesn’t worked;

switch Statement Flow Chart

numOfYears 7 15 30 default Next Statement annualInterestRate=7.25 annualInterestRate=8.50 annualInterestRate=9.0 System.out.println("Wrong number of " + "years, enter 7, 15, or 30"); System.exit(0);

Conditional Operator

if (x > 0)

y = 1;

else

y = - 1;

is equivalent to

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

Called Ternary operator

Binary operator

Unary operator

Conditional Operator Example 1: if (num % 2 == 0) System.out.println(num + “is even”); else System.out.println(num + “is odd”); Example 2: String result = (num % 2 == 0)? “ is even” : “ is odd” ; System.out.println(“The number ” + result); Example 3: System.out.println((num % 2 == 0)? num + “is even” :num + “is odd”);

Repetitions  while Loops  do-while Loops  for Loops

while Loop Flow Chart

false true Statement(s) Next Statement Continuation condition? while (continuation-condition) { // loop-body; }

do-while Loop

false true Statement(s) Next Statement Continue condition? do { // Loop body; } while (continue-condition);

for Loops

for (initial-action; loop-continuation-condition; action-after-each-iteration) { //loop body; } int i = 0; while (i < 100) { System.out.println("Welcome to Java! ” + i); i++; } Example: int i; for (i = 0; i < 100; i++) { System.out.println("Welcome to Java! ” + i); }

Caution Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below: for (int i=0; i<10; i++) ; { System.out.println("i is " + i); } Wrong