cmps 135 introduction to...

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

Upload: domien

Post on 17-Mar-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

CMPS 135 Introduction to

Programming

Instructor:

Dr. Cong-Cong Xing

Page 2: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Part I

Overview of

Computers and

Programming

Page 3: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

1. Computer Hardware System

Basic architecture

CPU Input devices Output devices

Storage devices

Page 5: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Input devices

– Enter data into computers

– Ex: keyboard, scanner

Output devices

– Observe computation results

– Ex: monitor, printer

Page 6: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

CPU (Central Processing Unit)

– Control unit: coordinate all computation tasks

– ALU (arithmetic-logic unit): carry out computations

Page 7: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Storage devices

– Major storage device: memory (also called primary

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

temporarily

Page 8: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

2nd storage devices store info permanently.

Ex: hard disks, floppy disk, optical disks

(CDs, DVDs), U-drive

Page 9: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Motherboard (main board): host memory,

CPU, etc.

Page 10: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

2. Problem Solving and

Programming

Problem

Implementation

Specifications Testing

Design

Requirements

Page 11: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

High-level languages

– English-like constructs

– Ex: x = a+b (meaning?)

– Examples of high-level languages

• Pascal, C, C++, Python, Java, Python, Haskell

– How can computer understand high-level

languages?

Page 15: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

4. Processing a High-level

Language

editor Source

file

Compile

Source file Object

file

Linker/

loader

executable

in RAM

Fix err err

More

Obj files

Page 16: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Part II

Welcome to Java

Page 17: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

// 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 main

Necessary for every Java program

Every “word” is fixed

Prog 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 Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

3. Compilation and Execution

(GUI Dr. Java)

Page 21: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

(Why command line then?)

Page 23: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 prog

Successfully.

Required for GUI.

Print “welcom to

Java” in a

Pop-up window

(See next slide)

Page 25: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

Page 26: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Part III

Basic Elements

Page 27: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

A, a, Max, MAX, daysOfWeek (legal)

%right, 30days, #missing (illegal)

Page 29: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

2. Data Types and Values

Name of type Meaning 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)

Character

strings

“abc”, “123d”

“a”, “ ”, “”

boolean Logical true, false

Page 30: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

more examples of variable

declarations: (taken from

lab 2)

Page 33: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 34: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 35: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 36: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

3/2 hours = how many seconds ?

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

60*60*(3/2) or (3/2)*60*60

60*60*(3.0/2) or 60*60*(3.0/2.0)

Page 37: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 38: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 39: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

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

(a + b + c) / 3

+

/

1

2

3

result

+

Page 40: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 41: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 42: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

more examples of assignment statements:

Page 43: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 44: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 45: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Input

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 46: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 47: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Input (alternative)

use Scanner class

Page 48: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Input (alternative)

this is the result

Page 49: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix
Page 50: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix
Page 51: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

quick reference for Console input/output, p776

Page 52: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Output

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 53: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 54: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 55: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 56: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 57: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d Design (structure chart)

(How to read the chart? from left to right, from top to

bottom)

Be careful about the shape of figures in structure chart.

More figure will be introduced later on.

START

Declare r, area, rs

double r,area String rs

Prompt and read r

rs=JOptionPane… (“enter a radius”);

Conver rs to r;

Echo r

Print (“radius is”+r);

Computes area

area=pi*r*r

Display area

Print (“area is “+area);

Page 58: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 59: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

Implementation (coding): translate the structure

chart into Java code. (next page).

Note the 1 to 1 correspondence between design

and code.

Page 60: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 61: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 62: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Part IV

Selection

Structures

Page 63: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 64: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 65: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 66: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

– 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 67: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 68: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 69: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 70: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

2. Precedence of Operators

From highest to lowest:

( )

!

* / %

+ -

< <= > >=

== !=

&&

||

Page 71: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

Ex: evaluation tree

1 > 2 || 2 > 1

>

||

>

1 2

3

true

false true

Page 72: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

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

>=

||

<

&&

!= 1 2 3

4

5

false true false

false

false

Page 73: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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

false true

note: this is not a

structure chart

Page 74: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 “good

work”

Page 75: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

4. if-else Statement

Syntax:

if (condition)

{ stmnt1;

…..

stmntn;

}

else

{ stmnt1’;

…..

stmntn’;

}

Meaning: (in flow chart)

cond

stmnt1

stmntn stmntn’

