programming constructs overview - idc · 2007-10-27 · 2 27 october 2007 © ariel shamir 3 method...

33
1 27 October 2007 © Ariel Shamir 1 Programming Constructs Overview Method calls More selection statements More assignment operators Conditional operator Unary increment and decrement operators Iteration statements Defining methods Method calls Method calls More selection statements More selection statements More assignment operators More assignment operators Conditional operator Conditional operator Unary increment and decrement operators Unary increment and decrement operators Iteration statements Iteration statements Defining methods Defining methods 27 October 2007 © Ariel Shamir 2 Method Call System.out.print(“hello”); Is a call to the (static) method print of some class (System.out). The usual syntax is: <className>.<methodName>(<parameters>); When you are inside the same class as the method called, there is no need to use the class name. System.out.print( System.out.print(“hello hello”); ); Is a call to the (static) method Is a call to the (static) method print print of of some class ( some class (System.out System.out). ). The usual syntax is: The usual syntax is: <className className>.< >.<methodName methodName>(<parameters>); >(<parameters>); When you are inside the same class as the When you are inside the same class as the method called, there is no need to use the method called, there is no need to use the class name. class name.

Upload: others

Post on 26-Mar-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

1

27 October 2007 © Ariel Shamir 1

Programming Constructs Overview

Method calls

More selection statements

More assignment operators

Conditional operator

Unary increment and decrement operators

Iteration statements

Defining methods

Method callsMethod calls

More selection statementsMore selection statements

More assignment operatorsMore assignment operators

Conditional operatorConditional operator

Unary increment and decrement operatorsUnary increment and decrement operators

Iteration statementsIteration statements

Defining methodsDefining methods

27 October 2007 © Ariel Shamir 2

Method CallSystem.out.print(“hello”);

Is a call to the (static) method print of some class (System.out ).

The usual syntax is:<className>.<methodName>(<parameters>);

When you are inside the same class as the method called, there is no need to use the class name.

System.out.print(System.out.print( ““ hellohello ”” ););

Is a call to the (static) method Is a call to the (static) method printprint of of some class (some class (System.outSystem.out ).).

The usual syntax is:The usual syntax is:<<classNameclassName >.<>.< methodNamemethodName>(<parameters>);>(<parameters>);

When you are inside the same class as the When you are inside the same class as the method called, there is no need to use the method called, there is no need to use the class name.class name.

Page 2: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

2

27 October 2007 © Ariel Shamir 3

Method Parameters

If the method requires parameters, they

come inside the parentheses as a list.

The order and type of parameters must be

the same as required by the method.

System.out.println(“...”)

Requires one parameter of type String.

If the method requires parameters, they If the method requires parameters, they

come inside the parentheses as a list.come inside the parentheses as a list.

The order and type of parameters must be The order and type of parameters must be

the same as required by the method.the same as required by the method.

System.out.printlnSystem.out.println (( ““ ...... ”” ))

Requires one parameter of type String. Requires one parameter of type String.

27 October 2007 © Ariel Shamir 4

Math Methods

double d1, d2, d3, d4, d5;

d2 = 99.7;

d1 = Math.ceil(d2);

d3 = Math.sqrt(d1);

d4 = Math.sin(Math.PI*2);

d5 = Math.min(d1,d3);

double d1, d2, d3, d4, d5;

d2 = 99.7;

d1 = Math.ceil(d2);

d3 = Math.sqrt(d1);

d4 = Math.sin(Math.PI*2);

d5 = Math.min(d1,d3);

Page 3: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

3

27 October 2007 © Ariel Shamir 5

Statements We Know

int number = 0; // declaration statement

number = 25; // assignment statement

System.out.println(“hello”); // method call

int i = myScanner.nextInt(); // ?

int number = 0; // declaration statement

number = 25; // assignment statement

System.out.println(“hello”); // method call

int i = myScanner.nextInt(); // ?

27 October 2007 © Ariel Shamir 6

Control Structures and Statements

There are several types of statements:

– Declaration statements

– Assignment statement

– Method call statement

– Expression statements

– Iteration statements

– Selection statements

There are several types of statements:There are several types of statements:

–– Declaration statementsDeclaration statements

–– Assignment statementAssignment statement

–– Method call statementMethod call statement

–– Expression statementsExpression statements

–– Iteration statementsIteration statements

–– Selection statementsSelection statementsControl flow statementsControl flow statements

Page 4: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

4

27 October 2007 © Ariel Shamir 7

Control Flow Statements

The control structures affect the flow of control in a program.

Control flow statements can be divided into two types:

The control structures affect the flow of The control structures affect the flow of control in a program.control in a program.

Control flow statements can be divided Control flow statements can be divided into two types:into two types:•• selection statementsselection statements

– if

– switch

