0% found this document useful (0 votes)
16 views35 pages

Lecture10 Slides PDF

Uploaded by

aaronnolan204
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views35 pages

Lecture10 Slides PDF

Uploaded by

aaronnolan204
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

CS161 Introduction to

Computer Science 1
Week 4 (Lecture 10)
Peter Mooney
Department of Computer
Science

Eolas Building.
Email: [email protected]

This lecture
corresponds to
Chapter 7 in
your CS161
textbook
Ternary Operator Revisited
int a = -100, b = 20;
//Get the maximum value
int min = (a < b) ? a : b;
System.out.println("Minimum value is: " + min);

int max = (a > b) ? a : b;


System.out.println("Maximum value is: " + max);

// Get the absolute value.


int abs = (a < 0) ? -a : a;
System.out.println("Absolute value is: " + abs);
TASK: Row of 10 stars 6 times

Write a Java program that prints 10 stars on a
line but does this 6 times.
What about printing a row of 8
starts 14 times?

Write a Java program that prints 8 stars on a
line but does this 14 times.
There is a major problem with this
approach
 As the number of lines to print grows it
is harder to know what the program
does (how many lines of stars in print
if there is no comment) and harder to
maintain
 Imagine you are now asked to change

the program so that it prints six


dashes per line instead of six stars...
 That’s a lot of code to change.. No

thanks!
CS161: The NEXT MAJOR CONCEPT

We’ve seen class structure, variables, data types,
conditions, IF statements, ternary operators, ...

Now we move onto LOOPS or ITERATION within
Java programs.

LOOPS or ITERATION are one of the key ways that
computer programming outperforms human
computational ability

LOOPS or ITERATION allows a computer program
to repeat the same calculation or computation
over and over again (and to do so very quickly!)
Let’s introduce iteration (loops)

 Loops allow your program to do the same thing


again and again and again and again.
 More efficient and more elegant!
 A loop repeatedly executes the same set of
instructions until a finishing condition is
met.
Types of looping structures in Java

 There are three looping statements in Java


 while

 for

 do…while
Syntax of while loops in Java
 Initialisation; // control variables, index, counters etc.

while(condition is true)
{
statement1;
statement2;
….
update;
}
 As long as the condition being tested is true,
whatever is between the braces will execute again and
again, possibly forever!
Syntax of do-while loops
 Initialisation; // control variables, index, counters etc.
do
{
statement1;
statement2;
….
update;
}
While (condition is true)
 As long as the condition being tested is true, whatever is
between the braces will execute again and again, possibly
forever! But statement1, statement2, etc will be excuted at
least once
Syntax of for loops
for(initial; condition is true; ++/--){
statement1;
statement2;
………
}
 The update in a for loop is uusually an ++ or - - operator.
All statements inside the { } are executed a known number of
times until the condition becomes false.
Comparing the three loops and
their syntax and structure
Examples of loop structures

We are going to look at several examples of
loop structures

For the first few examples, we will create the
code for the three types of loops.

Then, for other examples, we will just create
the code for one of the three types of loops.

We’ll also do some live coding of an example
(in lecture 10 or lecture 11)
Example 1: Printing numbers

Use a loop in Java to print all of the


ODD numbers between 0 and n
(where n is any integer). You must
print out the numbers on one line.
Input n = 14
Output 1 3 5 7 9 11 13
Example 1: Printing numbers
(for loop code) as our counter
Initial value of i –

Our condition –
once this
becomes FALSE
we are finished
the loop
Increment –
move the value
of i on by 1 each
time.

When i = 0, line 12 is FALSE .. Then i++


When i = 1, line 12 is TRUE so print (i)..
Then i++
For loop curly When i = 2, line 12 is FALSE .. then i++
Backets ........
(block)
When i = 14, line 12 is FALSE.... then i+
+
When i = 15 – WAIT the condition on line
9 is FALSE so STOP Loop over
Example 1: Printing numbers
(while loop code) as our counter
Initial value of i –

Our condition –
once this
becomes FALSE
we are finished
the loop
Increment –
move the value
of i on by 1 each
time.

When i = 0, check condition on line 9 – if


true then execute the code. Then update
i on line 18
While loop When i = 1, check condition on line 9 – if
curly true then execute the code. Then update
Backets i on line 18
(block)
.......
When i = 15 check condition on line 9 –
FALSE – then STOP we skip past the
loop and exit.
Example 1: Printing numbers
(do-while loop code) Initial value of i –
as our counter

Our condition –
once this
becomes FALSE
we are finished
the loop
Increment –
move the value
of i on by 1 each
time.
When i = 0, execute the code on line 12
– then update i on line 18. If condition on
line 19 is TRUE – go back and do the
loop again.
When i = 1, execute the code on line 12
The do-while loop curly – then update i on line 18. If condition on
Backets (block) line 19 is TRUE – go back and do the
loop again.

When i = 14, execute the code on line 12


– then update i on line 18. The condition
on line 19 is FALSE – STOP and exit the
IMPORTANT – the code for line 12 – 15 is identical.
Loop condition is the same. DIFFERENCE is
structure, initialisation, update
Example 2: Calculations with loops

Use a loop in Java to sum (or add up) ALL


numbers that are divisible by 7 between 0
and N (inclusive). Your program should
indicate if a number is divisible by 7. The
final line of code will out the sum of all
numbers divisible by 7
Input n = 30
Output 7 14 21 28 Sum is 70
Example 2: Calculations with loops
(let’s plan our solution)