stmnt1’

true false

note: this is not a

structure chart

Page 76: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 77: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Its structure chart

grade>=60

print “you

passed”

print

“congratulations”

print “work

harder”

print “you

failed”

T F

Page 78: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

There is a way to write

programs…

Write comments

Indent programs

“Well paired” { and }

Add blank lines/divide program into blocks

Page 79: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix
Page 80: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix
Page 81: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 82: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 83: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 84: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 85: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 86: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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? print

zero

print

pos

print

neg

T F

T F

Page 87: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

if (x==0)

{ System.out.println(“zero”);

}

else

{

if (x>0)

{ System.out.println(“positive”); }

else

{ System.out.println(“negative”); }

}

Page 88: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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?

prn

zero

prn

pos prn

neg

T T T

Page 89: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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, compares them,

and outputs the largest integer. E.g., given

3,4,10, then 10 should be selected.

Page 90: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 91: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 92: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

– Design

start

P & R

a, b, c

Find the

max output end

Read sa Read sb Read sc

largest =a largest=b nothing largest=c

display

largest

Convert

sa to a

Echo of

a

Convert

sb to b

Echo of

b

Convert

sc to c

Echo of

c

a>=b largest

>=c

T F T F

Page 93: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 94: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

An alternative solution

– Design (partial)

a>=b

a>=c b>=c

display c display b display c display a

f t

f t f t

Page 95: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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;

break;

*type of expression

should be “countable”.

Type of label must be of

the same type as that of

expression.

Page 96: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

Meaning (flow chart)

exp=l1

exp=l2

exp=ln

default

break stmntn

break stmnt2

break stmnt1

t

f

t

f

t

f

Page 97: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

Structure chart

Switch()

stmnt1 stmnt2 stmnt3 stmntn

exp=l1 exp=l2 exp=l3 exp=ln

Page 98: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 99: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 100: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 101: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

Name Type Usage

score int hold input (number grade)

sscore String String for score

grd int Scaled-down of score

Page 102: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 103: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

(structure chart)

START

P&R

sscore

Decide letter

grade end

Convet

sscore

to score

Echo

score

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,0

switch(grd)

7

Page 104: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 105: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 106: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Part V

Loops

Page 107: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

1. while loop

Syntax: while (cond)

{ stmnt1;

…..

stmntn;

}

note: cond must be a boolean expression

loop

body

Page 108: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 109: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

Meaning (in structure chart)

stmnt1 stmnt2 stmntn

cond

Page 110: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

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

counter = 1;

while (counter <= 5)

{ System.out.print(counter);

counter = counter + 1;

}

Page 111: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 112: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

Ex:

counter = 1;

while (counter < 5)

{ System.out.print(counter);

counter = counter + 1;

}

How many times will the body be executed?

Page 113: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

Ex:

counter = 1;

while (counter > 0)

{ System.out.print(counter);

counter = counter + 1;

}

How many times will the body be executed?

Page 114: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

Ex:

counter = 1;

while (counter < 0)

{ System.out.print(counter);

counter = counter + 1;

}

How many times will the body be executed?

Page 115: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 116: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 117: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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, others-no”);

answer = Integer.parseInt(answerstr);

}

System.out.println(“bye”);

…………

Page 118: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 119: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 120: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 121: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 122: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 123: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 124: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 125: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 126: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 127: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

– Design: (note how the

– loop is represented)

START

P & R first grade

grdstr

Convert grdstr to grd

echo

sum=0 n=0

accumulate total grade

add current grd to total

sum= sum+grd

increase # of students

n=n+1

P &R grdstr

convert grdstr to grd

echo

compute avgerage

avg= sum/n

display avg

end

while

grd !=9999

Page 128: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 129: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

// 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 130: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

// 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 131: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

// compute average

avg = sum/n;

// dispaly result

System.out.println("The average

is:"+avg);

// termination

System.exit(0);

}

}

// end of program

Page 132: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

2. For-Loop

Syntax:

for (<init>;<cond>;<incre>)

{

body

}

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

{

System.out.println(i);

}

Page 133: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 134: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 135: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 136: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 137: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 138: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 139: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 of

Out loop

Body of

in loop

Page 140: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 141: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 142: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 143: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 144: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 145: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 146: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d 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 147: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 ?

(blan

ks)

??

(*’s)

1st 1 4 1

2nd 2 3 2