••iteration statementsiteration statements

– for

– while

– do … while

27 October 2007 © Ariel Shamir 8

If & If..Else Statements

statement

statement

If ?

statement

true

false

statement

If..else ?

statement

false

statement

statement

true

Page 5: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

5

27 October 2007 © Ariel Shamir 9

Switch Statement The switch statement is a choice between doing several things (usually more then two things).

The switch statement evaluates an expression, then attempts to match the result to one of a series of values.

Execution transfers to statement list associated with the first value that matches.

The The switchswitch statement is a choice between statement is a choice between doing several things (usually more then doing several things (usually more then two things).two things).

The The switchswitch statement evaluates an statement evaluates an expression, then attempts to match the expression, then attempts to match the result to one of a series of values.result to one of a series of values.

Execution transfers to statement list Execution transfers to statement list associated with the first value that associated with the first value that matches.matches.

27 October 2007 © Ariel Shamir 10

Switch Syntaxswitch(exp){

case value1:

statement1;

break;…

case valueN:

statementN;

break;

default:

defaultStatement;

break;

}

switch(exp){ switch(exp){

case value1: case value1:

statement1;statement1;

break;break;

……

case valueN: case valueN:

statementN;statementN;

break;break;

default:default:

defaultStatement; defaultStatement;

break;break;

}}

Page 6: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

6

27 October 2007 © Ariel Shamir 11

Choice of Execution • If the value of exp equals to value1then statement1 is performed.

•…

• If the value of exp equals to valueNthen statementN is performed.

• If the value of exp is different from value1 , ... , valueN then defaultStatement is performed.

•• If the value of If the value of expexp equals to equals to value1value1then then statement1statement1 is performed.is performed.

••……

•• If the value of If the value of expexp equals to equals to valueNvalueNthen then statementNstatementN is performed.is performed.

•• If the value of If the value of expexp is different from is different from value1 value1 , ... , , ... , valueNvalueN then then defaultStatementdefaultStatement is performed. is performed.

27 October 2007 © Ariel Shamir 12

Switch Statement Details exp can be an integer variable or an expression that evaluate to an integer value.

statementN can be empty or can be a set of instructions.

A default case can be added to the end of the list of cases, and will execute if no other case matches.

expexp can be an integer variable or an can be an integer variable or an expression that evaluate to an integer expression that evaluate to an integer value.value.

statementNstatementN can be empty or can be a set can be empty or can be a set of instructions.of instructions.

A A defaultdefault case can be added to the end of case can be added to the end of the list of cases, and will execute if no the list of cases, and will execute if no other case matches.other case matches.

Page 7: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

7

27 October 2007 © Ariel Shamir 13

The Break Statement

The break statement is usually used to

terminate the statement list of each case.

This causes the control to jump to the end

of the switch statement and continue.

Note: if the break statement is omitted

execution continues (“falls”) to the next

case!

The The breakbreak statement is usually used to statement is usually used to

terminate the statement list of each case. terminate the statement list of each case.

This causes the control to jump to the end This causes the control to jump to the end

of the of the switchswitch statement and continue.statement and continue.

Note: if the Note: if the breakbreak statement is omitted statement is omitted

execution continues (execution continues (““fallsfalls””) to the next ) to the next

case!case!

27 October 2007 © Ariel Shamir 14

Exampleswitch(item) {

case 0:

case 1:

// do something

break;

default:

// do something

break;

case 2:

// do something

break;

case 8:

// do something

break;

}

switch(item) {

case 0:

case 1:

// do something

break;

default:

// do something

break;

case 2:

// do something

break;

case 8:

// do something

break;

}

Page 8: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

8

27 October 2007 © Ariel Shamir 15

Exampleswitch(letter) {

case ‘a’:

System.out.println(“The letter was a”);

add();

break;

case ‘d’:

System.out.println(“The letter was d”);

delete();

break;

default:

System.out.println(“Illegal input”);

break;

}

switch(letter) {

case ‘a’:

System.out.println(“The letter was a”);

add();

break;

case ‘d’:

System.out.println(“The letter was d”);

delete();

break;

default:

System.out.println(“Illegal input”);

break;

}

27 October 2007 © Ariel Shamir 16

More Operators

Conditional (ternary ���� ?���� : ���� )

Assignment (binary ���� +=���� )

Increment & decrement (unary ���� ++)

Conditional (ternary Conditional (ternary �������� ?? �������� :: �������� ))

Assignment (binary Assignment (binary �������� +=+=�������� ))

Increment & decrement (unary Increment & decrement (unary �������� ++++))

Page 9: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

9

27 October 2007 © Ariel Shamir 17

The Conditional Operator

The conditional operator evaluates a Boolean condition that determines which of two expressions is evaluated.

condition ? e xp1 : e xp2

