0% found this document useful (0 votes)
311 views9 pages

If and Loop

The document discusses different types of control structures in Java programming including decision and repetition control structures. It describes if, if-else, if-else-if statements which allow conditional execution of code blocks based on boolean expressions. It also covers the switch statement which allows branching based on multiple outcomes. For repetition, it explains while, do-while, and for loops which allow executing code blocks a specified number of times. Key guidelines are provided for proper usage of these control structures to avoid common errors. Examples are also given to demonstrate each type of control structure.

Uploaded by

lorei
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
311 views9 pages

If and Loop

The document discusses different types of control structures in Java programming including decision and repetition control structures. It describes if, if-else, if-else-if statements which allow conditional execution of code blocks based on boolean expressions. It also covers the switch statement which allows branching based on multiple outcomes. For repetition, it explains while, do-while, and for loops which allow executing code blocks a specified number of times. Key guidelines are provided for proper usage of these control structures to avoid common errors. Examples are also given to demonstrate each type of control structure.

Uploaded by

lorei
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

The if-statement has the form,

5 Control Structures
5.1 Objectives
In the previous sections, we have given examples of
sequential programs, wherein statements are executed one
after another in a fixed order. In this section, we will be
discussing control structures, which allows us to change
the ordering of how the statements in our programs are
executed.
At the end of the lesson, the student should be able to:
Use decision control structures (if, else, switch) which
allows selection of specific sections of code to be
executed
Use repetition control structures (while, do-while,
for) which allow executing specific sections of code
a number of times

5.2 Decision Control Structures


Decision control structures are Java statements that allows
us to select and execute specific blocks of code while
skipping other sections.

if( boolean_expression )
statement;
or
if( boolean_expression ){
statement1;
statement2;
. . .
}
where, boolean_expression is either a boolean expression or
boolean variable.
For example, given the code snippet,
int grade = 68;
if( grade > 60 )
System.out.println("Congratulations!");

or
int grade = 68;
if( grade > 60 ){
System.out.println("Congratulations!");
System.out.println("You passed!");
}

5.2.1 if statement
The if-statement specifies that a statement (or block of
code) will be executed if and only if a certain boolean
statement is true.
1

Coding Guidelines:
1. The boolean_expression part of a statement should
evaluate to a boolean value. That means that the
execution of the condition should either result to a
value of true or a false.
2. Indent the statements inside the if-block.For
example,

or can also be written as,


if( boolean_expression ){
statement1;
statement2;
. . .
}
else{
statement1;
statement2;
. . .
}

if( boolean_expression ){
//statement1;
//statement2;
}

For example, given the code snippet,


5.2.2 if-else statement
The if-else statement is used when we want to
execute a certain statement if a condition is true, and
a different statement if the condition is false.
The if-else statement has the form,

int grade = 68;


if( grade > 60 )
System.out.println("Congratulations!");
else
System.out.println("Sorry you failed");

or

if( boolean_expression )
statement;
else
statement;

int grade = 68;


if( grade > 60 ){
System.out.println("Congratulations!");
System.out.println("You passed!");
}
else{
System.out.println("Sorry you failed");
}
3

Coding Guidelines:
1. To avoid confusion, always place the statement or
statements of an if or if-else block inside brackets
{}.
2. You can have nested if-else blocks. This means that
you can have other if-else blocks inside another ifelse block. For example,
if( boolean_expression ){
if( boolean_expression ){
. . .
}
}
else{
. . .
}
5.2.3 if-else-if statement
The statement in the else-clause of an if-else block can be
another if-else structures.
This cascading of structures allows us to make more
complex selections.

Take note that you can have many else-if blocks after an ifstatement. The else-block is optional and can be omitted. In
the example shown above, if boolean_expression1 is true,
then the program executes statement1 and skips the other
statements. If boolean_expression2 is true, then the program
executes statement 2 and skips to the statements following
statement3.
For example, given the code snippet,
int grade = 68;
if( grade > 90 ){
System.out.println("Very good!");
}
else if( grade > 60 ){
System.out.println("Good!");
}
else{
System.out.println("Sorry you failed");
}

5.2.4 Common Errors when using the if-else


statements:

The if-else if statement has the form,


if( boolean_expression1 )
statement1;
else if( boolean_expression2 )
statement2;
else
statement3;

1. Using = instead of == for comparison. For example,


//WRONG
int number = 0;
if( number = 0 ){
//some statements here
}
5

5.2.6 switch statement


Another way to indicate a branch is through the switch
keyword. The switch construct
allows branching on multiple outcomes.
The switch statement has the form,

This should be written as,


//CORRECT
int number = 0;
if( number == 0 ){
//some statements here
}

switch( switch_expression ){
case case_selector1:
statement1;
statement2; //block 1
. . .
break;
case case_selector2:
statement1;
statement2; //block 2
. . .
break;
. . .
default:
statement1;
statement2; //block n
. . .
}

2. Writing elseif instead of else if.


