# Lecture 3 Slides

```Programming for Beginners
Lecture 3: Flow Control I: For Loops
Martin Nelson
Elizabeth FitzGerald
Revision of Session 2

Declaration of variables and assigning values to them.

The main Java variable types:

char

String

byte

integer

boolean

Performing arithmetic.

Decision making

double
class myprog
{
public static void main(String[] args)
{
//Declare an integer
int x=1;
//Do some arithmetic
x=x+10;
//Print the result
System.out.println(“The value of x is”+x);
}
}
Session 3 - aims &amp; objectives

Find out more about decision making using logical
operators

Learn how to use ‘for’ loops to automate repetitive
Conditional branching


Comparison operators
&gt;
&gt;=
==
&lt;
&lt;=
!=
Logical operators
&amp;&amp;
||
!
AND
OR
NOT
Comparison of data types

You will need to use different methods for comparing
Strings than for comparing doubles, integers or chars

We will discuss how to do this in Session 8.
Looping

A block of code is repeated


A pre-defined number of times
(determinate)
Until a certain (boolean) condition is met
(indeterminate)

The contents of variables often change in each cycle

Beware of perpetual or infinite loops!
‘For’ loops

These are probably the most common type of loop.

They require a starting condition, something to test to
decide whether to continue, and a statement of what
changes on each iteration.

In Java, the syntax is:
for(start condition; continue condition; update instruction)
{
Stuff to do on each iteration of the loop.
This will be a list of statements, often a few lines long.
}
For loop example

Some code to print the numbers 1 to 100 on the screen.
for(int x=1; x&lt;=100; x++)
{
System.out.println(x);
}

‘for’ is a reserved word which tells java that this is a loop.

Here x is declared when the for loop starts, but you could
declare x before the loop.

x++ is shorthand for ‘x=x+1’.
Exercises


Look at the example code in for this session:

Simple determinate loop

Loop a block of code: going up/going down

N green bottles!

N men went to mow!
Then attempt today’s exercises.
A different kind of loop…
Coming up in Session 4...

More on flow control...
```