If condition is true, exp1 is evaluated; if it is false, exp2 is evaluated.

The result of the chosen expression is the result of the entire conditional operator.

The conditional operator evaluates a The conditional operator evaluates a Boolean condition that determines which Boolean condition that determines which of two expressions is evaluated.of two expressions is evaluated.

conditioncondition ? e? e xp1xp1 : e: e xp2xp2

If If conditioncondition is true, is true, exp1exp1 is evaluated; if is evaluated; if it is false, it is false, exp2exp2 is evaluated. is evaluated.

The result of the chosen expression is the The result of the chosen expression is the result of the entire conditional operator.result of the entire conditional operator.

27 October 2007 © Ariel Shamir 18

Conditional Operator Usage

The conditional operator is similar to an if-else statement, except that it is an expression that returns a value:

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

If a is greater that b, then a is assigned to max; otherwise, b is assigned to max.

The conditional operator is ternary, meaning it requires three operands

The conditional operator is similar to an The conditional operator is similar to an ifif--else statement, except that it is an else statement, except that it is an expression that returns a value:expression that returns a value:

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

If If aa is greater that is greater that bb, then , then aa is assigned to is assigned to maxmax; otherwise, ; otherwise, bb is assigned to is assigned to maxmax..

The conditional operator is The conditional operator is ternaryternary, , meaning it requires three operandsmeaning it requires three operands

Page 10: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

10

27 October 2007 © Ariel Shamir 19

Conditional Operator ExampleSystem.out.println ("Your change is " + count

+ ((count == 1) ? “ Shekel" : " Shekels”));

If count equals 1, “ Shekel " is printed,

otherwise “ Shekels " is printed

The conditional operator can be nested:

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

: ((b > c) ? b : c) ;

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

+ ((count == 1) ? + ((count == 1) ? ““ Shekel" : " ShekelsShekel" : " Shekels ”” ));));

If If countcount equals 1, equals 1, ““ ShekelShekel "" is printed, is printed,

otherwise otherwise ““ ShekelsShekels "" is printedis printed

The conditional operator can be nested:The conditional operator can be nested:

intint max = (a > b) ? ((a > c) ? a : c) max = (a > b) ? ((a > c) ? a : c)

: ((b > c) ? b : c) ;: ((b > c) ? b : c) ;

27 October 2007 © Ariel Shamir 20

More Assignment Operators

Often we perform an operation on a variable, then store the result back into that variable.

Java provides assignment operators that do just this. Instead of :

sum = sum + value;

you can write:

sum += value;

Often we perform an operation on a Often we perform an operation on a variable, then store the result back into variable, then store the result back into that variable.that variable.

Java provides Java provides assignment operatorsassignment operators that that do just this. Instead of :do just this. Instead of :

sum = sum + value;sum = sum + value;

you can write:you can write:

sum += value;sum += value;

Page 11: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

11

27 October 2007 © Ariel Shamir 21

Assignment Operators List

Operator+=-=*=/=%=|=&=

Examplex += y;x -= y;x *= y;x /= y;x %= y;x |= y;x &= y;

Equivalent Tox = x + y;x = x – y;x = x * y;x = x / y;x = x % y;x = x | y;x = x & y;

27 October 2007 © Ariel Shamir 22

Right Hand Side ExpressionThe right hand side of an assignment operator can be a complete expression.

The entire right-hand expression is evaluated first, then combined with the additional operation.

result /= (total-MIN) % n;

is NOT equivalent to:

result = result/(total-MIN) % n;

but equivalent to

result = result / ((total-MIN) % n);

The right hand side of an assignment operator can be a The right hand side of an assignment operator can be a complete expression.complete expression.

The entire rightThe entire right--hand expression is evaluated first, then hand expression is evaluated first, then combined with the additional operation.combined with the additional operation.

result /= (totalresult /= (total -- MIN) % n;MIN) % n;

is NOT equivalent to:is NOT equivalent to:

result = result/(totalresult = result/(total -- MIN) % n;MIN) % n;

but equivalent tobut equivalent to

result = result / ((totalresult = result / ((total -- MIN) % n);MIN) % n);

Page 12: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

12

27 October 2007 © Ariel Shamir 23

Unary Increment and Decrement Operators The ++ and -- are the increment and decrement operators.

For example the expression j++ is equivalent to j=j+1 .

The increment and decrement operators can be used as:

• Prefix – appears before what they operate on.

• Postfix – appears after what they operate on.

The The ++++ and and ---- are the increment and are the increment and decrement operators.decrement operators.

For example the expression For example the expression j++j++ is is equivalent to equivalent to j=j+1j=j+1 ..

The increment and decrement operators The increment and decrement operators can be used as:can be used as:

•• Prefix Prefix –– appears before what they operate on.appears before what they operate on.