5.2.5 Example for if-else if-else (try this)
public class GradeIf{
public static void main( String[] args ){
double grade = 92.0;
if( grade >= 90 ){
System.out.println( "Excellent!" );
}
else if( (grade < 90) && (grade >= 80)){
System.out.println("Good job!" );
}
else if( (grade < 80) && (grade >= 60)){
System.out.println("Study harder!" );
}
else{
System.out.println("Sorry, you
failed.");
}
}
}

where, switch_expression is an integer or character


expression and, case_selector1, case_selector2 and so on,
are unique integer or character constants.
When a switch is encountered, Java first evaluates the
switch_expression, and jumps to the case whose selector
matches the value of the expression. The program executes
7

the statements in order from that point on until a break


statement is encountered, skipping then to the first statement
after the end of the switch structure.

an integer or character value. Also, the value


provided to each case statement must be unique.
5.2.7 Example for switch (try this)

If none of the cases are satisfied, the default block is


executed. Take note however, that the default part is optional.
A switch statement can have no default block.
NOTES:
Unlike with the if statement, the multiple statements
are executed in the switch statement without
needing the curly braces.
When a case in a switch statement has been
matched, all the statements associated with that
case are executed. Not only that, the statements
associated with the succeeding cases are also
executed.
To prevent the program from executing statements
in the subsequent cases, we use a break statement
as our last statement.
Coding Guidelines:
1. Deciding whether to use an if statement or a switch
statement is a judgment call. You can decide which to
use, based on readability and other factors.
2. An if statement can be used to make decisions
based on ranges of values or conditions, whereas
a switch statement can make decisions based only on
9

public class GradeSwitch{


public static void main( String[] args ){
int grade = 92;
switch(grade){
case 7:
System.out.println( "Grade 7" );
break;
case 8:
System.out.println("Grade 8" );
break;
case 9:
System.out.println("Grade 9" );
break;
case 10:
System.out.println("Grade 10" );
break;
default:
System.out.println("Invalid Level");
}
}
}

10

5.3 Exercises
Number in words
Class Name: NumberWords
Get a number as input from the user, and output the
equivalent of the number in words. The number inputted
should range from 1-10. If the user inputs a number that is not
in the range, output, "Invalid number".
1. Use an if-else statement to solve this problem
2. Use a switch statement to solve this problem
Apples
Class Name: Apples
Apple Co is one of the most leading apple company in
Magnolia. Because of the growing number of customers
buying their product, they want you to create a program that
will ask for the number of apples (in pieces) then compute for
the total amount to pay. Display the price per apple and the
total amount to pay. Apples are sold according to the
following: (1box = 3doz)
1 50pcs
540.00/box
51-100pcs
450.00/box
More than 100pcs
360.00/box
*input is in integer

5.4 Repetition Control Structures

times. There are three types of repetition control structures,


the while, do-while and for loops.

5.4.1 while loop


The while loop is a statement or block of statements that is
repeated as long as some condition is satisfied.
The while statement has the form,
while( boolean_expression ){
statement1;
statement2;
. . .
}
The statements inside the while loop are executed as long
as the boolean_expression evaluates to true.
For example, given the code snippet,
int i = 4;
while ( i > 0 ){
System.out.print(i);
i--;
}

Repetition control structures are Java statements that


allows us to execute specific blocks of code a number of

The sample code shown will print 4321 on the screen. Take
note that if the line containing the statement i--; is removed,

11

12

this will result to an infinite loop, or a loop that does not


terminate. Therefore, when using while loops or any kind of
repetition control structures, make sure that you add some
statements that will allow your loop to terminate at some point.

The main difference between a while and do-while loop is


that, the statements inside a do-while loop are executed at
least once.
The do-while statement has the form,

The following are other examples of while loops,


do{
Example 1:
int x = 0;
while (x<10){
System.out.println(x);
//x++;
}

statement1;
statement2;
. . .
}while( boolean_expression );
The statements inside the do-while loop are first executed,
and then the condition in the boolean_expression part is
evaluated. If this evaluates to true, the statements inside the
do-while loop are executed again.
Here are a few examples that uses the do-while loop:
Example 1:
int x = 0;
do
{
System.out.println(x);
x++;
}while (x<10);

Example 2:
//infinite loop
while(true)
System.out.println(hello);
Example 3:
//no loops
// statement is not even executed
while (false)
System.out.println(hello);
5.4.2 do-while loop
The do-while loop is similar to the while-loop. The statements
inside a do-while loop are executed several times as long as
the condition is satisfied.
13

This example will output 0123456789 on the screen.

14

Example 2:
//infinite loop
do{
System.out.println(hello);
} while (true);

5.4.3 for loop


The for loop, like the previous loops, allows execution of the
same code a number of times.

This example will result to an infinite loop, that prints


hello on screen.

for (InitializationExpression;
LoopCondition; StepExpression){
statement1;
statement2;
. . .
}

The for loop has the form,

Example 3:
//one loop
// statement is executed once
do
System.out.println(hello);
while (false);

where,

This example will output hello on the screen.


Coding Guidelines:
1. Common programming mistakes when using the dowhile loop is forgetting to write the semi-colon after
the while expression.
do{

InitializationExpression -initializes the loop


variable.
LoopCondition - compares the loop variable to
some limit value.
StepExpression - updates the loop variable.
A simple example of the for loop is,
int i;
for( i = 0; i < 10; i++ ){
System.out.print(i);
}

...
}while(boolean_expression)
//WRONG-forgot semicolon ;

2. Just like in while loops, make sure that your do-while


loops will terminate at some point
15

In this example, the statement i=0, first initializes our variable.


After that, the condition expression i<10 is evaluated. If this
16

evaluates to true, then the statement inside the for loop is


executed. Next, the expression i++ is executed, and then the
condition expression is again evaluated. This goes on and
on, until the condition expression evaluates to false.

Largest and Smallest


Class Name: LargestSmallest
Create a program that will ask for 10 numbers then identify
the largest and smallest number.

This example, is equivalent to the while loop shown below,


int i = 0;
while( i < 10 ){
System.out.print(i);
i++;
}
5.5 Exercises
Powers
Class Name: Powers
Compute the power of a number given the base and
exponent. Do three versions of this program using a while
loop, a do-while loop and a for-loop.
Odd Summation
Class Name: OddSummation
Given a range of numbers (from a to b), compute for the
summation of all odd numbers. For example, the summation
of all the odd integers in the range 3 to 9 is 3 + 5 + 7 + 9 = 24.

17

18

You might also like