cmps 135 introduction to programming instructor: dr. cong-cong xing

192
CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Upload: giles-york

Post on 28-Dec-2015

224 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

CMPS 135 Introduction to Programming

Instructor:

Dr. Cong-Cong Xing

Page 2: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Part I

Overview of Computers and Programming

Page 3: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

0. Java

High level programming language Developed by James Gosling (and his

team) at Sun Microsystems in 1991. Formally born in 1995 Naming: oak (tree) Java (coffee) High popularity in industry and academia

Page 4: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

1. Computer Hardware System

Basic architecture

CPUInput devices Output devices

Storage devices

Page 5: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Input devices– Enter data into computers– Ex: keyboard, scanner

Output devices– Observe computation results– Ex: monitor, printer

Page 6: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

CPU (Central Processing Unit)– Control unit: coordinate all computation tasks– ALU (arithmetic-logic unit): carry out computations

Page 7: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Storage devices– Major storage device: memory (also called primary

memory, RAM, 1st storage device) which stores info temporarily

Page 8: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

2nd storage devices store info permanently. Ex: hard disks, floppy disk, optical disks (CDs, DVDs), U-drive

Page 9: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Motherboard (main board): host memory, CPU, etc.

Page 10: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

2. Problem Solving and Programming

Problem

Implementation

Specifications Testing

Design

Requirements

Page 11: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Problem: problem statement Requirements: complete understanding of

the problem (what needs to be done) Specs: explicit list of input(s), output(s),

relevant formulas (if any), data structures, and methodology

Page 12: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Design: algorithm (a step-by-step procedure showing how to solve the problem)

Implementation: coding of design in the chosen language (ex: Java)

Testing: try the best to ensure the program works correctly

Page 13: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

3. Overview of Programming Languages

Machine language (lowest level)– Native language for computers– Binary numbers– The only language that computers can understand– Ex: 00011100111100010 (meaning?)

Assembly language (low level)– 2-to-4 letter commands– Ex: ADD R2 R4 (meaning?)– Assembly programs needs to be translated into

machine programs by assembler

Page 14: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

High-level languages– English-like constructs– Ex: x = a+b (meaning?)– Examples of high-level languages

• Pascal, C, C++, Fortran, COBOL, Java

Page 15: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

4. Processing a High-level Language

editor Sourcefile

CompileSource file

Objectfile

Linker/loader

executablein RAM

Fix err err

MoreObj files

Page 16: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Part II

Welcome to Java

Page 17: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

1. The First Program

// my first Java program

public class Greeting

{ public static void main (String args[])

{ System.out.println(“Welcome to Java”);

}

}

Page 18: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

2. Dissection of the First Program

What is the output of the program?– Welcome to Java (is displayed on monitor)

How to get the output?– Compile and execute the program

Java is case-sensitive. Main, main, and MaIn are different.

Line by line interpretation (informally)

Page 19: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

// my first Java program

public class Greeting

{ public static void main (String args[])

{ System.out.println(“Welcome to Java”);

}

}

Comments. Ignored by compiler.Starts the def of class Greeting

“public” and “class” are key words“Greeting” can be changed

Starts the def of method mainNecessary for every Java program

Every “word” is fixedProg execution starts here

Printout “Welcome to Java”On monitor

Signifies the begin and end Class Greeting and

Method main

Page 20: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

3. Compilation and Execution (GUI Dr. Java)

Page 21: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Compilation and Execution (command line)

Every java program must be save in a file ended with .java– Ex: Greeting.java

Compilation: javac <filename>– Ex: javac Greeting.java

Execution: java <filename (w/o .java)>– Ex: java Greeting

Page 22: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

(Why command line then?)

Page 23: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

4. Java Packages

Many predefined classes are grouped together to form various packages. Ex: class JOptionPane is in package javax.swing

How to use packages?– Syntax: import <name of package>

Ex: print “welcome to java” again

Page 24: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

import javax.swing.JOptionPane;public class GreetingAgain{ public static void main (String args[]) { JOptionPane.showMessageDialog(null, “Welcome to Java”); System.exit(0); } }

Direct compiler to load JOptionPane

Terminate progSuccessfully.

Required for GUI.

Print “welcom to Java” in a

Pop-up window(See next slide)

Page 25: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Page 26: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Part III

Basic Elements

Page 27: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

1. Identifiers

Names that users make up for describing data and programs

Ex: Greeting (a class name) Rule to make identifiers

– A letter (a – z or A – Z) followed by a combination of letters and digits (0 – 9)

More examples:

Page 28: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

A, a, Max, MAX, daysOfWeek (legal) %right, 30days, #missing (illegal)

Page 29: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

2. Data Types and Values

Name Type Ex of values

int Integer 1, 2, -1, -2, 3

double Real number 1.0, 2.3, -4.5

char Character ‘a’, ‘m’, ‘1’

String (S is capital)

Strings “abc”, “123d”

boolean Logical true, false

Page 30: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

3. Variables

Special identifiers that hold certain type of data Each variable corresponds to a memory location

(or memory cell)– Ex: a 2 variable a holds 2– b 1.23 variable b holds 1.23

Value of variables may be changed (by programmers) at any time

Each variable must have a data type

Page 31: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

4. Declaration of variables

Syntax– <type> var1, var2, …, varn;

Ex: – int a, b, c; --------------(a) – double A; --------------(b)

Meaning: (a) declares variables a, b, and c are of type int. (b) declares variable A is of type double

Every variable must be declared first before it can be used

Page 32: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

5. Arithmetic Expressions

Math formulas expressed in Java Addition operator: +

– In math: a+b– In Java: a+b

Subtraction operator: -– In math: a-c– In Java: a-c

Multiplication operator: *– In math: b×c– In Java: b*c

