0% found this document useful (0 votes)
6 views

Repetition Sturcture - Looping JAVA ch3

Uploaded by

Tang Alex
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Repetition Sturcture - Looping JAVA ch3

Uploaded by

Tang Alex
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 62

Looping

Loop Basics
• All programming languages provide statements to
create a loop. The loop is the basic component of a
repetition structure.
• These statements are a block of code, which under
certain conditions, will be executed repeatedly.
• In this section, we will introduce some basic ideas
about these structures.
• We will start with a simple illustration of a loop
shown.
This example uses a type of loop called a
Repeat...Until loop.
1 Declare Number As Integer
2 Repeat 3
3 Write "Please enter a number: "
4 Input Number
5 Write Number
6 Until Number == 0
7 Write "List Ended”
Iterations

The number of times a task is repeated is always a


significant part of any repetition structure, but a
programmer must be aware of how many times a loop
will be repeated to ensure that the loop performs the
task correctly. In computer lingo, a single pass through
a loop is called a loop iteration.
Example
1 Declare Name As String
2 Repeat 3
3 Write "Enter the name of your brother or sister: "
4 Input Name
5 Write Name
6 Until Name == "Done"
Types of Loops

• Basically, all repetition structures can be divided

into two fundamental types:

• pretest loops

• post-test loops
The Do . . . While Loop
Declare Number As Integer
Do
Write "Enter a number: “
Input Number
Write Number
While Number != 0
Write "List Ended"
Pre-Test Loop

1 Declare Number As Integer


2 Write "Enter a number; enter 0 to quit."
3 Input Number
4 While Number != 0
5 Write Number
6 Input Number
7 End While
8 Write "List Ended
Pre-Test Loop
Post-Test Loop
Pre-test loop to display the squares of number
Start
Declare Number As Integer “Enter a
Number”
Write "Enter a number:"
Input Number No
While Number > 0 YesNumber > 0
Write Numberˆ2
Input Number
Number^2
End While
output

Stop
Using a Counter

To keep track of how many times a loop has been


executed using a counter, you must define,
initialize, and either increment (to count up) or
decrement (to count down) the counter.
Define a counter

• Define a counter: the counter is a variable. It is always an

integer because it counts the number of times the loop body

is executed and you cannot tell a computer to do something

5 3/4 times.

• Common variable names for counters are counter, Count, I,

or j. For now, we will call our counter Count.


Initialize the counter

Initialize the counter: set the counter at a beginning value.

Although a counter can begin at any integer value often

determined by other factors in the program for now, we

will usually set our counter equal to 0 or 1 (Set Count = 0 or

Set Count = 1, depending on the program’s requirements).


Increment the counter
Increment the counter: the computer counts the way you did
when you were young. To count by ones, the computer takes
what it had before and adds one. So the code for a computer
to count by ones looks like Count + 1. Then, to store the new
value where the old value was, you use the statement

Set Count = Count + 1. This takes the old value, adds one to it,
and stores the new value where the old value was.
Using a Counter to Display the Squares of Numbers
• Declare PositiveInteger As Integer
• Declare Count As Integer
• Write "Please enter a positive integer: "
• Input PositiveInteger (5) count count^2
• Set Count = 1 1 1
• While Count <= PositiveInteger 2 4
• Write Count + " " + Countˆ2 3 9
• Set Count = Count + 1 4 16
• End While 5 25
Countdown
• Declare Count As Integer
• Set Count = 100
• Write "Countdown in . . . ";
• While Count > 0
• Write Count + " seconds"
• Set Count = Count − 1
• End While
• Write "Blastoff!"
The For Loop

• The For loop provides a shortened method to


initialize the counter, to tell the computer how
much to increase or decrease the counter for
each pass through the loop, and to tell the
computer when to stop
For loop
The For Statement
• For (Counter = InitialValue; Test Condition; Counter++)
• body of the loop
• End For count = count + 1
• count++
Example:
• For (Count = 1; Count <= 4; Count++)
• Write Count
• End For
• Output 1, 2, 3, 4
The Increment/Decrement Statement
• The increment or decrement statement does the same thing that the

• Set Count = Count + 1 (increment)

• Set Count = Count − 1 (decrement)

• However, many programming languages use a shorthand method to


