Lecture 6 Instructions, Loops

background image

Programming Languages

Lecture 6

Instructions. Loops

R. Pełka – Wojskowa Akademia Techniczna

background image

R. Pełka: Programming Languages

2

Richard Stallman

(born 1953)

Described by some as “world’s best
programmer”

Wrote/developed GNU software
tools, particularly g++

Believes all software should be free,
but like “free speech”, not “free beer”

Won MacArthur award for his efforts
and contributions

League for Programming Freedom

Gnu/Linux is a free operating system
and computing environment

Heavy industry/web use

Wintel killer??

Local tie-in: Red Hat Linux,

•headquarted in Durham, NC
•IPO in 1999 at $14
•One month later at $110+
•Markets “free” product

background image

R. Pełka: Programming Languages

3

Outline

Control statements

if

if

statement

if

else

statement

nested

if

Comparing values in conditions

switch

statement

break

default

Loops

while

do-while

for

Breaking and continuing loops

background image

R. Pełka: Programming Languages

4

Conditional Statements

A conditional statement lets us select which statement will
be executed next

Conditional statements give us the power to make basic
decisions

Also called selection statements or decision statements

The Java conditional statements are the:

if statement

if-else statement

switch statement

background image

R. Pełka: Programming Languages

5

if-else

statement

syntax

if

(condition)

statement1

else

statement2;

condition – boolean

statements

single instruction

block od instructions

{

//example of if-else

int v=5;

int sum=0;

if(

v > 0

){

sum += v*v;

v++;

}

else

sum = 42;

}

Attention:

Condition is boolean expression and may
use both aritmetic and logical relations

the precedence rules are important

Indendation is important for readibility

Blocks should be defined with braces { }

background image

R. Pełka: Programming Languages

6

if

statement

syntax

if

(condition)

action;

condition – boolean

action

single instruction

block od instructions

{

//example of if

int v=5;

int sum=0;

if(

v > 0

){

sum += v*v;

v++;

}

}

background image

R. Pełka: Programming Languages

7

Nested if Statements

The statement executed as a
result of an

if

statement or

else

clause could be

another

if

statement

These are called

nested if

statements

An

else

clause is matched

to the last unmatched

if

(no

matter what the indentation
implies)

Braces can be used to
specify the

if

statement to

which an

else

clause

belongs

{

//nested if example

boolean isLeapYear;

if

(year % 4 == 0)

if

(year % 100 != 0)

isLeapYear = false;

if

(year % 1000 == 0)

isLeapYear = true;

else

isLeapYear = false;

}

?

background image

R. Pełka: Programming Languages

8

Conditions – problems

The precedence of the arithmetic operators is higher than the
precedence of the equality and relational operators

All logical operators have lower precedence than the relational and
arithmetic operators

Logical NOT has higher precedence than logical AND and logical OR

Arithmetic operators (e.g., +) have higher precedence than equality and
relational operators

The processing of logical AND and logical OR is “short-circuited”

If the left operand is sufficient to determine the result, the right operand
is not evaluated

It may produce side-effects

When comparing data using boolean expressions, it's important to
understand the nuances of certain data types

background image

R. Pełka: Programming Languages

9

Comparing Float Values

You should rarely use the equality operator (

==

) when comparing

two floating point values (

float

or

double

)

Two floating point values are equal only if their underlying binary
representations match

exactly

Computations often result in slight differences that may be irrelevant

In many situations, you might consider two floating point numbers to
be "close enough" even if they aren't exactly equal

To determine the equality of two floats, you may want to use the
following technique:

if the difference between the two floating point values is less than the
tolerance, they are considered to be equal

the tolerance could be set to any appropriate level, such as 0.000001

if (Math.abs(f1 - f2) < TOLERANCE)

System.out.println ("Essentially equal");

background image

R. Pełka: Programming Languages

10

Comparing Characters

As we've discussed, Java character data is based on the Unicode character
set

Unicode establishes a particular numeric value for each character, and
therefore an ordering

We can use relational operators on character data based on this ordering
For example, the character

+

is less than the character

‘J’

because it

comes before it in the Unicode character set

In Unicode, the digit characters (0-9) are contiguous and in order

Likewise, the uppercase letters (A-Z) and lowercase letters (a-z) are
contiguous and in order

97 through 122

a – z

65 through 90

A – Z

48 through 57

0 – 9

Unicode Values

Characters

background image

R. Pełka: Programming Languages

11

Comparing

Strings

Remember that in Java a character string is an

object

The

equals

method can be called with strings to

determine if two strings contain exactly the same
characters in the same order

The

equals

method returns a boolean result

if (name1.

equals

(name2))

System.out.println ("Same name");

background image

R. Pełka: Programming Languages

12

Comparing Strings

We cannot use the relational operators to compare strings

The

String

class contains a method called

compareTo

to

determine if one string comes before another

A call to