Page 33: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Division operator: /– In math: a÷b– In Java: a/b

Modulo operator: %– In math: a mod b (the remainder of a÷b)– In Java: a%b– Ex: 7%4 = 3

Page 34: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Note: a/b, when both a and b are integers, the result of a/b is also an integer (the integer part of the quotient, no rounding). Otherwise, the result is a real.

Ex: 7/4 = 1 2/4 = 0 2.0/4 = 0.5 2/4.0 = 0.5 2.0/4.0 = 0.5

Page 35: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

3/2 hours = how many seconds ?

60*60*3/2 or 3/2*60*60 or neither

Page 36: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

More examples

math Java

(a+b+c)÷3 (a+b+c)/3

a+b-c÷2 a+b-c/2

(b2-4ac) ÷2a (b*b-4*a*c)/(2*a)

(a+b)(a-b) ÷(a2-b2) fill in

Page 37: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

6. Precedence of Operators

From highest to lowest:

( )

* / %

+ - For operator of the same level: innermost

first, from left to right Consistent with math

high

low

Page 38: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: evaluation tree of (a+b+c)/3

(a + b + c) / 3

+

/

1

2

3

result

+

Page 39: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Ex: evaluation tree of (b*b-4*a*c)/(2*a)

(b * b – 4 * a * c) / (2 * a)

/

*

-

*

**1

2

3

4

5

6

result

Page 40: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

7. Assignment Statements

Syntax: <var> = <expression>; Ex: a = 1; b = 2; b = a+b-2; a = a+1; b = b – 1; Meaning: evaluates the expression on the right

first and stores the result of evaluation into the variable on the left (a memory cell).

Note: = does not mean “equal”! Types on both sides of = MUST match!

Page 41: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

8. Keywords

Reserved words by Java. They have special meanings to Java and should be avoided by users.

Examples: int, double, boolean, char,

while, if, for, void, static

Page 42: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

9. Input and Output

String type: another data type in Java. Any double quoted sequence of symbols are of type String.

Ex: “123”, “ab”, “ab45H$%”,

“1”, “_”, “ “

Page 43: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Input statement: reads data into programs– Syntax:

import javax.swing.JOptionPane;

<var> = JOptionPane.showInputDialog(“___”);

note: <var> must be of type String– Meaning: prompts and reads data into variable var– Convert string type variable vstr to int or double type

• <var> = Integer.parseInt(vstr);• <var> = Double.parseDouble(vstr);

Page 44: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: the following statements

String astr; int a; astr=JOptionPane.showInputDialog(“enter a value for a”);

a = Interger.parseInt(astr);

pops up a window and prompts for input and converts astr (String type) to a (int type)

Page 45: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Output statement: display computation results on monitor.– Syntax: System.out.println(“msg”+var); or

System.out.print(“msg”+var);– Meaning: print msg and the value of variable

var on the monitor. – with ln, line is changed. w/o ln, line is not

changed.

Page 46: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– Ex: the statements

a = 1; b =2;

System.out.println(“value of a is: ”+a);

System.out.println(“value of b is: ”+b);

Produces the following on monitor:

value of a is: 1

value of a is: 2

Page 47: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– Ex: the statements

a = 1; b =2;

System.out.print(“value of a is: ”+a);

System.out.println(“value of b is: ”+b);

Produces the following on monitor:

value of a is: 1value of b is: 2

Page 48: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

10. Case Study

Problem: write a Java program that prompts and inputs a radius of a circle and computes the area of the circle.

Requirements: users enter the radius, program outputs the corresponding area.

Specification: – Input(s): radius of a circle– Output(s): area of the circle– Relevant formula: area = pi*radius*radius

Page 49: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– Data structure (dictionary of variables)

Name Type Usage

r double Input, used to hold radius

rs String String variable for r

area double Output, used to hold the result

Page 50: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d Design (structure chart) (How to read the chart? from left to right, from top to

bottom)

START

Declare r, area, rs

double r,areaString rs

Prompt and read r

rs=JOptionPane.showInputDialog(“enter a radius”);

r=Double.parseDouble(rs);

Echor

System.out.println(“radius is”+r);

Computes area

area=pi*r*r

Display area

System.out.println(“area is “+area);

Page 51: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Test Cases: hand-compute some problem instances and use them to run/test your program

r area

1.0 3.14

2.3 16.6

11.2 393.9

Page 52: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Implementation (coding): translate the structure chart into Java code. (next page)

Page 53: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

// Name: your name // NSU#: your N-# // date: today's date // course: course # // description: this program prompts a radius of a circle and outputs // the area of the circle

import javax.swing.JOptionPane;