increment or decrement the counter. In our pseudocode, we will use a
similar shorthand as follows: ● Count++ increments the variable named
Count by 1 (i.e., it counts up). ● Count−− decrements the variable named
Count by 1 (i.e., it counts down).
Incremental For Loop and Decremental For Loop
• For (Count = 0; Count <= 15; Count+5)
• Write Count count = count + 5
• End For
Output: 5, 10, 15
• For (Count = 15; Count >= 0; Count−5)
• Write Count
• End For
• Output: 15, 10, 5, 0
While loop
• The while … EndWhile Structure is used when a set of instruction is to be executed
repeatedly until a specified condition is met. It is best used when the number of
time the instructions are to be executed is not known in advance.
• The general structure of the while loop is as shown below
• While (Condition)
S1
S2
.
.
Sn
• EndWhile
While Loop Flow
Example: Let us consider an algorithm for calculating the average age of N students.

• Declare counter As Integer


• Declare N As Integer
• Declare sum As Integer
• Declare Average As Float
• Write “Enter N”
• Input N
• Set count = 0
• Set sum = 0
• While count<=N
• Sum = sum + N
• count = count + 1
• endWhile
• Set Average = Sum/N
• Write Average
Functions
Built-in Functions Programming languages
typically provide a wide assortment of built-in
functions. These are often referred to as a library.
The code for these functions is supplied in
separate modules, and doesn’t need to be
included within your program. In this book, you
have already seen the following examples of built-
in functions:
Functions Statement
• Sqrt(X) computes the square root of the number X. A =sqrt(4) A=2
● Int(X) computes the integer obtained by discarding the fractional part
of the number X. Y =Int(5.78) Y=5
● Ceiling(X) computes the integer obtained by rounding the number X
up to the next integer.
● Floor(X) computes the integer obtained by discarding the fractional
part of the number X.
● Random() generates a random integer (whole number) from 0.0 to
1.0, including 0.0 but not 1.0.
• Length_Of(S) computes the length of the string S.
● ToUpper(S) changes the value of all characters in a string, S, to
uppercase.
● ToLower(S) changes the value of all characters in a string, S, to
lowercase
• pow(a,b) return (a *a)
• min(X) return minimum value
• max(X) return maximum vaue
Example
• Abs(10) returns 10
● Abs(−10) returns 10
● Round(10.5) returns 11
● Round(100 * 10.443)/100 returns 10.44
● Str(31.5) returns "31.5"
● Str(−100) returns "−100"
● Val("31.5",N) returns the number 31.5 and N = 1
● Val("abc",N) returns the number 0 and N = 0
Recursion
• When a subprogram calls itself, the process is
called recursion, and the subprogram is said to
be recursive. Some programming languages
allow recursion; others do not. Recursive
algorithms are algorithms that make use of
recursive subprograms. Sometimes they can
provide quick and simple solutions to complex
problems.
The Recursive Process
• To illustrate the concept of recursion, let’s consider a
simple programming problem: Given a positive integer, N,
we will write a function, Sum(N), which computes the sum
of the first N positive integers. To solve this problem we
will set up a countercontrolled loop in which each
successive integer is added to a running total. The
pseudocode is as follows: N! n,n-1,n-2….n-N-1 n, n+1,N+2
Example
• Function Sum(Integer N) As Integer
• Input N
• Set Total = 0
• For (K = 1; K <= N; K++)
• Set Total = Total + K
• End For
• Set Sum = Total
• Write Sum
• End Function
Example

• Function Sum(Integer N) As Integer


• If N == 1 Then
• Set Sum = 1
• Else
• Set Sum = Sum(N − 1) + N
• End If
• End Function
N! Factorial (Example for 8!)
• Declare N as Integer
• Declare Fact As Integer
• Declare I As Integer
• Write “Enter N”
• Input N
• Fact = 1
• If N<2 Then
• Write Fact
• Else
• Set I = 2
• Repeat
• Fact = Fact *I
• I=I+1
• Until (I > N)
• Write Fact
• Endif
• stop
N! factorial (Example use for 5! )
Declare n As Integer
Declare fact As Integer
Write “Enter N”
Input N
If N < 2 then
Write N
Else
I=N–1
Repeart
Fact = Fact *1
I=I–1
UNTIL (I<2)
Write Fact
Endif
LOOP
• A loop is part of a program that repeats.
• A loop is a control structure that causes a statement
or group of statements to repeat. Java has three
looping control structures: the while loop, the do-
while loop, and the for loop. The difference among
each of these is how they control the repetition. In
this section we will focus on the while loop.
The difference between Postfix and Prefix mode
While Loop
While loop in Java
Pretest Loop
Do while loop
Posttest Loop
Do while Loop flow chart
For Loop
for (count = 1; count <= 5; count++)
System.out.println("Hello");
For Loop Flow Chart

for (number = 1; number <= 10; number++)


System.out.print(number + " ");
Example
For Loop is a Pretest Loop
Sample Questions
Example
Nested Loop
Example

You might also like