Download week-8-lec-1_2-ch04_control-structure-loops

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Series (mathematics) wikipedia , lookup

Mathematics of radio engineering wikipedia , lookup

Addition wikipedia , lookup

Location arithmetic wikipedia , lookup

Transcript
Chapter 4: Control Structures
REPETITION-COUNTER
CONTROL LOOP
Why Is Repetition Needed?
How can you solve the following problem:
 What is the sum of all the numbers from 1
to 100.
 The answer will be
1 + 2 + 3 + 4 + 5 + 6 + … + 99 + 100.
Why Is Repetition Needed?
Here’s some sample Java code:
int sum=0;
sum = sum+1;
sum = sum +2;
sum = sum +3;
sum = sum +4;
…
sum = sum +99;
sum = sum +100;
System.out.println(“The sum from 1 to 100 = “
+sum);
Why Is Repetition Needed?
This solution has problems:
 It would take a long time to type in.
 There is a high risk of making an error
while typing it in.
 It doesn’t easily scale. This may work for
100 numbers but how would you handle
having to add from 1 to a 1000? Or to
1000000?Or to 1000000000?
Why Is Repetition Needed?
The Algorithm
1.
2.
3.
4.
5.
6.
7.
8.
9.
Create a variable to hold the sum.
Initialize the sum to zero.
Create a variable to hold a counter from 1 to 100.
Initialize the counter to 1.
While the counter is less-than-or-equal to 100
add the counter to the sum
add one to the counter
Now repeat
Print the sum
Why Is Repetition Needed?
We can use pseudo-code:
sum = 0
count = 1
loop while count <= 100
sum = sum + count
count++
endloop
print sum
Why Is Repetition Needed?
loop while condition
<body>
endloop

This pseudo-code means: before executing the
statements in the body, evaluate the condition. If the
condition is true then execute the body once.

Once you have executed the body statements once, go
back to the loop condition and re-evaluate it. If it is true,
execute the body code again. If the condition is not true
then the body will not be executed!
The while Looping (Repetition) Structure
•
•
•
Infinite loop: is a loop that continues to execute
endlessly.
So, expression is always true in an infinite loop.
Statements must change value of expression to
false.
8
Example
i = 0
loop while (i <= 20)
print(i)
i = i + 5
end loop
i
0
5
10
15
20
25
Output
0
5
10
15
20
start
i = 0
i <= 20
Yes
Print i
i = i + 5
end
What will happen if you omit (i= i + 5) ?
No
While Loop Types
Counter-Controlled Loop
 Sentinel-Controlled Loop
 Flag-Controlled Loop

Counter-Controlled Loop


Used when exact number of data or entry pieces is
known.
General form:
N=…
Read N
or
N = …
counter = 0
Loop while (counter < N)
.
.
.
counter = counter + 1
.
.
.
End loop
(1)
Initialization
stmt.
(2)
Loop condition
counter = 0
counter < N
Yes
do operation
counter = counter + 1
(3)
Update stmt.
No
Example

Write a program to allow the user to enter a
set of integer numbers, then print the sum of
these numbers.
Start Program
Read setSize
counter = 0
sum = 0
Loop while (counter < setSize)
Read number
sum = sum + number
counter = counter + 1
End loop
Print sum
End Program
Start Program
Read setSize
counter = 0
sum = 0
Loop while (counter < setSize)
Read number
sum = sum + number
counter = counter + 1
End loop
Print Sum
End Program
setSize counter sum number
3
0
0
1
Output
1
1
10
2
11
4
3
1
10
4
15
3
15
start
Read setSize
counter = 0
sum = 0
counter <
setSize
Yes
Read number
sum = sum + number
counter = counter + 1
Print sum
end
No
The while Looping (Repetition) Structure
14



Syntax:
while (expression)
statement
Statements must change value of expression to false.
A loop that continues to execute endlessly is called an
infinite loop (expression is always true).
The while Looping (Repetition) Structure
15
Example 5-1
i = 0;
while (i <= 20)
{
System.out.print(i + " ");
i = i + 5;
}
System.out.println();
Output
0 5 10 15 20
The while Looping (Repetition) Structure
16
Typically, while loops are written in the following form:
//initialize the loop control variable(s)
while (expression)
//expression tests the LCV
{
.
.
.
//update the loop control variable(s)
.
.
}
Counter-Controlled while Loop
17