public class CompArea { public static void main(String args[]) { // declaration of variable String rs; double r, area;

Page 54: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

// prompts and reads radius rs = JOptionPane.showInputDialog("Enter a radius"); // convert rs to a real number r = Double.parseDouble(rs);

// echo the radius(for printout purpose) System.out.println("The radius is: "+r);

// compute the area area = Math.PI*r*r;

// display the result System.out.println("The area is: "+area);

// terminate the program System.exit(0); } } // end of program

Page 55: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Part IV

Selection Structures

Page 56: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

1. Relational and Logical Operators

Relation expressions

Operator Meaning Example Value

< < 1<2, x<1 true, depending on x

> > 3>4 false

<= ≤ 3.1<=3.2 true

>= ≥ 100>=100 true

== = (equal) 3 == 3 true

!= ≠ 3 != 3 false

Page 57: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Logic expressions– Logic “and” operator (&&) (a, b are any

expressions of type boolean)

a b a && b

true true true

true false false

false true false

false false false

Page 58: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: true && false false

(1>3) && (3>1) false

(1>=1) && (1<=1) && (1==1) true

Note : true and false are values (of type boolean). Just like numbers can be used to build arithmetic expressions, true and false can be used to build relational and logic expressions.

Page 59: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

– Logic “or” (||) (a, b are any expressions of type boolean)

a b a || b

true true true

true false true

false true true

false false false

Page 60: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d ex: true || false true

(1>2) || (3>4) false

((1>3)&&(3>1)) || (2>1) true

– Logic “not” (!) (a is any expression of type boolean)

a !a

true false

false true

Page 61: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

ex: !true false

!(1>2) true

!(1>3) && (3>1) true

((1>2) && (1==1)) || (!(2>3)) true

(true || (4>=4)) && !(!(4<4)) false

Page 62: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Comparing relational expressions, logic expressions and arithmetic expressions. They are all expressions and each has a type and a value.

Relational exp

Logic exp Arithmetic exp

type boolean boolean int or double

example

3>4 5==5 (1>2) || (3==5) 3+4 (5+4)*2

value false true false 7 18

Page 63: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

2. Precedence of Operators

From highest to lowest: ( ) ! * / % + -< <= > >=== !=&&||

Page 64: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: evaluation tree

1 > 2 || 2 > 1

>

||

>1 2

3

true

false true

Page 65: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

(1 >= 2) || (3 < 4) && (5 != 5)

>=

||

<

&&

!=12 3

4

5

false true false

false

false

Page 66: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

3. if Statement

Syntax:

if (condition) { statement 1; statement 2; …..

statement n; }note: condition must be a

boolean expression Meaning: (in flow chart)

cond

stmnt1

stmnt2

stmntn

falsetrue

note: this is not a structure chart

Page 67: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex:

if ( grade >= 60 )

{ System.out.println(“you passed”);

System.out.println(“good work”); }

Its structure chart:grade>=60

print “you passed”

T

print “goodwork”

Page 68: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

4. if-else Statement

Syntax: if (condition) { stmnt1; ….. stmntn; } else { stmnt1’; ….. stmntn’; } Meaning: (in flow chart)

cond

stmnt1

stmntn stmntn’

stmnt1’

truefalse

note: this is not a structure chart

Page 69: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: if (grade >=60) { System.out.println(“you passed”); System.out.println(“congratulations!”); } else { System.out.println(“you failed”);

System.out.println(“work harder!”); }

Page 70: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Its structure chart

grade>=60

print “youpassed”

print “congratulations”

print “work harder”

print “youfailed”

T F

Page 71: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d Note:

– In if and if-else statements, if there is only one statement after if (or else), the pair of { } can be omitted. Conversely, if there is no { } after if (or else) in if and if-else statements, the system will take the first statement (whatever it is) after if (or else) as the “true” (or “false”) body. The rule of thumb is: always put a pair of { } around the “true” and “false” bodies.

Page 72: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: what’s the output of the following code fragment?

Temp = 56;

if (Temp>55)

{ System.out.println(“HD temp is over 55 degree!”);

System.out.println(“Shut down system immediately!”);

}

else

{ System.out.println(“HD temp is OK”);

System.out.println(“Keep monitoring HD”);

}

Page 73: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: what’s the output of the following code fragment?

Temp = 56;

if (Temp>55)

{ System.out.println(“HD temp is over 55 degree!”);

System.out.println(“Shut down system immediately!”);

}

else

System.out.println(“HD temp is OK”);

System.out.println(“Keep monitoring HD”);

Page 74: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: what’s the output of the following code fragment?

Temp = 56;

if (Temp>55)

System.out.println(“HD temp is over 55 degree!”);

System.out.println(“Shut down system immediately!”);

else

{ System.out.println(“HD temp is OK”);

System.out.println(“Keep monitoring HD”);

}

Page 75: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: what’s the output of the following code fragment?

Temp = 56;

if (Temp>55)

System.out.println(“HD temp is over 55 degree!”);

System.out.println(“Shut down system immediately!”);

else

System.out.println(“HD temp is OK”);

System.out.println(“Keep monitoring HD”);

Page 76: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: Given x, write a code fragment s.t. if x=0, print zero; if

x>0, print positive; if x<0, print negative.

Idea? (design?)

X=0?

X>0?zero

pos neg

T F

T F

Page 77: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

if (x==0){ System.out.println(“zero”);}else{ if (x>0) { System.out.println(“positive”); } else { System.out.println(“negative”); }}

Page 78: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

An alternative design:

if (x==0) System.out.println(“zero”);if (x>0) System.out.println(“positive”);if (x<0) System.out.println(“negative”);

X>0?X=0? X<0?

zero pos neg

T T T

Page 79: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Case study

Find the max among 3 integers.– Problem: Given 3 integers, find the largest

one.– Requirements: write a Java program which

prompts and reads 3 integers, compare them, and outputs the largest integer. E.g., given 3,4,10, then 10 should be selected.

Page 80: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– Specifications: • Input(s): 3 integers• Output(s): the largest one among the 3 integers• Relevant formula: n/a. The major computation is

comparison.• Data structure: (next pg)

Page 81: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Name Type Usage

a int input, hold the 1st integer

b int input, hold the 2nd integer

c int input, hold the 3rd integer

sa String string for a

sb String string for b

sc String string for c

largest int output, hold the largest integer

Page 82: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– Design

start

P & Ra, b, c

Find the max

output end

Read sa Read sb Read sc

largest =a largest=b nothing largest=c

displaylargest

Convertsa to a

Echo ofa

Convert sb to b

Echo ofb

Convert sc to c

Echo of c

a>=b largest>=c

T F T F

Page 83: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– Test cases

inputs output

a b c largest

1 2 3 3

10 24 -5

24

100 34 90 100

-1 -34 -3 -1

Page 84: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

An alternative solution – Design (partial)

a>=b

a>=cb>=c

display c display b display c display a

f t

f t f t

Page 85: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

5. Switch Statement

Syntax: switch (expression) { case label1: stmnt1; break; case label2: stmnt2; break; …… case labeln: stmntn; break; default: default stmnt; break; }

Note: * break cannot be missed *if two or more cases have the same action, we can combine them: case label1; case label2; stmnts; beak; *type of expression must be int or char. Type of label must be of the same type as that of expression.

Page 86: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Meaning (flow chart)

exp=l1

exp=l2

exp=ln

default

breakstmntn

breakstmnt2

breakstmnt1t

f

t

f

t

f

Page 87: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Structure chartSwitch()

stmnt1 stmnt2 stmnt3 stmntn

exp=l1 exp=l2 exp=l3exp=ln

Page 88: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: (num is a variable of type int) switch (num) { case 1: System.out.println(“It’s 1”); break; case 2: System.out.println(“It’s 2”); break; case 3: case 4: case 5: System.out.println(“It’s 3 or 4 or 5”); break; default: System.out.println(“Invalid data”); break; }

Page 89: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Case Study– Problem: computes a student’s letter grade by the following

chart. (assume score is an integer between 0 and 100) score grade 90+ A 80 – 89 B 70 – 79 C 60 – 69 D 59- F

Page 90: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– Requirements:• Users enter a student’s number grade (e.g. 85), the program

outputs the corresponding letter grade (e.g. B).

– Specifications:• Input(s): a number grade (integer)• Output(s): the corresponding letter grade• Formula: no specific formula. Job is done through

comparisons.• Data structure:

Page 91: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Name Type Usage

score int hold input (number grade)

sscore String String for score

grd int Scaled-down of score

Page 92: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– Design– Q: how to “map” 99, 98, 97,…,90 all to 9 so that we

can output an A? (89, …,80 all to 8, 79,..,70 all to 7, …..)

– A: (trick)type casting reals to integer: coerce reals to integers by dropping everything after decimal point.

example: (int) (8.9) = 8 (int) (99/10.0) = 9 (int) (4.0) = 4 (int) (98/10.0) = 9 (int) (-4.3) = -4 (int) (97/10.0) = 9

Page 93: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

(structure chart)

START

P&Rsscore

Decide lettergrade

end

Convetsscore

to score

Echoscore

grd=(int)(score/10.0)

switch(grd)

print “A” print”B” print “C” print “D” print “F”

10,9 8 6 5,4,3,2,1,0switch(grd)

7

Page 94: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

cont’d

– Test cases

– Implementation: (next page)

score 100 95 81 89 75 70 66 51 0

grade A A B B C C D F F

Page 95: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– Implementation (partial)– switch(grd)– { case 10: case 9:– System.out.println("A"); break; – case 8:– System.out.println("B"); break;– case 7:– System.out.println("C"); break;– case 6:– System.out.println("D"); break;– case 5: case 4: case 3: case 2: case 1: case 0:– System.out.println(“F"); break;– default:– System.out.println(“invalid data"); break;– }

Page 96: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Part V

Loops

Page 97: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

1. while loop

Syntax: while (cond)

{ stmnt1;

…..

stmntn;

}

note: cond must be a boolean expression

loopbody

Page 98: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Meaning (in flow chart)

cond

stm1

stm2

stmn

f

t

In English:(1) cond is evaluated first. As long as cond is true, all statements in the loop body will be executed one by one (probably many times). (2) at the time cond becomes false, the first statement out of loop body will be executed. Loop is exited.

other stmnt

Page 99: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Meaning (in structure chart)

stmnt1 stmnt2 stmntn

cond

Page 100: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: what’s the output of the code fragment?

counter = 1;

while (counter <= 5)

{ System.out.print(counter);

counter = counter + 1;

}

Page 101: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Output is : 12345

How many times has the body of loop been executed? 5 (not 6). There is an attempt for the 6th loop, but it is aborted.

Loop Val of counter at entry of loop

Counter <=5?

Output so far

1 1 true 1

2 2 true 12

3 3 true 123

4 4 true 1234

5 5 true 12345

6 6 false (exit loop)

Page 102: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex:

counter = 1; while (counter < 5) { System.out.print(counter); counter = counter + 1; }

How many times will the body be executed?

Page 103: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex:

counter = 1; while (counter > 0) { System.out.print(counter); counter = counter + 1; }

How many times will the body be executed?

Page 104: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex:

counter = 1; while (counter < 0) { System.out.print(counter); counter = counter + 1; }

How many times will the body be executed?

Page 105: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: output of the following code fragment?

c=10; while (c>=1) { System.out.print(c); c = c-1; }

10987654321

Loop printed Val of c

1 10 9

2 9 8

3 8 7

4 7 6

5 6 5

6 5 4

7 4 3

8 3 2

9 2 1

10 1 0

Page 106: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: a typical use of while loop – control the validity of input data. Suppose we want to read a radius (r) of a circle, we can use the following code to ensure the entered radius must be nonnegative.

while (r<0) { // print some warning message System.out.println(“Invalid data, try again”);

// use JOptionPane to read radius again rs = JOptionPane.showInputDialog("Enter a radius"); r = Double.parseDouble(rs); }

Page 107: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: another typical use of while loop – controls the stop/continuation of programs.

….. answer = 1;

while(answer ==1) { // do whatever computation, e.g. compute area // output results

// prompts to stop/continue the program answerstr = JOptionPane.showInputDialog(“Do you want to

continue? 1-yes,0-no”); answer = Integer.parseInt(answerstr); }

System.out.println(“bye”); …………

Page 108: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: compute 2100

idea: 2100 = 2*2*…*2 (100 times). Set up a loop running 100 times. In each time, a 2 is multiplied to the current result.

code (fragment):

prod = 1; counter=1; while(counter <= 100) { prod = prod * 2.0 ; // why not 2? counter = counter+1; } // prod holds the result. Print prod

Page 109: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

How does it work?

loop counter at entry of loop

counter<= 100?

prod at end of loop

1 1 true 21 (2)

2 2 true 22 (2*2)

3 3 true 23 (2*2*2)

…. … … ….

100 100 true 2100 (2*…*2)

101 101 false

Page 110: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: compute 1+2+…+100

c=1; sum=0; while (c<=100) { sum = sum +c; c = c + 1; } // sum holds the result, print sum

Page 111: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: compute n! for any natural number n. Note: n! is called the factorial of n and is defined as: n! = 1*2*….*n e.g., 3! = 1*2*3 = 6 4! = 1*2*3*4 = 24 1! = 1 0! = 1 (defined)

Page 112: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Code (partial)

p=1; c=1; // initialize p and c

while (c<=n) // n acquires a value before this point

{ p = p*c;

c = c + 1;

}

// p holds n!, we can printout p

Page 113: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

How does the loop work?

loop c at entry of loop

c <= n? (e.g. n=100)

p at end of loop

1 1 true 1! (1)

2 2 true 2! (1*2)

3 3 true 3! (1*2*3)

…. … … ….

100 100 true 100! (1*2…*100)

101 101 false

Page 114: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: compute 1!+2!+…+n! for any natural number n>0. e.g.:

if n=1, 1!=1 if n=3, 1!+2!+3!=9

s=0; p=1; y=1; while (y <=n) // whatever n is { p = p*y; s = s+p; y = y+1; } // s holds the result

Page 115: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Case Study– Problem: compute the average of your computer

science class– Requirements: Users enter each student’s grade into

computer and enters 9999 to signify the end. The program takes these grades and computes the average. (Note: users do not need to input the number of students into computer, the program should be able to detect the number of students automatically.)

– Specifications:• Inputs: each student’s grade• Output: the average of those grade

Page 116: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

• Relevant formula:

avg = total grade/number of students• major programming construct: loops• Data structure:

Name Type Usage

grd double holds each student’s grade. Input

sum double holds the total grade

n int holds the number of students

avg double holds average. Ouput

grdstr String associated with grade

Page 117: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– Design: (note how the– loop is represented) START

P & R first grade

grdstr

Convertgrdstr to grd

echo

sum=0n=0

accumulate total grade

add curren

tgrd to

total

sum=sum+grd

increase #of students

n=n+1

P &Rgrdstr

convertgrdstrto grd

echo

computeavgerage

avg=sum/n

displayavg end

whilegrd !=9999

Page 118: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– Test Case:

– Implementation:

avg

grd 10 55 69 100 98 76 58 85 73 75 69

grd 100 99 98 95 76 83 92 100 91 51 66 95

Page 119: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

// Name: your name// ssn: your ssn// date: today's date// course: cmps120// description: fill out by yourself

import javax.swing.JOptionPane;

public class CompAvg{ public static void main(String args[]) { // declaration of variables String grdstr; double grd, avg, sum; int n;

// prompts and reads the first grade grdstr = JOptionPane.showInputDialog("Enter a grade");

Page 120: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

// convert grdstr to grd grd = Double.parseDouble(grdstr);

// echo System.out.println("The grade is: "+grd);

// initialization sum =0; n=0;

// accumulate total grade while (grd != 9999) { sum = sum + grd; n = n+1; grdstr = JOptionPane.showInputDialog("Enter a grade"); grd = Double.parseDouble(grdstr); System.out.println("The grade is: "+grd); }

Page 121: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

// compute average avg = sum/n;

// dispaly resultSystem.out.println("The average

is:"+avg); // termination System.exit(0); }}// end of program

Page 122: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

2. For-Loop

Syntax: for (<init>;<cond>;<incre>) { body } Ex: for (i=1;i<=10;i++) { System.out.println(i); }

Page 123: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Meaning: special counter-controlled while

loop. The initialization is made first, then condition is checked. If false, the body is skipped. If true, body of the loop is executed and the increment is made and the condition is checked again. Just like the first time, what to do next strictly depends on the value of the condition. In another word, the loop will keep running until (sooner or later) the condition (value) becomes false. (see flow chart)

init

body

incre

cond

t

f

Page 124: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Meaning of the example code:

i=1

Print i

i++

i<=10

t

f

For i=1 to 10,i++

Print i

Page 125: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

ex: what is the output of the following code?

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

{ System.out.println(“this is”+i+”pass”);

System.out.println(“i is “+i);

}

Output: this is 1 pass

i is 1

this is 2 pass

i is 2

…..

this is 10 pass

i is 10

Page 126: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

ex: what is the output of the following code?

for (i=100; i>=1; i--)

{ System.out.println(i);

}

Output:

100

99

98

….

2

1

Page 127: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

ex: what’s the output of the code?

for (i=2; i<=10; i=i+2)

{ System.out.println(i);

}

Output:

2

4

6

8

10

Page 128: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: write a for-loop to printout

2,5,8,11,14,17,20 each at a line.

for (i=2; i<=20; i=i+3)

{ System.out.println(i); }

Page 129: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Nested loops: loops (while-loops and/or for-loops) can be embedded inside another loop to make (complicated) nested loops.

Ex: what’s the output of the code?

for (i=1; i<=5; i++)

{ for (j=1; j<=4; j++)

{ System.out.print(“*”); }

System.out.println();

}

Body ofOut loop

Body ofin loop

Page 130: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

****

****

****

****

****

i controls # of

rows, j controls

# of columns

j=1 j=2 j=3 j=4

i=1 * ** *** ****

i=2 *****

******

*******

********

i=3 *********

**********

***********

goes on in the same way

i=4

i=5

Page 131: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: write a program fragment to printout

***************

for (i=1; i<=5; i++)

{ for (j=1; j<=?; j++)

{ System.out.print(“*”); }

System.out.prrintln();

}

analysis (to decide ?)

1st row i=1 ?=1

2nd row i=2 ?=2

3rd row i=3 ?=3

4th row i=4 ?=4

5th row i=5 ?=5

Page 132: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

cont’d

from the analysis we see: ?=i, so the code is:

for (i=1; i<=5; i++)

{ for (j=1; j<=i; j++)

{ System.out.print(“*”); }

System.out.prrintln();

}

Page 133: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

ex: write a program fragment to printout

*****

****

***

**

*

for (i=1; i<=5; i++)

{ for (j=1; j<=?; j++)

{ System.out.print(“*”); }

System.out.prrintln();

}

analysis (to decide ?)

1st row i=1 ?=5

2nd row i=2 ?=4

3rd row i=3 ?=3

4th row i=4 ?=2

5th row i=5 ?=1

Page 134: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

from the analysis we see:

?=6-i, so the code is as follows (structure chart on the right)

for (i=1; i<=5; i++)

{

for (j=1; j<=6-i; j++)

{ System.out.print(“*”); }

System.out.prrintln();

}

Println()

Print”*”

For j=1;j<=6-i;j++

For i=1,i<=5,i++

Page 135: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

ex: write a program fragment to printout

*

**

***

****

*****

for (i=1; i<=5; i++)

{ // print leading blanks

for (k=1; k<=?;k++)

{System.out.print(“ “);}

// print *’s

for (j=1; j<=??; j++)

{ System.out.print(“*”); }

System.out.prrintln();

}

Page 136: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’dRow i ?

(blanks)

?? (*’s)

1st 1 4 1

2nd 2 3 2

3rd 3 2 3

4th 4 1 4

5th 5 0 5

Page 137: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d It is easy to see: ?=5-i and ??

=i, so the code is:

for (i=1; i<=5; i++){ // print leading blanks for (k=1; k<=5-i; k++) {System.out.print(“ “);}

// print *’s for (j=1; j<=i; j++) { System.out.print(“*”); }

System.out.prrintln(); }

Row i ? (blanks)

?? (*’s)

1st 1 4 1

2nd 2 3 2

3rd 3 2 3

4th 4 1 4

5th 5 0 5

Page 138: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Structure chart of previous code

Println()

Print “ “ Print “*”

For i=1;i<=5;i++

For k=1;k<=5-i;k++ For j=1;j<=i;j++

Page 139: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: what about this diagram?

*************************

for (i=1; i<=4; i++){ for (j=1;j<=i; j++) { System.out.print(“*”);} System.out.println(); }

for (i=1; i<=5; i++) { System.out.print(“*”);} System.out.println();

for (i=4; i>=1; i--){ for (j=1; j<=i; j++) { System.out.print(“*”);} System.out.println();}

Page 140: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Part VI

Modular Programming

Page 141: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

1. Methods

Basic idea of modular programming: break down large and complicated programs into smaller and easy-to-handle programs (called modules).

Page 142: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

1. Methods

In Java, modules are represented as methods: there are two types of methods in Java: –value-producing methods: called

functions–valueless methods: called

procedures

Page 143: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

1. Methods

Syntax of methods:

public static type method-name (parameter list)

{ body of method }

Page 144: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

ex: a function that computes the square of an integer.

public static int sq (int x) { return x*x; }

sq takes an integer x and returns the square of x.

return valtype name

para name

paratype

what isreturned

Page 145: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

to use (to call) this function:

a = sq(1); or

b = sq(3);

the definition and usage of functions in Java are similar to that in math.

Page 146: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

2. Program Structure

public class class-name { public static … method1(…) { … } public static …. method2(…) { …. } ………………. pubic static void main(String args[]) { ….. } }

call

call

Page 147: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

3. Pre-defined Math functions

usage: Math.fun-name(…) ex:

– Math.sqrt(9.0); square root of 9.0– Math.max(2,3); the max of 2 and 3– Math.PI; the pi

(3.1415926535897932384626433…)

Page 148: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

4. Examples

Computes the square of a real number.

import javax.swing.*; public class CompSq { // method sq public static double sq(double x) { return x*x; } // main method public static void main(String args[]) { double a,b; // use JOptionPane, read a real into a b = sq(a); System.out.println(“the sq root of “+a+”is “+b); System.exit(0); } }

Page 149: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

compute the area of a circle. import javax.swing.*; public class Area { // module A: get input public static double getR() { double r; String sr; sr = JOptionPane.showInputDialog(“enter a radius”); r = Double.parseDouble(sr); return r; }

// module B: compute area public static double doComp(double x) { return Math.PI*x*x; }

Page 150: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

// module C: display resultpublic static void display(double y){ System.out.println(“the area is “+y); }

// main methodpublic static void main(String args[]) { double radius, area; radius = getR(); area = doComp(radius); display(area); System.exit(0); }} // end of clas

Page 151: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

5. Local variables, variable lifetime

Local variables: variables defined inside methods and method (formal) parameters.

Variable lifetime: the time period in which variables exist in memory with respect to program execution. Some variables exist for a short period of time, others may exist for the entire execution of the program.

(Local) variable management: Each time a method is called, a memory area is created for local variables. When the call is returned, this memory area will be erased and freed up.

Page 152: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

method f(…)

{…..}

.. main(…)

{….. f (..) }

… class

call

create

Memory area

erase Memory area

Memory area for local variables in f

Page 153: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

6. Global variables

Variables defined in classes and out of all methods, with static modifier are called global variables. Also called class variables. They are visible to all methods.

Note: global variable is dangerous, and is not recommended generally.

……… class T{ static int x;

…. m1 {… } ….. main() {…. }}

visible

x is global

visible

Page 154: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

7. Example

public class Ex{ static int id =1; // class var, global public static double average(double x,

double y) { double avg; // local var avg = (x+y)/2; System.out.println(“id is “+id); return avg; } public static void main(String args[]) { double a, b, avg; // local var a=1; b=2; avg = average(a,b); System.out.println(“id is “+id); System.out.println(“average is “+avg); System.exit(0); }}

1

2

1

2

1.5

a

b

avg

x

y

avg

1.5M area erased upon return

Page 155: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

8. Case Study

Problem: Given a positive integer n, compute 1+2+…+n Requirements: Users input a positive integer n, the program computes

the sum from 1 to n. E.g., if n=1, ouput = 1 if n=2, output = 1+2=3 if n=10, output = 1+2+…+10=55 Specification:

– Input: positive integer n– Output: 1+2+…+n– Relevant formula/methodology: modules, loops– Method getN:

• purpose: It takes nothing and returns the positive integer entered by the user• type: () int• data structure

Name Type usage

n Int Input, positive integer

Sn String String for n

Page 156: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– Method doComp:• purpose: computes 1+…+n and returns the result.• type: int int• data structure

Name Type Usage

n int formal parameter

i int loop controller

sum int hold 1+…+n

Page 157: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– Method display:• purpose: display the

result• type: int ()• data structure

Name Type Usage

r int formal parameter

Page 158: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– Method main• Purpose: default• Type: default• Data structure:

name type usage

num int hold input integer

result int hold 1+…+n. Output

Page 159: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Design:

Main(String args[])

result=doComp(num)

Num=getN()

display(result)

end

Page 160: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

getN()

sn=JOpt… convert sn to n return n

display(int r)

print r

doComp(int n)

sum=0

sum=sum+i

return sumfor i=1 to n

Page 161: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Implementation: left as a lab.

Page 162: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Part VII

Arrays

Page 163: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

1. 1-D Arrays

Concept: – 1-d array is a single list (with order

embedded) of collection of data of the same type.

– It corresponds to the notion of finite tuples in math. (x1,x2, …., xn)

Page 164: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

1. 1-D Arrays

– ex:

an int array of size =5

an boolean array of size =3

1 2 3 4 5

true false true

Page 165: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Syntax: type var-name[] = new type [n];

Meaning: – Indicates that var-name is an array variable

(not a conventional variable)– Each element in the array is of type type.– Allocates n cells in memory for this array

which are indexed from 0 to n-1. (not from 1 to n).

Page 166: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

An alternative way to define arrays:

type[] var-name = new type [n];

Page 167: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex: (typing this) int a[] = new int[10];Creates the following in memory

The 1st element is referenced by a[0]The last element is referenced by a[9]All elements (a[0],…,a[9]) are of type int

a

a[0] a[1] a[2] a[8] a[9]

Page 168: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Setting and getting values in an array– Each array element can be treated as an

individual variable.– Ex: int b[] = new int[5];

b[0] =1; b[1]=2;

b[2]=5; b[4]=5; b[3]=6;

results in

1 2 5 6 5b

b[0] b[1] b[2] b[3] b[4]

Page 169: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

and

System.out.println(b[3]);

prints 5.

c=b[0]+b[4];

puts 6 into variable c

b[0]=b[1]*b[2];

puts 10 into b[0]

Page 170: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d– Ex: combine loops with arrays.

int a[] = new int[10];

for (i=0; i<10; i++)

{ a[i]=0; }results in

for (j=0; j<10; j++)

{ a[j] = j; } results in

0 0 0 0 0 0 0 0 0 0a

[0] [1] ……… [8] [9]

0 1 2 3 4 5 6 7 8 9

[0] [1] ……… [8] [9]

a

Page 171: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

to printout the contents of array a,

for (k=0; k<10; k++)

{ System.out.println(a[k]); }

Page 172: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’dQ: how to reverse a[]? i.e., make a[] like

will for (i=0; i<10; i++) a[9-i] = a[i];work? if not, what does it do?

will for (i=0; i<10; i++) { t = a[9-i]; a[9-i] =a[i]; a[i]=t; }work? if not, what does it do?

9 8 7 6 5 4 3 2 1 0a

[0] [1] ……… [8] [9]

Page 173: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

solution:

// reverse a[] into b[] for (i=0; i<10; i++) { b[9-i] = a[i] ; } // copy b[] back to a[] for (i=0; i<10; i++) { a[i] = b[i]; }

b[] is an auxiliary array.

Page 174: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Pass arrays as parameters

// def array a

int[] a = new int a[10];

…..

// call method m

// passing array a to it

…m(a);

}

public static void m(int x[])

{ ……….

// body of method m

//Note:

// operations performed

// on array x will affect

// array a in the caller

// no array “return” needed.

}

Page 175: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Examples of arrays– Compute the average of a class.

• Input: # of students and grade of each student.• Output: average of the class• Analysis: (data structure) n: type int, holds the # of students g[]: type double array, holds the grade of each student avg: type double, holds the average of class sum: type double, holds the summation of all grades• relevant formula: sum = ∑g[i], avg = sum/n

Page 176: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

• Design:

START

P & Rn

read allgrades

cal sum of grade cal averagedisplay

avg

read each grade

into g[i]

sum=sum+g[i]

avg = sum/n

End

for i=1 ton

for i=1 to n

Page 177: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Implementation:

• import javax.swing.*;

• public class Array• {

• public static void main(String args[])• { int n, i;• String sn;• double avg,sum, g[] = new double[100];

• // read # of students• sn=JOptionPane.showInputDialog("How many students?");• n=Integer.parseInt(sn);

Page 178: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– // read grade of each student– for (i=1;i<=n;i++)– g[i]=Double.parseDouble(JOptionPane.showInputDialog("grade?"));

– // totoal grades– sum=0;– for (i=1;i<=n;i++)– sum = sum + g[i];

– // compute avgerage– avg = sum/n;– – // output– System.out.println("average is "+avg);– – // terminate– System.exit(0);– }– }

Page 179: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– ex: sorting of numbers• given a set of numbers, sort them into ascending

order (i.e., from small to large). e.g.:

2 4 3 1 5 will be sorted to

1 2 3 4 5• analysis: the strategy of bubble sort. We use an

example to illustrate the idea of bubble sort. Suppose we want to sort the set of integers:

2 4 3 1 5

Page 180: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

2 4 3 1 5

2 4 3 1 5

1 4 3 2 5

2 4 3 1 5

1 2 3 4 5

1 4 3 2 5

1 4 3 2 5

1 3 4 2 5

1 2 4 3 5

1 2 4 3 5

1 2 4 3 5

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

Page 181: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Java code:public class BSort{ public static void main(String args[]) { int n, j, i, temp; int a[] = new int[100]; String sn;

sn = JOptionPane.showInputDialog(“how many numbers?”); n = Integer.parseInt(sn);

for (i=0; i<n; i++) // read data into array a, you can do it by yourself

Page 182: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

for (i=0; i<=(n-2); i++) { for (j=i+1; j<=(n-1); j++) { if (a[i]>a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } // output array a[] for (i=0; i<n; i++) System.out.println(a[i]); System.exit(0); } }

Page 183: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

2. 2-D Arrays

Concept: – a table of collection of data of the same type– ex:

size: 2 x 4 (# of rows x # of columns); type of element: int Syntax:

– type var-name[][] = new type[n][m];– ex: int t[][] = new int[10][20];

Meaning: – indicates that var-name is a 2-d array– each element in the array is of type type– size of array is n rows and m columns, total n x m cells– index of cells starts form 0 (not 1!)

4 5 21 4

88 7 6 5

Page 184: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

ex: int a[][] = new int[3][4];

size : 3 x 4; 3 rows, 4 columnsEach element in the array is identified by its row # and

col #, e.g., the element at 2nd row and 3rd column is referenced by a[1][2].

a[0][0] a[0[1] a[0][2] a[0][3]

a[1][0] a[1][1] a[1][2] a[1][3]

a[2][0] a[2][1] a[2][2] a[2][3]

Page 185: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Setting and getting values in a 2-d array– each array element can be treated just like an individual

variable– ex: a[1][2]=5; b = a[1][2]+a[1][3]; System.out.println(a[0][0]);– loops and arrays// a[][] can be filled up in the following way for (i=0; i<3; i++) { for (j=0; j<4; j++) { a[i][j] = 0; } // assign 0 to each cell }

0 0 0 0

0 0 0 0

0 0 0 0

result

Page 186: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– ex:

// fill row-by-row

for (i=0; i<3; i++)

{ for (j=0; j<4; j++)

a[i][j]=i*j;

}

// fill col-by-col

for (j=0; j<4; j++)

{ for (i=0; i<3; i++)

a[i][j]=i*j;

}

0 0 0 0

0 1 2 3

0 2 4 6

0 0 0 0

0 1 2 3

0 2 4 6

Page 187: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– printout:// printout row-by-rowfor (i=0; i<3; i++) { for (j=0; j<4; j++) {System.out.print(a[i][j]);} System.out.println(); } // printout col-by-colfor (j=0; j<4; j++){ for (i=0; i<3; i++) {System.out.print(a[i][j]);} System.out.println();}

0 0 0 0 1st row 0 1 2 3 2nd row 0 2 4 6 3rd row

0 0 0 1st col 0 1 2 2nd col 0 2 4 3rd col 0 3 6 4th col

Page 188: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Call-by-value (and call-by-reference)– call-by-value: one of the parameter passing

modes. When a method is called, a (separate) copy of the argument is passed to the parameter and any changes made to this copy is local. All single-valued variables and individual array element of base types are passed by call-by-value.

Page 189: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– ex:…..main(String …)

{ int a;

a=3;

System.out.println(a);

AddTwo(a);

System.out.println(a);

}

public static void AddTwo(int x)

{

x = x+2;

}

- x is local, changes made to x will not affect variable a in main

3

a

x

3

5

Page 190: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– Call-by-reference: one of the parameter passing modes. When a method is called, a reference of the argument is passed to the parameter. Any changes made to the parameter will affect the original argument. Arrays are passed by call-by-reference. (different perspective: call-by-value since b is a ref variable and its value is a reference already.)

– ex: ….main(String…) { int b[] = new int[10]; // fill up array b b[1]=1; AddTwo(b); Sytem.out.println(b[1]); }

public static void AddTwo(int x[]){ x[1] = x[1]+2; }

b and x contains the same reference to the array

x 1 3 x x x

b

x

Page 191: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

Ex of 2-d arrays: suppose

compute the average of each person.

Basic idea: use a 2-d array to store the grades of the 3 students. Write a method which handles the computation of average.

cmps math eng avg

John 80 90 85

Mary 70 75 76

Al 100 95 98

Page 192: CMPS 135 Introduction to Programming Instructor: Dr. Cong-Cong Xing

Cont’d

– Java code:public class Ex{ public static void main(String

args[]) { int i; double grade[][] =

{{80,90,85,0},{70,75,76,0},{100,95,98,0}};

compAvg(grade); for (i=0; i<3;i++) System.out.print(grade[i][3]); System.exit(0); } // end of main

public static void compAvg(double g[][])

{ double sum=0; i, j; for (i=0; i<3; i++) { for (j=0; j<3; j++) { sum=sum+g[i][j];} g[i][3] = sum/3.0; sum=0; } } // end of compAvg

}// end of class