•• Postfix Postfix –– appears after what they operate on.appears after what they operate on.

27 October 2007 © Ariel Shamir 24

Increment, Decrement Operators Usage

decrements j by 1decrements j by 1

evaluates to the value of j after it was decremented evaluates to the value of j after it was decremented

---- jj----

evaluates to the value of j before it was decremented evaluates to the value of j before it was decremented

decrements j by 1decrements j by 1

jj --------

increments j by 1increments j by 1

evaluates to the value of j after it was incrementedevaluates to the value of j after it was incremented

++j++j++++

evaluates to the value of j before it was incremented evaluates to the value of j before it was incremented

increments j by 1increments j by 1

j++j++++++

DescriptionDescriptionUseUseOperatorOperator

Page 13: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

13

27 October 2007 © Ariel Shamir 25

Inc/Dec Exampleclass IncDecExample

{

public static void main(String args[])

{

int i0,i1,i2,j=5;

i0 = ++j;

i1 = j++;

i2 = j--;

System.out.println(i0+“ “+i1 +“ “+i2);

}

}

class class IncDecExampleIncDecExample

{ {

public static void main(String public static void main(String argsargs [])[])

{ {

intint i0,i1,i2,j=5;i0,i1,i2,j=5;

i0 = ++j;i0 = ++j;

i1 = j++;i1 = j++;

i2 = ji2 = j ---- ;;

System.out.println(i0+System.out.println(i0+ ““ ““ +i1 ++i1 + ““ ““ +i2); +i2);

}}

}}

27 October 2007 © Ariel Shamir 26

Inc/Dec Example (Cont)

The output is: 6 6 7• i0 = ++j; j is pre-incremented to 6

and assigned to i0 .

• i1 = j++; j is first assigned to i1 (as 6) and then post-incremented to 7.

• i2 = j--; j with a value of 7 is assigned to i2 and then post-decremented to 6.

The output is:The output is: 6 6 76 6 7•• i0 = ++j;i0 = ++j; jj is preis pre--incremented to 6 incremented to 6

and assigned to and assigned to i0i0 ..

•• i1 = j++;i1 = j++; jj is first assigned to is first assigned to i1i1 (as (as

6) and then post6) and then post--incremented to 7.incremented to 7.

•• i2 = ji2 = j ---- ;; jj with a value of 7 is with a value of 7 is assigned to assigned to i2i2 and then postand then post--decremented decremented to 6.to 6.

Page 14: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

14

27 October 2007 © Ariel Shamir 27

More Control Flow

What if we want to

repeat some sequence

of statements many

times?

What if we want to What if we want to

repeat some sequence repeat some sequence

of statements many of statements many

times?times? statement

statement

statement

statement

27 October 2007 © Ariel Shamir 28

Iteration Statements

Iteration statements are also called loop control structures.

A loop is a repetition of certain pieces of the code several times.

In Java there are Three types of Loops:

for loop, while loop, do loop.

Iteration statements are also called Iteration statements are also called loop control structures.loop control structures.

A loop is a repetition of certain A loop is a repetition of certain pieces of the code several times. pieces of the code several times.

In Java there are Three types of In Java there are Three types of Loops:Loops:

forfor loop, loop, whilewhile loop, loop, dodo loop.loop.

Page 15: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

15

27 October 2007 © Ariel Shamir 29

For Statement for( start; limit; step_exp)

{

statement;

}

start is a statement that initializes the loop.

limit is a Boolean statement that determines when to terminate the loop.

It is evaluated before each iteration.

for( start; limit; step_exp)for( start; limit; step_exp)

{ {

statement; statement;

}}

startstart is a statement that initializes the is a statement that initializes the loop.loop.

limitlimit is a Boolean statement that is a Boolean statement that determines when to terminate the loop. determines when to terminate the loop.

It is evaluated It is evaluated beforebefore each iteration.each iteration.

27 October 2007 © Ariel Shamir 30

For Statement (Cont.)When limit is true statement is performed, when it is false the loop is terminated.

step_exp is an expression that is invoked after each iteration of the loop and is called the step of the loop.

The for loop is often used for counting from start to limit by a step size.

When When limitlimit is true is true statementstatement is is performed, when it is false the loop is performed, when it is false the loop is terminated.terminated.

step_expstep_exp is an expression that is invoked is an expression that is invoked afterafter each iteration of the loop and is each iteration of the loop and is called the step of the loop.called the step of the loop.

The The forfor loop is often used for counting loop is often used for counting from start to limit by a step size.from start to limit by a step size.

Page 16: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

16

27 October 2007 © Ariel Shamir 31

For Diagram

Limit Condition

Start

true

Statement

Step

false

27 October 2007 © Ariel Shamir 32

