11
Program Structures Chapter 5

Chapter 05

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Chapter 05

Program Structures

Chapter 5

Page 2: Chapter 05

5

BranchingAllows different code to execute based on a conditional test.if, if-else, and switch statements

Page 3: Chapter 05

5

If, Else, and Else-Ifif Statements

“If the sky is blue, I’ll ride my bike.”

else Statements“If the sky is red, I’ll drive; else (otherwise) I’ll ride my bike.”

Else-if Idioms“If the sky is blue, I’ll ride my bike; else if the sky is red, I’ll drive, else I’ll walk.”

Page 4: Chapter 05

5

Nested if Statementsif statements can be nested (combined) within other if statements to account for multiple conditions.

If the sky is blueIf there are clouds in the sky

Do something for blue sky, cloudy days

ElseDo something for blue sky, cloudless days

ElseDo something for non-blue sky days

Page 5: Chapter 05

5

The switch Statementswitch statements are an efficient way to choose between multiple options.

Easier to expand options than else-if structuresEasier to read than multiple else-if structuresUse the break keyword to prevent “falling through” to next statement

Page 6: Chapter 05

5

Switch Evaluationswitch statements evaluate int values:

int x = 3;switch(x){ 1: x += 2; break; 2: x *= 2; break; 3: x /= 2; break;}

Page 7: Chapter 05

5

Logical OperatorsCombine or negate conditional tests

Logical AND (&&)“The value of x is greater than 10 and the value of x is less than 20”(x > 10) && (x < 20);

Logical OR (||)“The value of x is greater than 10 or the value of x is lessthan 5”(x > 10) || (x < 5);

Logical NOT (!)“The value of x is not greater than 10”! (x > 10);

Page 8: Chapter 05

5

LoopingWhat is iteration?

Iteration is a structure that repeats a block of code a certain number of times, or until a certain condition is met.

Page 9: Chapter 05

5

The while Loop“As long as this condition is true,

execute this code”while ( counter < 11){ counter++;}

Might not execute if the condition is already false

Page 10: Chapter 05

5

The for LoopIncludes (optional) arguments for:

An initialization variable

A conditional test

An action

for ( int counter = 1; counter < 11; counter++ )

{

System.out.print(counter + “ ”)

}

Page 11: Chapter 05

5

The do...while Loop“Take this action, while this is true”

int value = 10;do{ value = value + 2;}while ( value < 10 );

Ensures at least one execution of code