name1.compareTo(name2)

returns zero if

name1

and

name2

are equal (contain the same

characters)

returns a negative value if

name1

is less than

name2

returns a positive value if

name1

is greater than

name2

if (name1.

compareTo

(name2) < 0)

System.out.println (name1 + "comes first");

else

if (name1.

compareTo

(name2) == 0)

System.out.println ("Same name");

else

System.out.println (name2 + "comes first");

background image

R. Pełka: Programming Languages

13

Comparing Strings

Because comparing characters and strings is based
on a character set, it is called a

lexicographic ordering

Lexicographic ordering is not strictly alphabetical when
uppercase and lowercase characters are mixed

For example, the string

"Great"

comes before the

string

"fantastic"

because all of the uppercase

letters come before all of the lowercase letters in
Unicode

Also, short strings come before longer strings with the
same prefix (lexicographically)

background image

R. Pełka: Programming Languages

14

Comparing Objects

The

==

operator can be applied to objects – it returns

true if the two references are

aliases

of each other

The

equals

method is defined for all objects, but unless

we redefine it when we write a class, it has the same
semantics as the

==

operator

It has been redefined in the

String

class to compare

the characters in the two strings

When you write a class, you can redefine the

equals

method to return true under whatever conditions are
appropriate

background image

R. Pełka: Programming Languages

15

The Conditional Operator

Java has a

conditional operator

that uses a boolean condition to

determine which of two expressions is evaluated

its syntax is:

condition

?

expression1

:

expression2

If the

condition

is true,

expression1

is evaluated; if it is false,

expression2

is evaluated

The value of the entire conditional operator is the value of the
selected expression

background image

R. Pełka: Programming Languages

16

The Conditional Operator

The conditional operator is similar to an

if-else

statement, except

that it is an expression that returns a value

for example:

larger = ((num1 > num2) ? num1 : num2);

if

num1

is greater than

num2

, then

num1

is assigned to

larger

;

otherwise,

num2

is assigned to

larger

the conditional operator is

ternary

because it requires three

operands

background image

R. Pełka: Programming Languages

17

The Conditional Operator

Another example:

if

count

equals 1, then

"Dime"

is printed

if

count

is anything other than 1, then

"Dimes"

is printed

System.out.println ("Your change is " + count +

((count == 1)

?

"Dime"

:

"Dimes"));

background image

R. Pełka: Programming Languages

18

The

switch

statement

The

switch

statement evaluates an expression, then attempts to match

the result to one of several possible

cases

Each case contains a value and a list of statements

The flow of control transfers to statement associated with the first case
value that matches

switch

(

expression

)

{

case

value1

:

statement-list1

case

value2

:

statement-list2

case

value3

:

statement-list3

case

...

}

switch

and

case

are

reserved

words

if

expression

matches

value2

,

control jumps

to here

background image

R. Pełka: Programming Languages

19

The

switch

statement

Often a

break

statement is used as the last

statement in each case's statement list

A

break

statement causes control to transfer

to the end of the

switch

statement

If a

break

statement is not used, the flow

of control will continue into the next case

Sometimes this may be OK, but often we want
to execute only the statements associated
with one case

The expression of a

switch

statement must result in an

integral

type

, meaning an

int

or a

char

(

also

byte

and

short

)

It cannot be a

boolean

value, a floating point value (

float

or

double

), or another integer type

The implicit boolean condition in a

switch

statement is equality

You cannot perform relational checks with a

switch

statement

switch

(option)

{

case 'A':

aCount++;

break

;

case 'B':

bCount++;

break

;

case 'C':

cCount++;

break

;

}

background image

R. Pełka: Programming Languages

20

The

switch

statement

A

switch

statement can have an optional

default

case

The default case has no associated value and simply uses the
reserved word

default

If the default case is present, control will transfer to it if no other
case value matches

If there is no default case, and no other value matches, control falls
through to the statement after the switch

public void switchExample(int digit){

switch (digit){

case 1: System.out.println("First ");

case 2: System.out.println("Second ");

case 3: System.out.println("Third ");

default

: System.out.println("Other ");

}

}

background image

R. Pełka: Programming Languages

21

Loops

Repetition

(or

iteration

) statements allow us to execute a statement

multiple times

Often they are referred to as

loops

Like conditional statements, they are controlled by boolean
expressions

Java has three kinds of repetition statements:

the

while

loop

the

do

loop

the

for

loop

The programmer should choose the right kind of loop for the
situation

background image

R. Pełka: Programming Languages

22

The

while

statement

int count = 1;

while

(count <= 5)

{

System.out.println (count);

count++;

}

If the condition of a

while

loop is false

initially, the
statement is never
executed

Therefore, the body
of a

while

loop will

execute zero or more
times

background image

R. Pełka: Programming Languages

23

This example shows how to calculate the successive powers of 2
(

using Java JDK

)

By the way, please note how to

