Outline Iteration and Algorithms The while loop The for loop

advertisement
Outline
•
•
•
•
Iteration and Algorithms
The while loop
The for loop
The do while loop
Iteration and Algorithms
• We have seen that flow control has three
types:
– Sequential
– Selection
– Iteration
• In the third control, a statement(s) will be
repeated a number of times based on a
criteria (condition)
Iteration and Algorithms
• Assume that we want to find the sum of
numbers from 1 to n
• Algorithm
– sum = 0
– index = 1
– while index <= n
• sum = sum + index
• index = index + 1
The while loop
• This loop is precondition loop or 0-trip loop.
• The general structure is
while (condition)
statement
• The condition is evaluated first. Statement is
executed if condition is true. The condition is
evaluated again and so on till the condition
evaluates to false.
The while loop (cont’d)
condition
true
statement
false
Example
public static int sum1toN(int n)
{
int sum = 0, index = 1;
while ( index <= n )
{
sum += index;
index++;
}
return sum;
}
Notes about while
• when using the while loop notice the
following:
– use braces if more than one statement to be
repeated
– initialize the variable used in the condition
before the loop
– update the variable inside the loop
The for loop
• This loop is precondition loop or 0-trip loop.
• The general structure is
for (initialization; condition; update)
statement
• First the initialization is executed once. The
condition is evaluated next. If the condition is true
the statement is executed if followed by the
update. The condition is then executed again and
so on till the condition evaluates to false.
The for loop (cont’d)
for (initialization; condition; update)
statement
initialization
condition
true
statement
update
false
Example
public static int sum1toN(int n)
{
int sum = 0, index = 1;
for ( index = 1; index <= n; index++)
sum += index;
return sum;
}
The do while loop
• This loop is post condition loop or 1-trip loop.
• The general structure is
do
statement
while (condition);
• The statement is executed first. The condition is
evaluated next. If the condition is true, the
statement is executed again and so on till the
condition evaluates to false.
The do while loop (cont’d)
statement
true
condition
false
Example
public static int sum1toN(int n)
{
int sum = 0, index = 1;
do
{
sum += index;
index++;
}while ( index <= n );
return sum;
}
Nested Loops
• Loops can be nested and will be executed
such that for every iteration of the outer
loop, all the iterations of the inner loop.
• The inner loop must be completely inside
the outer loop.
• Loop indexes must be different.
Example
public static void multiplicationTable(int n)
{
int row, col;
for (row = 1; row <= n; row++)
{
for (col =1; col <= n; col++)
System.out.print(row*col + “\t”);
System.out.println( );
}
}
Download