For Example class For_Example {

public static void main(String[] args){

int fact = 1;

for(int k=1; k<5; k++) {

fact *= k;

System.out.println(

“The factorial of “ + k +

“ is:“ + fact);

}

}

}

class For_Example {

public static void main(String[] args){

int fact = 1;

for(int k=1; k<5; k++) {

fact *= k;

System.out.println(

“The factorial of “ + k +

“ is:“ + fact);

}

}

}

Page 17: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

17

27 October 2007 © Ariel Shamir 33

While Statementwhile( Boolean_cond)

statement;

The value of Boolean_cond can be:

• true and than the statement is performed

• false and than loop terminates

The statement is executed over and over

until the boolean_condition becomes false.

while( while( Boolean_condBoolean_cond ))

statement;statement;

The value of The value of Boolean_condBoolean_cond can be:can be:

•• true and than the statement is performedtrue and than the statement is performed

•• false and than loop terminatesfalse and than loop terminates

The statement is executed over and over The statement is executed over and over

until the until the boolean_conditionboolean_condition becomes false.becomes false.

27 October 2007 © Ariel Shamir 34

While Diagram

Statement

true

falseBoolean Condition

Page 18: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

18

27 October 2007 © Ariel Shamir 35

While Exampleclass While_Example {

public static void main(String[] args){

int sum=0,k=0;

while(sum<100) { sum=sum+k;

System.out.print(

“the sum of 0 to “ + k +

” is ” + sum);

k++;

}

}}

class While_Example { class While_Example {

public static void main(String[] public static void main(String[] argsargs ){){

intint sum=0,k=0;sum=0,k=0;

while(sum<100) { while(sum<100) {

sum=sum+k;sum=sum+k;

System.out.print(System.out.print(

““ the sum of 0 to the sum of 0 to ““ + k + + k +

”” is is ”” + sum);+ sum);

k++;k++;

}}

}}

}}

27 October 2007 © Ariel Shamir 36

Do.. While Statementdo {

statement;

} while (Boolean_cond);

First, the statement performed once!

Then, the Boolean_cond is checked. If it is true the next iteration of the loop is performed. If it is false, the loop terminates.

do {do {

statement; statement;

} while (} while ( Boolean_condBoolean_cond ););

First, the statement performed once! First, the statement performed once!

Then, the Then, the Boolean_condBoolean_cond is checked. If it is checked. If it is true the next iteration of the loop is is true the next iteration of the loop is performed. If it is false, the loop performed. If it is false, the loop terminates.terminates.

Page 19: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

19

27 October 2007 © Ariel Shamir 37

Do.. While Diagram

Boolean Condition

Statement

true

false

27 October 2007 © Ariel Shamir 38

Infinite Loops

If Boolean_cond in one of the loop structures is always true then loop will be executed forever - it is ‘unbounded’.

Such a loop is called an infinite loop.

The infinite loop will execute until the program is interrupted.

If If Boolean_condBoolean_cond in one of the loop in one of the loop structures is always true then loop structures is always true then loop will be executed forever will be executed forever -- it is it is ‘‘unboundedunbounded’’..

Such a loop is called an infinite loop.Such a loop is called an infinite loop.

The infinite loop will execute until The infinite loop will execute until the program is interrupted.the program is interrupted.

Page 20: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

20

27 October 2007 © Ariel Shamir 39

Infinite Loop Example// Two infinite loops program

Class Infinity {

public static void main(String[] args){

int count=0;

for( ; ; )

System.out.print(“Infinity”);

while(count<10) {

System.out.println(

“Another infinite loop”);

System.out.println(

“The counter is “+counter);

}

}

}

// Two infinite loops program// Two infinite loops program

Class Infinity { Class Infinity {

public static void main(String[] public static void main(String[] argsargs ){){

intint count=0;count=0;

for( ; ; )for( ; ; )

System.out.print(System.out.print( ““ InfinityInfinity ”” ););

while(count<10) {while(count<10) {

System.out.printlnSystem.out.println ((

““ Another infinite loopAnother infinite loop ”” ););

System.out.printlnSystem.out.println ((

““ The counter is The counter is ““ +counter);+counter);

}}

}}

}}

27 October 2007 © Ariel Shamir 40

Nested Loops Examplefor (int row = 1; row <= numRows; row++) {

for (int column = 1;

column <= numColumns; column++) {

System.out.print(row * column + “ “);

}

System.out.println();

}

for (for ( intint row = 1; row <= row = 1; row <= numRowsnumRows; row++) {; row++) {

for (for ( intint column = 1; column = 1;

column <= column <= numColumnsnumColumns; column++) {; column++) {

System.out.print(row * column + System.out.print(row * column + ““ ““ ););

}}

System.out.printlnSystem.out.println ();();

} } Can you make this code more

efficient?

Page 21: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