3rd 3 2 3

4th 4 1 4

5th 5 0 5

Page 148: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

Structure chart of previous code

Println()

Print “ “ Print “*”

For i=1 to 5;i++

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

Page 149: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 150: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Part VI

Modular

Programming

Page 151: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

1. Methods

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

Page 152: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 153: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

1. Methods

Syntax of methods:

public static type method-name (parameter list)

{

body of method

}

Page 154: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 val

type name

para

name

para

type

what is

returned

Page 155: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 156: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

2. Program Structure

public class class-name

{

public static … method1(…)

{ …

}

public static …. method2(…)

{ ….

}

……………….

pubic static void main(String args[])

{ …..

}

}

call

call

Page 157: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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…)

– (There are more built-in functions, but do not

use them unless you are clearly allowed.)

Page 158: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 square of “+a+”is “+b);

System.exit(0);

}

}

Page 159: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Types: Java is strongly typed

Types of methods

– Given a method

public static T1 f (T2 x)

f’s type is: T2 T1 (domain codomain)

(input type output type)

– Ex: Given:

public static double sf(int x)

type of sf is: int double

Page 160: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

-ex: Given

– public static void display(int x)

its type: int ()

(it takes an integer and returns nothing)

– public static double getX()

its type: () double

(it takes nothing and return a double)

Page 161: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

compute the area of a circle.

import javax.swing.*;

public class Area

{

// module A: get input

public static double getR() // type: () double

{ 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) // type: double double

{ return Math.PI*x*x; }

Page 162: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

// module C: display result

public static void display(double y) // type: double ()

{ System.out.println(“the area is “+y); }

// main method

public static void main(String args[]) // type?

{ double radius, area;

radius = getR();

area = doComp(radius);

display(area);

System.exit(0);

}

} // end of class

Page 163: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 164: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

method f(…)

{…..}

.. main(…)

{….. f (..) }

… class

call

create

Memory

area

erase

Memory area

Memory area

for local

variables in f

Page 165: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

6. Global variables

Variables defined in classes and out of all methods, with static modifier are called global variables. They are 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 166: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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(“I am doing avg for”+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.print(“ok, ”+id+ “your”);

System.out.println(“average is “+avg);

System.exit(0);

}

}

1

2

1

2

1.5

a

b

avg

x

y

avg

1.5

Memory

area

erased

upon return

Page 167: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 168: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 169: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

– Method display:

• purpose: display the

result

• type: int ()

• data structure

Name Type Usage

r int formal parameter

Page 170: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 171: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

Design: (structure chart for method main)

main(String args[])

result=

doComp(num)

num=

getN()

display

(result)

end

Page 172: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

Structure chart for method getN

getN()

sn=JOpt… convert sn to n return n

Page 173: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

Structure chart for method doComp

doComp(int n)

sum=0

sum=sum+i

return sum for i=1 to n

Page 174: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

Structure chart for method display

display(int r)

print r

Page 175: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

Implementation: left as a lab.

Page 176: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Part VII

Arrays

Page 177: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 178: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 179: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 180: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

An alternative way to define arrays:

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

Page 181: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 182: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 5 b

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

Page 183: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

and

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

prints 6.

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

puts 6 into variable c

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

puts 10 into b[0]

Page 184: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 0 a

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

0 1 2 3 4 5 6 7 8 9

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

a

Page 185: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

to printout the contents of array a,

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

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

Page 186: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

When size of an array is small, we may

declare and initialize an array in the

following way (in a “set notation”)

Ex: int[] b = {1,2,3,4,5};

results in

1 2 3 4 5

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

Page 187: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

Q: how to reverse a[]? E.g: given array a[]

after being reversed, a[] will have

9 8 7 6 5 4 3 2 1 0 a

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

0 1 2 3 4 5 6 7 8 9 a

Page 188: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

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

a[9-i] = a[i];

work? if not, what does it do?

Page 189: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

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?

Page 190: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

solution: b[] is an auxiliary array.

// reverse a[] into b[]

0 1 2 3 4 5 6 7 8 9 a

9 8 7 6 5 4 3 2 1 0 b

Page 191: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

// copy b[] back to a[]

9 8 7 6 5 4 3 2 1 0 b

9 8 7 6 5 4 3 2 1 0 a

Page 192: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 193: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 194: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

• Design:

START

P & R

n

read all

grades cal sum of grade cal average

display

avg

