Professional Documents
Culture Documents
Session 5
Session 5
Session 5
rA
pt
ec
h
C
en
tre
U
se
O
Fundamentals of Java
nl
y
y
List the different types of loops
nl
O
Explain the while statement and the associated rules
se
Identify the purpose of the do-while statement
U
State the need of for statement
tre
Describe nested loops
en
Compare the different types of loops
C
State the purpose of jump statements
h
ec
Fo
nl
executed sequentially.
O
However, in certain situations, it is necessary to repeat certain steps to meet a
se
specified condition.
U
Following figure shows the program that displays the multiples of 10:
tre
en
C
h
ec
pt
nl
O
se
Loops enable programmers to develop
concise programs, which otherwise would
U
require thousands of program statements. do-
tre
while while
en
Loops consists of statement or a block of
C
statements that are repeatedly executed.
for-
h
for each
ec
pt
nl
O
is true.
se
It is used when the number of times the block has to be executed is not
U
known.
The syntax to use the while statement is as follows:
tre
Syntax
en
while (expression) {
C
h
// one or more statements
ec
}
pt
where,
rA
expression: Is a conditional expression which must return a boolean value, that is,
true or false.
Fo
The use of curly braces ({}) is optional and can be avoided, if there is only a single
statement within the body of the loop. However, providing statements within the curly
braces increases the readability of the code.
© Aptech Ltd. Looping Constructs/Session 5 5
y
Following figure shows the flow of execution of while loop:
nl
O
The body of the if loop
se
contains a set of statements.
U
tre
Statements will be executed
until the conditional expression
evaluates to true.
en
When the conditional C
h
expression evaluates to false,
ec
statement immediately
following the loop.
Fo
nl
O
se
public class PrintMultiplesWithWhileLoop {
/**
U
* @param args the command line arguments
*/
tre
public static void main(String[] args) {
// Variable, num acts as a counter variable
en
int num = 1;
// Variable, product will store the result
int product = 0;
C
h
ec
nl
while (num <= 5) {
product = num * 10;
O
System.out.printf(“\n %d * 10 = %d”, num, product);
num++; // Equivalent to n = n + 1
se
} // Moves the control back to the while statement
U
// Statement gets printed on loop termination
System.out.println(“\n Outside the Loop”);
tre
}
}
en
The conditional expression:
C
num <= 5 is evaluated at the beginning of the while loop. The loop is executed only if
the conditional expression evaluates to true.
h
In this case, as the value in the variable, num is less than 5, hence, the statements present in
ec
The first statement within the body of the loop calculates the product by multiplying
num with 10.
rA
nl
Following figure shows the output of the code:
O
se
U
tre
en
C
h
ec
pt
rA
Fo
nl
O
Such a loop is referred to as null statement loop.
se
Null statement loop:
U
There are no statements in the body of the loop.
tre
The loop is terminated with a semicolon.
Following code snippet demonstrates a code that prints the midpoint of two
en
numbers with an empty while loop:
C
public class TestWhileEmptyBody {
h
/**
ec
* @param args the command line arguments
*/
pt
int num1 = 1;
int num2 = 30;
Fo
O
// The statement executes after the while loop is completed
se
System.out.println(“Midpoint is: “ + num1);
}
U
}
tre
The value of num1 is incremented and the value of num2 is decremented.
en
The loop repeats till the value of num1 is equal to or greater than num2.
Thus, upon exit num1 will hold a value that is midway between the
C
original values of num1 and num2.
h
Following figure shows the output of the code:
ec
pt
rA
Fo
nl
The value of the variables used in the expression must be set once before
O
the execution of the loop. For example, num = 1;
se
The body of the loop must have an expression that changes the value of
U
the variable which is a part of the loop’s expression. For example,
num++; or num--;
tre
en
C
h
ec
pt
rA
Fo
nl
O
se
Following code snippet shows the implementation of an infinite loop using the
while statement:
U
tre
public class InfiniteWhileLoop {
/**
* @param args the command line arguments
en
*/
public static void main(String[] args) {
/*
C
* Loop begins with a boolean value true and is executed
h
* infinitely as the terminating condition is missing
ec
*/
while (true) {
pt
System.out.println(“Welcome to Loops...”);
} //End of the while loop
rA
}
}
Fo
The loop never terminates as the expression always returns a true value.
nl
O
se
The syntax to use the do-while statement is as follows:
U
Syntax
tre
do {
en
statement(s);
C
h
} while (expression);
ec
where,
pt
nl
O
For each iteration, the do-while loop first
se
executes the body of the loop and then, the
conditional expression is evaluated.
U
tre
When the conditional expression evaluates to
en
true, the body of the loop executes.
C
h
When the conditional expression evaluates to
ec
nl
the sum of 10 numbers:
O
se
public class SumOfNumbers {
/**
U
* @param args the command line arguments
*/
tre
public static void main(String[] args) {
int num = 1, sum = 0;
en
/**
* The body of the loop is executed first, then the condition is
* evaluated
*/ C
h
do {
ec
}
}
nl
respectively.
O
The loop block begins with a do statement.
se
The first statement in the body of the loop calculates the value of sum by
adding the current value of sum with num.
U
The next statement in the loop increments the value of num by 1.
tre
The condition, num <= 10, included in the while statement is evaluated.
en
If the condition is met, the instructions in the loop are repeated.
C
After the loop terminates, the value in the variable sum is printed.
h
Following figure shows the output of the code:
ec
pt
rA
Fo
O
se
• Used when the user knows the number of times the statements
U
need to be executed.
tre
• Statements within the body of the loop are executed as long as the
en
condition is true.
C
• Condition is checked before the statements are executed.
h
ec
pt
rA
Fo
nl
Syntax
O
se
for(initialization; condition; increment/decrement) {
U
// one or more statements
tre
}
where,
en
initialization: Is an expression that will set the initial value of the loop
control variable.
C
condition: Is a boolean expression that tests the value of the loop control
h
variable. If the condition expression evaluates to true, the loop executes, else
ec
terminates.
pt
variable (s) in each iteration, till the condition specified in the condition section is
reached. Typically, increment and decrement operators, such as ++, --, and
Fo
nl
O
The initialization expression is executed only
se
once, that is, when the loop starts.
U
Next, the boolean expression is evaluated and
tests the loop control variable against a targeted
tre
value.
en
If the expression is true, then the body of the
loop is executed and if the expression is false,
then the loop terminates. C
h
ec
nl
multiples of 10:
O
public class PrintMultiplesWithForLoop {
/**
se
* @param args the command line arguments
*/
U
public static void main(String[] args) {
int num, product;
tre
// The for Loop with all the three declaration parts
en
for (num = 1; num <= 5; num++) {
product = num * 10;;
C
System.out.printf(“\n % d * 10 = % d “, num, product);
} // Moves the control back to the for loop
h
}
}
ec
In the initialization section of the for loop, the num variable is initialized to 1.
pt
The condition statement, num <= 5, ensures that the for loop executes as long as
rA
Finally, the loop terminates when the condition becomes false, that is, when the
value of num becomes equal to 6.
© Aptech Ltd. Looping Constructs/Session 5 21
y
Following figure shows the output of the code:
nl
O
se
U
tre
en
C
h
ec
pt
rA
Fo
nl
Are used within the for loops and may not be used further in the
O
program.
se
It is possible to restrict the scope of variables by declaring them at the
U
time of initialization.
Following code snippet declares the counter variable inside the for
tre
statement:
en
public class ForLoopWithVariables {
/**
C
* @param args the command line arguments
h
*/
ec
int product;
rA
nl
product = num * 10;;
O
System.out.printf(“\n % d * 10 = % d “, num, product);
se
} // End of the for loop
}
U
}
tre
In the code, the variable num has been declared inside the for statement.
This restricts the scope of the variable, num to the for statement and
en
nl
O
se
Expressions are separated by using the ‘comma’ (,) operator.
U
Expressions are evaluated from left to right.
tre
The order of the evaluation is important, if the value of the second
en
Following code snippet demonstrates the use of for loop to print the
C
addition table for two variables using the ‘comma’ operator:
h
public class ForLoopWithComma {
ec
/**
pt
nl
* The initialization and increment/decrement section includes
* more than one variable
O
*/
for (i = 0, j = max; i <= max; i++, j--) {
se
System.out.printf(“\n%d + %d = %d”, i, j, i + j);
}
U
}
}
tre
en
Three integer variables i, j, and max are declared.
The variable max is assigned a value 10. The i variable is assigned a value of
C
0 and j is assigned the value of max, that is, 10. Thus, two parameters are
h
initialized using a ‘comma’ operator.
ec
The condition statement, i <= max, ensures that the for loop executes as
pt
Finally, the iteration expression again consists of two expressions, i++, j--.
After each iteration, i is incremented by 1 and j is decremented by 1.
Fo
The sum of these two variables which is always equal to max is printed.
nl
O
se
U
tre
en
C
h
ec
pt
rA
Fo
nl
Tested with the targeted values, but, it can also be used for testing
O
boolean expressions.
se
Alternatively, the initialization or the iteration section in the for loop may be
left empty, that is, they need not be present in the for loop.
U
Following code snippet demonstrates the use of for loop without the
tre
initialization expression:
en
public class ForLoopWithNoInitialization {
C
public static void main(String[] args) {
h
/*
ec
int num = 1;
rA
/*
* Boolean variable initialized to false
Fo
*/
boolean flag = false;
nl
* The for loop starts with num value 1 and continues till value of
* flag is not true
O
*/
for (; !flag; num++) {
se
System.out.println(“Value of num: “ + num);
if (num == 5) {
U
flag = true;
}
tre
} // End of for loop
}
en
The for loop in the code continues to execute till the value of the variable
flag is set to true.
C
h
Following figure shows the output of the code:
ec
pt
rA
Fo
nl
The infinite for loop will run continuously because there is no terminating
O
condition.
se
Following code snippet demonstrates the code for the infinite for loop:
U
.....
tre
for( ; ; ) {
System.out.println(“This will go on and on”);
en
}
.....
C
The code will print ‘This will go on and on’ until the loop is
h
ec
terminated manually.
Infinite loops make the program run indefinitely for a long time resulting in
pt
nl
array.
O
It is also used to iterate over the elements of the collection objects, such as
se
ArrayList, LinkedList, HashSet, and so on defined in the collection
framework.
U
It continues till all the elements from a collection are retrieved.
tre
The syntax for using the enhanced for loop is as follows:
en
Syntax
C
for (type var: collection) {
h
// block of statement
ec
}
pt
where,
rA
var: Is an iteration variable that stores the elements from the collection.
nl
object using enhanced for loop and its equivalent for loop:
O
se
for Loop Enhanced for Loop
U
type var; for (type var : arr)
for (int i = 0; i < arr. length; i++) {
tre
{ . . .
var = arr[i]; // Body of the loop
en
. . , . . .
} }
C
h
ec
pt
rA
Fo
nl
O
There can be any number of combinations between the three types of loops.
se
The most commonly nested loops are formed by for statements which can
be nested within another for loop forming nested-for loop.
U
Following code snippet demonstrates the use of a nested-for loop for
tre
displaying a pattern:
en
public class DisplayPattern {
/**
C
* @param args the command line arguments
h
*/
ec
nl
* For each iteration, the inner for loop will execute from col = 1
* and will continue, till the value of col is less than or equal to row
O
*/
for (col = 1; col <= row; col++) {
se
System.out.print(“ * “);
} // End of inner for loop
U
System.out.println();
tre
} // End of outer for loop
}
en
}
C
The outer for loop starts with the counter variable row whose initial value is
h
set to 1.
ec
As the condition, row < 5 is evaluated to true, the body of the outer for
pt
The body contains an inner for loop which starts with the counter variable’s
value col set to 1.
Fo
nl
equal to the value of row variable.
O
Once the value of col is greater than row, the inner for loop terminates.
se
For each iteration of the outer loop, the inner for loop is reinitialized and
continues till the condition evaluates to false.
U
Following figure shows the output of the code:
tre
en
C
h
ec
pt
rA
Fo
nl
loops:
O
se
while/for do-while
U
Loop is pre-tested. The condition Loop is post-tested. The condition is
is checked before the statements checked after the statements within the
tre
within the loop are executed. loop are executed.
en
The loop does not get executed if The loop gets executed at least once
C
the condition is not satisfied at even if the condition is not satisfied at
the beginning. the beginning.
h
ec
pt
rA
Fo
U
are used within loops to change the flow of control based on
tre
conditions.
en
C
h
ec
pt
rA
Fo
nl
It forces immediate termination of a loop, bypassing the loop’s normal
O
conditional test.
se
When the break statement is encountered inside a loop, the loop is
U
immediately terminated and the program control is passed to the statement
following the loop.
tre
If used within a set of nested loops, the break statement will terminate the
en
innermost loop.
Following code snippet demonstrates the use of break statement:
C
/**
* @param args the command line arguments
pt
*/
rA
nl
// Scanner class is used to accept data from the keyboard
Scanner input = new Scanner(System.in);
O
System.out.println(“Enter a number: “);
number = input.nextInt();
se
if (number == 0) {
U
// break statement terminates the loop
break;
tre
} // End if statement
} // End of for statement
en
}
}
variable, number.
C
In the code, the user is prompted to enter a number, and this is stored in the
h
ec
However, if the user enters the number zero, the loop terminates and the
pt
nl
O
se
U
tre
en
C
h
ec
pt
rA
Fo
nl
loop.
O
In while and do-while loops, a continue statement transfers the
se
control to the conditional expression which controls the loop.
Following code snippet demonstrates the code that uses continue
U
tre
public class NumberRoot {
en
/**
* @param args the command line arguments
*/
C
public static void main(String[] args) {
h
int cnt, square, cube;
ec
if (cnt % 3 == 0) {
continue;
}
Fo
nl
cube = cnt * cnt * cnt;
System.out.printf(“\nSquare of %d is %d and Cube is %d”, cnt, square,
O
cube);
} // End of the for loop
se
}
}
U
The code declares a variable cnt and uses the for statement which contains the
tre
initialization, termination, and increment expression.
The value of cnt is divided by 3 and the remainder is checked.
en
If the remainder is 0, the continue statement is used to skip the rest of the
C
statements in the body of the loop.
h
If remainder is not 0, the if statement evaluates to false, and the square and cube
ec
rA
Fo
nl
referred to as labeled statements.
O
Labeled Statements:
se
Are expanded forms that can be used within any block that must be part of a loop
or a switch statement.
U
Can be used to precisely specify the point from which the execution should
tre
resume.
Can be used to exit from a set of nested blocks.
en
break label;
where,
pt
rA
nl
O
public class TestLabeledBreak {
/**
se
* @param args the command line arguments
*/
U
public static void main(String[] args) {
int i;
tre
outer:
en
for (i = 0; i < 5; i++) {
if (i == 2) {
C
System.out.println(“Hello”);
// Break out of outer loop
h
break outer; }
ec
System.out.println(“This is the outer loop.”);
}
pt
System.out.println(“Good - Bye”);
rA
}
}
Fo
nl
The first two times it displays the sentence ‘This is the outer loop’.
O
In the third round of iteration the value of i is set to 2 and prints ‘Hello’.
se
Next, the break statement is encountered and the control passes to the
U
label named outer:.
tre
Thus, the loop terminates and the last statement is printed.
Following figure shows the output of the code:
en
C
h
ec
pt
rA
Fo
nl
Similar to labeled break statement, you can specify a label to enclose a
O
loop that continues with the next iteration of the loop.
se
This is done using labeled continue statement.
U
Following code snippet demonstrates the use of labeled continue
statement:
tre
public class NumberPyramid {
en
/**
* @param args the command line arguments
*/
C
public static void main(String[] args) {
h
ec
outer:
for (int i = 1; i < 5; i++) {
pt
System.out.println();
/* Terminates the loop counting j and continues the
* next iteration of the loop counting I */
Fo
continue outer;
} // End of if statement
nl
} // End of inner for loop
System.out.println(“\nThis is the outer loop.”);
O
} //End of outer for loop
System.out.println(“Good-Bye”);
se
}
}
U
tre
Following figure shows the output of the code:
en
C
h
ec
pt
rA
Fo
nl
O
The loop statements supported by Java are namely, while, do-while, and for.
se
The while loop is used to execute a statement or a block of statements until
U
the specified condition is true.
The do-while statement checks for condition at the end of the loop rather
tre
than at the beginning to ensure that the loop is executed at least once.
en
The for loop is especially used when the user knows the number of times the
statements need to be executed in the code block of the loop. The three parts
C
of for statement are initialization, condition, increment/decrement.
h
The placing of a loop in the body of another loop is called nesting.
ec
Java provides two keywords namely, break and continue that serve diverse
pt
purposes. However, both are used with loops to change the flow of control.
rA
Fo