convert

a String

args[0]

to

integer

while

example

background image

R. Pełka: Programming Languages

24

Infinite loops

The body of a

while

loop eventually must make

the condition false

If not, it is called an

infinite loop

, which will

execute until the user interrupts the program

This is a common logical

error

You should always double check the logic of a
program to ensure that your loops will terminate
normally

Entore Buggati:
„I build cars to go, not to stop."

int count = 1;

while

(count <= 25)

{

System.out.println (count);

count = count - 1;

}

This loop will continue
executing until interrupted
(Ctrl-C in DOS window or
until an underflow error
occurs)

background image

R. Pełka: Programming Languages

25

Nested loops

How many times will the string

"Here"

be printed?

count1 = 1;

while

(count1 <= 10)

{

count2 = 1;

while

(count2 <= 20)

{

System.out.println ("Here");

count2++;

}

count1++;

}

answer: 10 * 20 = 200 times

background image

R. Pełka: Programming Languages

26

The

do

statement

do

{

statement

;

}

while

(

condition

)

The

statement

is executed once initially,

and then the

condition

is evaluated

The statement is executed repeatedly until
the condition becomes false

int count = 0;

do

{

count++;

System.out.println(count);

} while (count < 5);

background image

R. Pełka: Programming Languages

27

The

for

statement

initialization

;

while

(

condition

)

{

statement1;

statement2;

...

increment

;

}

for

(

initialization

;

condition

;

increment

)

{

statement1;

statement2;

...

}

=

// for loop – example

// calculate N!

int sum = 1;

for

(int i=1; i<=N; i++)

sum*=i;

System.out.println(sum);

Initialization can be used to

declare

the variable

background image

R. Pełka: Programming Languages

28

The

for

statement

Like a

while

loop, the condition of a

for

loop is tested

prior to executing the loop body

Therefore, the body of a

for

loop will execute zero or

more times

A

for

loop is well suited for executing statements a

specific number of times that can be calculated or
determined in advance

Each expression in the header of a

for

loop is optional

If the

initialization

is left out, no initialization is performed

If the

condition

is left out, it is always considered to be

true

, and

therefore creates an

infinite loop

If the

increment

is left out, no increment operation is performed

background image

R. Pełka: Programming Languages

29

Nested loops

loops can be nested

example: Pitagoras numbers

numbers (a, b, c) fulfilling the rule: a

2

+b

2

=c

2

task: find all Pitagoras numbers for a, b

100

class

Pitagoras{

static

void

allTriples(

int

n){

for (

int

a=1; a <= n; a++)

for (

int

b = a; b <= n; b++){

int

c = intSqrt(a*a+b*b);

if (a*a+b*b == c*c)

System.out.println(”(”+a+”,”+b+”,”+c+”)”);

}

}

static

int

intSqrt(

int

n){

return (

int

)(Math.sqrt(n));

}

}

background image

R. Pełka: Programming Languages

30

Breaking the loop

syntax:

break;

breakes the loop (or switch)
immediately

can be used only in loops

while

for

do-while

or in the

switch

statement

used when we want to leave the loop
before the „normal” termination, eg.
when the element we are looking for
has been already found

{// server

while(true){

acceptRequest();

if (timeOut())

break;

provideService();

}

}

background image

R. Pełka: Programming Languages

31

continue

the loop

syntax:

continue;

-

skip to the beginn of the loop from its body

used when in the current iteration we do not want to complete the
remaining part of the body, but we want to start the next iteration

/** read numbers from keyboard until you get 0.

* ignore numbers < 10 or > 60

* write an average

*/

Public static void readComputeAverage(){

java.util.Scanner in = new java.util.Scanner(System.in);

System.out.println(„Please enter the number”);

int sum = 0, counter = 0;

while(true){

int n = in.nextInt();

if(n==0)

break;

//finished

if(n <10 || n > 60)

continue;

//go ahead

sum += n;

counter++;

}

// end while

System.out.println(”Average is ” + (float)sum/counter);

}

background image

R. Pełka: Programming Languages

32

Finishing the method

the instruction

return

breaks the method immediately

may take back the value – result

methods that produce result

must have the

return

statement

return stanKonta+16;

methods without result (ie.

void

)

may have the

return

statement

return;

orthodox programmers

avoid

placing

return

inside

the

loops

background image

R. Pełka: Programming Languages

33

Summary

Control statements

if

if

statement

if

else

statement

nested

if

Comparing values in conditions

switch

statement

break

default

Loops

while

do-while

for

Breaking and continuing loops


Wyszukiwarka

Podobne podstrony:
15427 Instrumementation system design lecture 1id 16462 ppt
15427 Instrumementation system design lecture 1id 16462 ppt
IR Lecture1
uml LECTURE
lecture3 complexity introduction
Promocja jako instrument marketingowy 1
benzen lecture

więcej podobnych podstron