read

each grade

into g[i]

sum=

sum+g[i]

avg = sum/n

End

for i=1 to

n for i=1 to

n

Page 195: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 196: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 197: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 198: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 199: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Suppose 2, 4, 3, 1, 5 are stored in array a[] in that order.

Then compare a[0] with a[1]. If a[0]<a[1], do nothing;

otherwise, swap a[0] w/ a[1].

compare a[0] with a[2]. If a[0]<a[2], do nothing;

otherwise, swap a[0] w/ a[2].

compare a[0] with a[3]. If a[0]<a[3], do nothing;

otherwise, swap a[0] w/ a[3].

compare a[0] with a[4]. If a[0]<a[4], do nothing;

otherwise, swap a[0] w/ a[4].

After these operations, a[0] will hold the smallest element

overall.

Page 200: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Then, leave a[0] alone, starting with a[1], repeat the

above process, that is,

compare a[1] with a[2]. If a[1]<a[2], do nothing;

otherwise, swap a[1] w/ a[2].

compare a[1] with a[3]. If a[1]<a[3], do nothing;

otherwise, swap a[1] w/ a[3].

compare a[1] with a[4]. If a[1]<a[4], do nothing;

otherwise, swap a[1] w/ a[4].

After these operations, a[1] will hold the second smallest

element overall.

Page 201: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Then, leave a[0] and a[1] alone, starting with a[2], repeat

the above process, that is,

compare a[2] with a[3]. If a[2]<a[3], do nothing;

otherwise, swap a[2] w/ a[3].

compare a[2] with a[4]. If a[2]<a[4], do nothing;

otherwise, swap a[2] w/ a[4].

After these operations, a[2] will hold the third smallest

element overall.

Page 202: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Then, leave a[0] , a[1] and a[2] alone, starting with a[3],

repeat the above process, that is,

compare a[3] with a[4]. If a[3]<a[4], do nothing;

otherwise, swap a[3] w/ a[4].

After these operations, a[3] will hold the the 4th smallest

element overall.

The last element a[4] must be the 5th smallest one, i.e. the

largest element overall, and there is no need to worry about

it.

Now, the array is sorted.

Page 203: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

Java implementation: left as a lab

Page 204: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 205: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

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

size : 3 x 4; 3 rows, 4 columns

Each element in the array is identified and accessed 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 206: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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[][] (3x4 array) can be initialized 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 207: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

– ex: fill up an array

// 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 208: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Cont’d

– printout:

// printout row-by-row

// left as a lab

// printout col-by-col

// left as a lab

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 209: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

2-d array is 1-d array of 1-d

arrays

0 0 0 0

0 1 2 3

0 2 4 6

a[0]

a[1]

a[2]

(a[0])[0] (a[0])[1]

Page 210: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix
Page 211: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 212: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 213: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 214: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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 215: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

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

Page 216: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

matrix multiplication

Page 217: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

example

Page 218: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix
Page 219: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

ASA (a special algorithm)

Ex 1

“new” last = middle -1

“new” first = middle +1

ex 1

Page 220: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

ASA (a special algorithm)

3 4 8 11 22 34 56 89 90 101

------------------------------------------------------------------------ look for 8

0 1 2 3 4 5 6 7 8 9

f * l

3 4 8 11 22 34 56 89 90 101

------------------------------------------------------------------------

0 1 2 3 4 5 6 7 8 9

f * l

3 4 8 11 22 34 56 89 90 101

------------------------------------------------------------------------

0 1 2 3 4 5 6 7 8 9

f * l

found, index 2 returned

ex 2

Page 221: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Set/collection,

subset/subcollection

Given a set, say, {a}, its subsets are

∅ (𝑛𝑢𝑙𝑙 𝑠𝑒𝑡), 𝑎

Given a set, say, {1, 2}, its subsets are

∅, 1 , 2 , 1,2

Page 222: CMPS 135 Introduction to Programmingmath.nicholls.edu/Xing/xing/public_html/cmps135-pool/cmps135-note/... · Design Requirements Problem: ... Linker/ loader executable in RAM Fix

Set, subset

Given a set, say, {a,b,c}, its subsets are

∅, 𝑎 , 𝑏 , 𝑐 , 𝑎, 𝑏 , 𝑎, 𝑐 , 𝑏, 𝑐 , 𝑎, 𝑏, 𝑐

You should get the idea of subsets now