Loops and Logic
Loops and Logic
Programming
Techniques
Prepared By: Umm-e-Laila & Aneeta Siddiqui
Lecture
Assistant 4: Loops and Logic
Professor
CED
1
Control Flow Statements
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
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
7
while Just like
in Java!
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
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:
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
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
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
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
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
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)
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
24