Object Oriented
Programming
Techniques
Prepared By: Umm-e-Laila & Aneeta Siddiqui
Lecture
Assistant 4: Loops and Logic
Professor
CED
1
Control Flow Statements
Use control flow statements in programs to:
conditionally execute statements,
repeatedly execute a block of statements,
change the normal, sequential flow of control.
2
Writing Loops
Loops
Repeated execution of one or more statements
until a terminating condition occurs
Pre-test and post-test loops
Types of loops: true
false
Pre-test loops
while
for
foreach (will cover in Arrays)
Post-test loop
do…while
3
for
The for statement is most commonly used to step through
an integer variable in equal increments
It begins with the keyword for, followed by three expressions in
parentheses that describe what to do with one or more controlling
variables
The first expression tells how the control variable or variables are
initialized or declared and initialized before the first iteration
The second expression determines when the loop should end, based on
the evaluation of a Boolean expression before each iteration
The third expression tells how the control variable or variables are
updated after each iteration of the loop body
The body may consist of a single statement or a list of statements
enclosed in a pair of braces ({ })
Initialize the
for (initialization; boolean_expression; update) { control variable
fals
Statements_Body;
e
} update
Almost like in Java, but true
you can have more statement(s)
than one loop variable!
4
The for Statement (I)
The for statement provides a compact way to iterate over a
range of values. The general form of the for statement can
be expressed like this:
The initialization is an expression that initializes the loop-it's
executed once at the beginning of the loop.
The termination expression determines when to terminate
the loop.
The increment is an expression that gets invoked after each
iteration through the loop.
5
The for Statement (II)
Often for loops are used to iterate over the elements
in an array, or the characters in a string. The
following sample, ForDemo, uses a for statement to
iterate over the elements of an array and print them:
public class ForLoop
{
public static void main(String[] args)
{ int limit = 20; // Sum from 1 to this value
int sum = 0; // Accumulate sum in this variable
// Loop from 1 to the value of limit, adding 1 each cycle
for(int i = 1; i <= limit; i++)
sum += i; // Add the current value of i to sum
System.out.println("sum = " + sum);
}
}
6
The for Statement (III)
public class ForLoop
{ public static void main(String[] args)
{
int limit = 20; // Sum from 1 to this value
int sum = 0; // Accumulate sum in this variable
// Loop from 1 to the value of limit, adding 1 each cycle
for(double radius = 1.0; radius <= 2.0; radius += 0.2)
{
System.out.println("radius = " + radius + " area = " +
Math.PI*radius*radius);
}
}
}
7
while Just like
in Java!
The while statement is used to repeat a portion of code (i.e.,
the loop body) based on the evaluation of a Boolean
expression
The Boolean expression is checked before the loop body is executed
When false, the loop body is not executed at all
Before the execution of each following iteration of the loop body, the
Boolean expression is checked again
If true, the loop body is executed again
If false, the loop statement ends
The loop body can consist of a single statement, or multiple
statements enclosed in a pair of braces ({ })
while (boolean_expression) {
false
Statement_1; whil
Statement_2; e
. . . true
Statement_Last;
}
etc.
The while and do-while
Statements (II)
public class WhileLoop
{
public static void main(String[] args)
{
int limit = 20; // Sum from 1 to this value
int sum = 0; // Accumulate sum in this variable
int i = 1; // Loop counter
// Loop from 1 to the value of limit, adding 1 each cycle
while(i <= limit)
sum += i++; // Add the current value of i to sum
System.out.println("sum = " + sum);
}
}
9
do-while Just like
in Java!
The do-while statement is used to execute a portion of
code (i.e., the loop body), and then repeat it based on
the evaluation of a Boolean expression
The loop body is executed at least once
The Boolean expression is checked after the loop body is executed
The Boolean expression is checked after each iteration of the
loop body
If true, the loop body is executed again false
do { whil
If false, the loop statement ends
Statement_1; e
Statement_2; true
. . .
Statement_Last;
} while (boolean_expression);
10
The while and do-while
Statements (III)
The Java programming language provides
another statement that is similar to the while
statement--the do-while statement. The general
syntax of the do-while is:
Instead of evaluating the expression at the top of
the loop, do-while evaluates the expression at the
bottom. Thus the statements associated with a do-
while are executed at least once.
11
The while and do-while
Statements (IV)
public class DoWhileLoop
{
public static void main(String[] args)
{
int limit = 20; // Sum from 1 to this value
int sum = 0; // Accumulate sum in this variable
int i = 1; // Loop counter
// Loop from 1 to the value of limit, adding 1 each cycle
do
{ sum += i; // Add the current value of i to sum
i++;
} while(i <= limit);
System.out.println("sum = " + sum);
}
}
12
Nested Loops
Loop can be nested
When nested, the inner loop iterates from beginning to
the end for each single iteration of the outer loop
There is no limit in how many levels you can nest loops.
It is usually not more than three levels.
Examples 1 2 3 4
Multiplication table 2 4 6 8
row =3, col = 4 3 6 9 12
for( int i = 1; i <= row; i ++) {
for (int j = 1; j <= col; j++) {
System.out.println ( (i * j) < 10 ? " " +i *j : " " + i *
j);
} 3 spaces if <10 else 2
System.out.println (); // Print blank line
}
for( int i = 0; i < row; i ++) { for( int i = 0; i < row; i ++) {
for (int j = 0; j < row; j++) { for (int j = 0; j <= i; j++) {
System.out.println ("*"); System.out.println ("*");
} *** } *
System.out.println (); *** System.out.println (); **
} *** } ***
13
Nested Loops
public class Factorial
{
public static void main(String[] args)
{
long limit = 20; // Calculate factorial of integers up to this value
long factorial = 1; // Calculate factorial in this variable
// Loop from 1 to the value of limit
for(int i = 1; i <= limit; i++)
{
factorial = 1; // Initialize factorial
int j =2;
while(j <= i)
factorial *= j++;
System.out.println(i + "!" + " is " + factorial);
} }}
14
break & continue
The break statement terminates the closest enclosing loop or switch statement in
which it appears.
Control is passed to the statement that follows the terminated loop (or switch), if any.
for( int i = 0; i < row; i ++) {
for (int j = 0; j < row; j++) {
if ( i+j >= row )
break; *** For row=3
System.out.println("*"); **
} *
System.out.println ();
}
The continue statement passes control to the next iteration of the enclosing
iteration statement in which it appears.
It must be enclosed by a while, do, for, or foreach statement
It applies only to the innermost statement in nested iteration statements
for (int i= 1; i <= row; i++ ) { i = 1
if( i % 2 == 0) i = 3
continue; // Go back to for
System.out.println("i = " + i );
}
15
Decision-Making Statements
Decision-Making statements evaluate conditions and
execute statements based on that evaluation
C# includes two decision-making statements:
If statement Just like
Evaluates an expression in Java!
Executes one or more statements if expression is true
Can execute another statement or group of statements if expression is
false
Switch statement
Evaluates a variable for multiple values
Executes a statement or group of statements, depending on contents
of the variable being evaluated
True
Condition
Flow chart of
a typical False
decision Conditional
structure Code 16
Switch
if (Boolean_Expression)
Just like
Statement_1;
in Java!
else if (Boolean_Expression_n)
Statement_n;
else
Switch Statement;
Acts like a multiple-way if statement
Transfers control to one of several statements, depending on the value of an
expression
No two case statements can have the same value.
Value must be an integer or a string
Execution of the statement body begins at the selected statement and proceeds until
the break statement transfers control out of the case body
Implicit fall through from one case to another if a case statement has no code.
The default statement is optional
switch (n) {
case value1: True Statement(s)
C1
statement1; 1
break; False
case value2: Implicit fall
case value3: through True Statement(s)
C2 2
statement2;
break; False
... True Statement(s)
default: C3 3
statementn;
False
break;
} 17
Shortcut if-else Statement
The ?: operator is a conditional operator that
is short-hand for an if-else statement:
op1 ? op2 : op3
The ?: operator returns op2 if op1 is true or
returns op3 if op1 is false.
18
The if-else statement (I)
The if statement enables your program to
selectively execute other statements, based on
some criteria.
Generally, the simple form of if can be written
like this:
19
if & if-else Just like
in Java!
if
true
The if statement
The block governed by it is executed if a condition is true
The Boolean_Expression must be enclosed in parentheses etc.
The statement_when_true branch of an if can be a made up of a single statement or a
compound statement
Note:
A compound statement is made up of a list of statements and must always be enclosed in a pair of
braces ({ })
if (boolean_expression) if (boolean_expression) {
statement_when_true; statementS_when_true;
...
}
The If-else statement
It is two-way selection.
The else block is executed if the if part is false.
Again, the statements_when_true or statements_when_false can be a made of a
single statement or many statements.
if (boolean_expression){ if-else
if (boolean_expression)
statements_when_true;
statement_when_true;
... true fals
else e
} else {
statement_when_false;
statements_when_false;
...
} 20
etc.
The if-else statement (II)
Suppose that your program needs to perform
different actions depending on whether the user
clicks the OK button or another button in an alert
window. Your program could do this by using an if
statement along with an else statement:
21
The if-else statement (III)
Following is a program, IfElseDemo, that assigns
a grade based on the value of a test score: an A
for a score of 90% or above, a B for a score of
80% or above, and so on:
22
The if-else statement (IV)
The output from this program is:
Grade = C
23
Nested If
public class NumberCheck
{
public static void main(String[] args)
{
int number = 0;
number = 1+(int)(100*Math.random()); // Get a random integer between 1 & 100
if(number%2 == 0) // Test if it is even
{
if(number < 50) // Output a message if number is < 50
System.out.println("You have got an even number < 50, " + number);
}
else
System.out.println("You have got an odd number, " + number); // It is odd
}
}
24