21

27 October 2007 © Ariel Shamir 41

Break inside a Loop

•The break statement, (already used within the switch statement), can also be used inside a loop

•When the break statement is executed, control jumps to the statement after the loop (the condition is not evaluated again)

••The The breakbreak statement, (already used statement, (already used within the within the switchswitch statement), can statement), can also be used inside a loopalso be used inside a loop

••When the When the breakbreak statement is statement is executed, control jumps to the executed, control jumps to the statement after the loop (the statement after the loop (the condition is not evaluated again)condition is not evaluated again)

27 October 2007 © Ariel Shamir 42

Continue inside a Loop

•A similar statement to the break is continue inside loops

•When the continue statement is executed, control jumps to the end of the loop and the condition is evaluated (possibly entering the loop statements again)

••A similar statement to the A similar statement to the breakbreak is is continuecontinue inside loops inside loops

••When the When the continuecontinue statement is statement is executed, control jumps to the end of executed, control jumps to the end of the loop and the condition is the loop and the condition is evaluated (possibly entering the loop evaluated (possibly entering the loop statements again)statements again)

Page 22: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

22

27 October 2007 © Ariel Shamir 43

Break and Continue Example

for (;;) {

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

if (n == 0)

break;

if (n%2 == 1)

continue;

sum += n;

}

System.out.print(

“The sum of all input even numbers is “ + sum);

for (;;) {for (;;) {

Scanner sc = new Scanner sc = new Scanner(System.inScanner(System.in ););

intint n = n = sc.nextIntsc.nextInt ();();

if (n == 0)if (n == 0)

break;break;

if (n%2 == 1)if (n%2 == 1)

continue;continue;

sum += n;sum += n;

}}

System.out.print(System.out.print(

““ The sum of all input even numbers is The sum of all input even numbers is ““ + sum);+ sum);

Can you modify it to get rid of the break

and continue ?

27 October 2007 © Ariel Shamir 44

Division Into Methods

Complicated tasks or tasks that occur often within a class should be wrapped in a method

It is helpful when implementing algorithms, or when we need “helper”methods in classes.

This will increase the readability and manageability of the code

Complicated tasks or tasks that occur Complicated tasks or tasks that occur often within a class should be wrapped in often within a class should be wrapped in a methoda method

It is helpful when implementing It is helpful when implementing algorithms, or when we need algorithms, or when we need ““helperhelper””methods in classes.methods in classes.

This will increase the readability and This will increase the readability and manageability of the codemanageability of the code

Page 23: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

23

27 October 2007 © Ariel Shamir 45

Sub Tasks Example

Task: calculate & print the average

and median of all students:

Get the grades of a student

Calculate the average

Calculate the median

Task: calculate & print the average Task: calculate & print the average

and median of all students:and median of all students:

Get the grades of a studentGet the grades of a student

Calculate the averageCalculate the average

Calculate the medianCalculate the median

OuterLoopOn Students

Inner Loops On Grades

27 October 2007 © Ariel Shamir 46

Sub Tasks Example

Task: calculate & print the average

and median of all students:

Get the grades of a student

Calculate the average

Calculate the median

Task: calculate & print the average Task: calculate & print the average

and median of all students:and median of all students:

Get the grades of a studentGet the grades of a student

Calculate the averageCalculate the average

Calculate the medianCalculate the median

OuterLoopOn Students

Define as methods

Page 24: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

24

27 October 2007 © Ariel Shamir 47

Defining Methods

Simplify and structure the program

code using sub-tasks

Reuse of the same piece of code (the

method) in many places

Simplify and structure the program Simplify and structure the program

code using subcode using sub--taskstasks

Reuse of the same piece of code (the Reuse of the same piece of code (the

method) in many placesmethod) in many places

27 October 2007 © Ariel Shamir 48

Example 1: Finding Primes// Prints all the prime numbers in a range

public class Primes {

public static final int RANGE = 1000;

public static void main(String[] args) {

int number = 0;

while (number < RANGE) {

number = number + 1;

for (int n = 0 ; n < number ; n++) {

//...check if n divides number...

}

}

}

}

// Prints all the prime numbers in a range

public class Primes {

public static final int RANGE = 1000;

public static void main(String[] args) {

int number = 0;

while (number < RANGE) {

number = number + 1;

for (int n = 0 ; n < number ; n++) {

//...check if n divides number...

}

}

}

}

Page 25: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

25

27 October 2007 © Ariel Shamir 49

Example 1 (Cont.)// Prints all the prime numbers in a range

public class Primes {

public static final int RANGE = 1000;

public static void main(String[] args) {

int number = 0;

while (number < RANGE) {

number = number + 1;

if (isPrime(number))

out.println(number);

}

}

}

// Prints all the prime numbers in a range