Used when exact number of data or entry pieces is
known.
General form:
int N = //value input by user or specified
//in program
int counter = 0;
while (counter < N)
{
.
.
.
counter++;
.
.
}
Counter-Controlled while Loop-Example 5-3
18
//Counter-controlled while loop
import java.util.*;
public class CounterControlledWhileLoop
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int limit;
//store the number of items
//in the list
int number;
//variable to store the number
int sum;
//variable to store the sum
int counter;
//loop control variable
System.out.print("Enter the number of "
+ "integers in the list: ");
limit = console.nextInt();
System.out.println();
sum = 0;
counter = 0;
System.out.println("Enter " + limit+ " integers.");
Counter-Controlled while Loop-Example 5-3
(continued)
19
while (counter < limit)
{
number = console.nextInt();
sum = sum + number;
counter++;
}
System.out.printf("The sum of the %d " +"numbers = %d%n", limit, sum);
if (counter != 0)
System.out.printf("The average = %d%n",(sum / counter));
else
System.out.println("No input.");
}
}
Sample Run:
Enter the number of integers I the list: 4
Enter 4 Integers
2158
The sum of the 4 numbers = 16
The average = 4
Counter-Controlled Loop: Another way
for expressing it
While loop
N = …
counter = 1
Loop while (counter<=N)
.
.
counter = counter + 1
End loop
For loop
N = …
For(counter = 1, counter <= N, counter = counter + 1)
.
.
End For
Initialization
Condition
counter = 1 to N
Increment \ Decrement
Step 1
Counter-Controlled Loop –For Loop
The for loop does not have a standard flowcharting method and you will find
it done in different ways.
N=…
or
Read N
Yes
do operation
counter = counter + 1
or
Read N
Can be
simplified
to:
counter = 1
counter
<= N
N=…
No
For counter = 1 to N,
step 1
do operation
Next counter
Example
1.
2.
Write down an algorithm and draw a
flowchart to find and print the largest of
N (N can be any number) positive
numbers. Read numbers one by one.
Verify your result by tracing the
developed algorithm. (Assume N to be 4
and the following set to be the numbers
{5 2 6 1})
start
Solution
Read N
max = 0
(1)
Start Program
Read N
max = 0
For(counter = 1 to N, step 1)
Read number
if (number > max)
max = number
End For
Print max
End Program
For counter = 1
to N, step 1
Yes
Read number
number >
max
Yes
max = number
Next counter
end
No
start
(2) •
•
N
4
Trace the developed algorithm.
Assume N to be 4 and the following
set to be the numbers {5 2 6 1}
max counter
max = 0
number
0
1
5
5
2
2
6
3
6
4
1
5
Read N
For counter = 1
to N, step 1
Yes
Read number
number >
max
Yes
max = number
Print max  6
Next counter
end
No
The for Looping (Repetition) Structure
25

Specialized form of while loop.

Its primary purpose is to simplify the writing of counter-controlled
loops. For this reason, the for loop is typically called a counted or
indexed for loop. .

Syntax:
for (initial statement; loop condition; update statement)
statement
The for Looping (Repetition) Structure
26

Execution:
1. Initial statement executes.
2. Loop condition is evaluated.
3. If loop condition evaluates to true,
1.
2.
4.
execute for loop statement and
execute update statement.
Repeat step 2 until loop condition is false.
The for Looping (Repetition) Structure
27
Example 5-9
The following for loop prints the first 10
nonnegative integers:
for (i = 0; i < 10; i++)
System.out.print(i + " ");
The for Looping (Repetition) Structure
28
Example 5-10
1.
The following for loop outputs the word Hello and a star (on
separate lines) five times:
2.
for (i = 1; i <= 5; i++)
{
System.out.println("Hello");
System.out.println("*");
}
The following for loop outputs the word Hello five times and
the star only once:
for (i = 1; i <= 5; i++)
System.out.println("Hello");
System.out.println("*");
The for Looping (Repetition) Structure
29





Does not execute if loop condition is initially false.
Update expression changes value of loop control
variable, eventually making it false.
If loop condition is always true, result is an infinite
loop.
Infinite loop can be specified by omitting all three
control statements.
If loop condition is omitted, it is assumed to be
true.

Action of for loop ending in semicolon is empty.
For Loop Programming Example: Classify
Numbers
30

Input: N integers (positive, negative, and zeros).
int N = 20;

//N easily modified
Output: Number of 0s, number of even integers,
number of odd integers.
For Loop Programming Example: Classify
Numbers (solution)
31
for (counter = 1; counter <= N; counter++)
{
number = console.nextInt();
System.out.print(number + " ");
switch (number % 2)
{
case 0: evens++;
if (number == 0)
zeros++;
break;
case 1:
case -1: odds++;
} //end switch
} //end for loop
While Loop Programming
Example: Fibonacci Number
32


Fibonacci formula for any Fibonacci sequence:
an = an-1 + an-2
Input: First two Fibonacci numbers in sequence,
position in sequence of desired Fibonacci number
(n).




int previous1 = Fibonacci number 1
int previous2 = Fibonacci number 2
int nthFibonacci = Position of nth Fibonacci number
Output: nth Fibonacci number.
While Loop Programming Example: Fibonacci Number
33
if (nthFibonacci == 1)
current = previous1;
else if (nthFibonacci == 2)
current = previous2;
else
{
counter = 3;
while (counter <= nthFibonacci)
{
current = previous2 + previous1;
previous1 = previous2;
previous2 = current;
counter++;
}
}

Final result found in last value of current.