Our loop needs to iterate or repeat
from 0 to N (inclusive)


The loop will iterate in steps of 1
each time (update)


We need to have a variable to store
or remember the sum of numbers
divisible by 7. This is like a
“running total”.


Each time we find a number
divisible by 7 we should add it to
the current SUM or TOTAL


The loop should stop or terminate
when our step or index is greater
than N.
Example 2: Adding numbers
(for loop code) as our counter
Initial value of i –

Our condition –
once this
becomes FALSE
we are finished
the loop
Increment – move
the value of i on by 1
each time.
When i = 0, line 11 is FALSE .. Then i++

When i = 7, line 11 is TRUE ..


We print that 7 is divisible by 7
Sum = sum + i .... so sum is now 7
then i++
........
When i = 14, line 11 is TRUE ..
We print that 14 is divisible by 7
Sum = sum + i .... so sum is now 14
then i++
....

When i = 1001 – WAIT the condition on line


8 is FALSE so STOP Loop over
Example 2: Printing numbers
(while loop code) as our counter
Initial value of i –

Our condition –
once this
becomes FALSE
we are finished
the loop

Increment – move
the value of i on by 1
each time.

When i = 0, check condition on line 9 – if


true then execute the code.
Then update i on line 19
When i = 7, check condition on line 9 – if
true then execute the code.
7 is divisible by 7 so
sum = sum + i (so sum is 7) Then
update i on line 19

.......
When i = 1001 check condition on line 9
– FALSE – then STOP we skip past the
Example 2: Printing numbers
(do-while loop code)

Exercise for you to complete

Can you write out the do-while


loop code for this example?
IMPORTANT – the code for line 11 – 17,18 is
identical. Loop condition is the same. DIFFERENCE
is structure, initialisation, update

REGARDLESS of which loop structure


you use – the internal LOOP CODE
(lines 11 – 17, 18) will always be the
same. Why? Because the LOOP CODE is
performing the same computation –
the difference is the loop structure
used to control the iteration or loop
LIVE CODE VERSION

Example 2 running live in class
What if we want a loop to go “in
reverse” or DESCENDING order

Note the difference with Example 1


from earlier in the lecture
We simply change the initial value (starting), change
the condition, and finally how the loop will update.
This will all be opposite to ASCENDING order.

Our loop code (inside the loop) does not change.


Question for you – What is the value of t
printed out on line 19 in this code?

A: 13 B: 54 C: 4
Answer provided live in the
lecture
So, remember, here’s how you choose
the correct loop structure
ALL Loop structures require
several key parts in their design

This is true for loop structures in any programming
language, not just Java
Structure Description
INITIALISATION: Initial conditions This is how our loop starts. What are the values of
or the starting conditions the variables at the very start of the repetition?
Usually, this involves a counter or index.
CONDITION: The condition that Very similiar to conditions in IF statements – we
stops or terminates the loop need a condition (evaluating to true or false) that
structure controls the loop. If the condition becomes false
then the loop stops
ITERATION: Iteration – what is the This is the code inside the body or the loop block
code that is being iterated or (essentially inside the { } curly braces). It is the
repeated inside the loop? code that you want repeated or looped
UPDATE: How is the loop To continually repeat the same code (as outlined in
structure updated? the iteration step) we have to update the variables
that are part of the CONDITION.
The for loop, while loop, and do-
while loop have many similarities
but they are not identical
Structure The for loop The while loop The do-while loop
INITIALISATION: Usually created within the Usually happens BEFORE the Usually happens BEFORE the do-while
Initial conditions for loop syntax – by while loop is written. loop is written.
declaring and initialising a
or the starting
variable
conditions
CONDITION: The Generally, a simple Usually, the condition is a Usually, the condition is a boolean
condition that condition involving the boolean condition which can condition which can involve
initialisation variable. involve initialisation variables initialisation variables
stops or
terminates the
loop structure
ITERATION: This can be any valid Java This can be any valid Java This can be any valid Java code. The
Iteration – what is code. The initialisation code. The initialisation variable initialisation variable is normally
variable is normally NOT is normally changed with in changed with in this code.
the code that is
altered in this code. this code.
being iterated or
repeated inside
the loop?

UPDATE: How is By ++ or – of the By changing the initialisation By changing the initialisation variable
the loop structure initialisation variable variable
updated?
Your choice of loop depends on
the computational task involved
Usage The for loop The while loop The do-while loop
When should I When you want to execute a When you do not know how The do-while loop is used when you
set of statements (iteration) many times you want to have a situation similiar to a while
use this loop? a specific number of times. execute a set of statements loop.
(iteration).
That is, you know exactly You do not know how
how many times you want You may want to execute 0
the loop to repeat or iterate. times, 1 times, or 10,000 times! many times you want to
execute a set of
The while loop iteration is
controlled by the condition statements (iterations)
but you know that they
must be executed at
least once.

The do-while loop iteration is


controlled by the condition
LECTURE 11 – To do list
 Bring your laptop and/or pen/paper – you
are going to do an exercise, in the lecture,
to write your own loop code for a given
problem

LECTURE 12 – To do list
 Bring your laptop or phone and/or
pen/paper – We will have our WEEK 4
IN LECTURE QUIZ
Week 4 – Lab 3 – OPEN ON MULE
All questions about the Labs
– please ask Mark Noone
(Lab manager and Teaching
assistant)

Email: [email protected]

You might also like