public class Primes {

public static final int RANGE = 1000;

public static void main(String[] args) {

int number = 0;

while (number < RANGE) {

number = number + 1;

if (isPrime(number))

out.println(number);

}

}

}

27 October 2007 © Ariel Shamir 50

Example 1 (Cont.)// Prints all the prime numbers in a range

public class Primes {

public static void main(String[] args) {

//...

if (isPrime(number))

//...

}

// Returns true iff number is prime

public static boolean isPrime(int number) {

// determines if number is prime

}

}

// Prints all the prime numbers in a range

public class Primes {

public static void main(String[] args) {

//...

if (isPrime(number))

//...

}

// Returns true iff number is prime

public static boolean isPrime(int number) {

// determines if number is prime

}

}

Page 26: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

26

27 October 2007 © Ariel Shamir 51

Example 2: Magic NumberA magic number is a number who’s sum of cubes

of digits equals itself:

XYZ = X3 + Y3 + Z3

Finding all magic numbers in the range 1-M:

• For each n in the range 1-M:

– Compute the sum of cubes of digits of n

– Check if this sum equals n

A magic number is a number whoA magic number is a number who’’s sum of cubes s sum of cubes

of digits equals itself:of digits equals itself:

XYZ = XXYZ = X33 + Y+ Y33 + Z+ Z33

Finding all magic numbers in the range 1Finding all magic numbers in the range 1--M:M:

•• For each n in the range 1For each n in the range 1--M:M:

–– Compute the sum of cubes of digits of nCompute the sum of cubes of digits of n

–– Check if this sum equals nCheck if this sum equals n

27 October 2007 © Ariel Shamir 52

/*** Returns the sum of cubes of digits of n*/

static int sumOfCubesOfDigits (int n) {// …

}

SumofCubes MethodFinding all magic numbers in the range 1-M:

• For each n in the range 1-M:

– Compute the sum of cubes of digits of n

– Check if this sum equals n

Finding all magic numbers in the range 1Finding all magic numbers in the range 1--M:M:

•• For each n in the range 1For each n in the range 1--M:M:

–– Compute the sum of cubes of digits of nCompute the sum of cubes of digits of n

–– Check if this sum equals nCheck if this sum equals n

Page 27: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

27

27 October 2007 © Ariel Shamir 53

Method Header

We declare methods in a similar way to the way the method main was declared:public static void main(String[] args)

{

// the code

}

public static double average(int num1,int num2)

{

// the code

}

We declare methods in a similar way to We declare methods in a similar way to the way the method main was declared:the way the method main was declared:public static void main(String[] args)

{

// the code

}

public static double average(int num1,int num2)

{

// the code

}

parameters

name

return type

27 October 2007 © Ariel Shamir 54

Methods Modifiers

The modifier public denotes that the method is exposes to outside world (more on this later)

The modifier static denotes that this method can be called without creating an object of this type (more on this too, later)

The modifier The modifier public denotes that denotes that the method is exposes to outside the method is exposes to outside world (more on this later)world (more on this later)

The modifier The modifier static denotes that denotes that this method can be called without this method can be called without creating an object of this type (more creating an object of this type (more on this too, later)on this too, later)

Page 28: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

28

27 October 2007 © Ariel Shamir 55

Return Types

The return type of a method indicates the type of value that the method sends back to the calling client.

The return-type of average () is double . When a client calls the method average ()it will get the answer as a double value.

The keyword void denotes that the method has no return value (main() )

The return type of a method indicates the The return type of a method indicates the type of value that the method sends back type of value that the method sends back to the calling client.to the calling client.

The returnThe return--type of type of average ()() is is doubledouble . . When a client calls the method When a client calls the method average ()()it will get the answer as a it will get the answer as a doubledouble value.value.

The keyword The keyword void denotes that the method denotes that the method has no return value (has no return value (main() ))

27 October 2007 © Ariel Shamir 56

Method Return Typespublic static double average (int num1,int num2) {

...

}

public static int sumOfCubesOfDigits (int n) {

...

}

public static boolean isPrime (int number) {

...

}

public static void main (String[] args) {

...

}

public static double average (int num1,int num2) {

...

}

public static int sumOfCubesOfDigits (int n) {

...

}

public static boolean isPrime (int number) {

...

}

public static void main (String[] args) {

...

}

Page 29: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

29

27 October 2007 © Ariel Shamir 57

Return Statementreturn <expression>;

In the method definition, the returnstatement specifies the value that should be returned, which must conform with the return type of the method.

If the method returns void you can just use return; or you can omit the statement (and reach the end of all the method statements)

return <expression>;return <expression>;

In the method definition, the In the method definition, the returnreturnstatement specifies the value that should statement specifies the value that should be returned, which must conform with the be returned, which must conform with the return type of the method. return type of the method.

If the method returns void you can just use If the method returns void you can just use return; return; or you can omit the statement or you can omit the statement (and reach the end of all the method (and reach the end of all the method statements)statements)

27 October 2007 © Ariel Shamir 58

Using the Return Valuedouble avg;

// more code…

avg = average(33,56);

double double avgavg ;;

// more code// more code ……

avgavg = average(33,56);= average(33,56);

Theaverageaverage

method will be invoked

It will return a value which is assigned to avgavg

The parameters sent toaverageaverage

Page 30: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

30

27 October 2007 © Ariel Shamir 59

Method Parameters

To invoke a method you must use the correct

1. Number of parameters

2. Type of parameters

3. Order of parameters

Sometimes there are several methods with the same name – be careful!

To invoke a method you must use the To invoke a method you must use the correctcorrect

1.1. Number of parametersNumber of parameters

2.2. Type of parametersType of parameters

3.3. Order of parametersOrder of parameters

Sometimes there are several methods Sometimes there are several methods with the same name with the same name –– be careful!be careful!

27 October 2007 © Ariel Shamir 60

Passing Parameters

When a parameter is passed, a copy

of the value is made and assigned to

the formal parameter:double avg;

avg = average(33,56);

public static double average(int num1,int num2)

When a parameter is passed, a copy When a parameter is passed, a copy

of the value is made and assigned to of the value is made and assigned to

the formal parameter:the formal parameter:double double avgavg ;;

avgavg = average(33,56);= average(33,56);

public static double average(int num1,int num2)

Page 31: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

31

27 October 2007 © Ariel Shamir 61

Code Example

Parameters can be used as any other variable

The return expression must match the return typepublic static double average(int num1,int num2)

{

return (num1 + num2)/2.0;

}

Parameters can be used as any other Parameters can be used as any other variablevariable

The return expression must match the The return expression must match the return typereturn typepublic static double average(int num1,int num2)

{

return (num1 + num2)/2.0;

}

27 October 2007 © Ariel Shamir 62

Method control flow

Instead of writing a long list of

instructions we write a collection of

methods and invoke (or call) them

one after another.

Instead of writing a long list of Instead of writing a long list of

instructions we write a collection of instructions we write a collection of

methods and invoke (or call) them methods and invoke (or call) them

one after another.one after another.

...

main()

M1()

M2()

Main invokes M1M1 invokes M2Main invokes…

Page 32: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

32

27 October 2007 © Ariel Shamir 63

Control Flow Chart

We decomposed a problem into series of

simpler methods. The invoked method

could be part of another class or object.

We decomposed a problem into series of We decomposed a problem into series of

simpler methods. The invoked method simpler methods. The invoked method

could be part of another class or object.could be part of another class or object.

M1 M2

M2();obj.M1();

main

27 October 2007 © Ariel Shamir 64

The RandomClass

A program may need to produce a random number (DiceSimulation . java ).

The Random class provides methods to simulate a random number generator.

The nextInt method returns a random number from the entire spectrum of intvalues. Usually, this number is be scaledand shifted to the desired range.

A program may need to produce a random A program may need to produce a random number (number (DiceSimulation . java ).).

TheThe Random class provides methods to class provides methods to simulate a simulate a random number generator.random number generator.

TheThe nextInt method returns a random method returns a random number from the entire spectrum ofnumber from the entire spectrum of int

values. Usually, this number is be values. Usually, this number is be scaledscaledand and shiftedshifted to the desired range.to the desired range.

Page 33: Programming Constructs Overview - IDC · 2007-10-27 · 2 27 October 2007 © Ariel Shamir 3 Method Parameters If the method requires parameters, they come inside the parentheses as

33

27 October 2007 © Ariel Shamir 65

Random Class Exampleimport java.util.Random;

// This program simulates a tossing of a dice

class DiceSimulation {

static final int NUMBER_OF_TOSSES = 10;

public static void main(String[] args) {

int sum = 0;

int count = 0;

Random rndGen = new Random();

import java.util.Random;

// This program simulates a tossing of a dice

class DiceSimulation {

static final int NUMBER_OF_TOSSES = 10;

public static void main(String[] args) {

int sum = 0;

int count = 0;

Random rndGen = new Random();

27 October 2007 © Ariel Shamir 66

Random Class Example while(count<=NUMBER_OF_TOSSES) {

int result =

Math.abs(rndGen.nextInt())%6+1;

sum = sum + result;

count = count + 1;

}

System.out.println(

“The sum of tosses is “+sum);

}

}

while(count<=NUMBER_OF_TOSSES) {

int result =

Math.abs(rndGen.nextInt())%6+1;

sum = sum + result;

count = count + 1;

}

System.out.println(

“The sum of tosses is “+sum);

}

}