cmps 135 introduction to...
TRANSCRIPT
CMPS 135 Introduction to
Programming
Instructor:
Dr. Cong-Cong Xing
Part I
Overview of
Computers and
Programming
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
1. Computer Hardware System
Basic architecture
CPU Input devices Output devices
Storage devices
Input devices
– Enter data into computers
– Ex: keyboard, scanner
Output devices
– Observe computation results
– Ex: monitor, printer
CPU (Central Processing Unit)
– Control unit: coordinate all computation tasks
– ALU (arithmetic-logic unit): carry out computations
Storage devices
– Major storage device: memory (also called primary
memory, RAM, 1st storage device) which stores info
temporarily
2nd storage devices store info permanently.
Ex: hard disks, floppy disk, optical disks
(CDs, DVDs), U-drive
Motherboard (main board): host memory,
CPU, etc.
2. Problem Solving and
Programming
Problem
Implementation
Specifications Testing
Design
Requirements
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
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
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
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?
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
Part II
Welcome to Java
1. The First Program
// my first Java program
public class Greeting
{ public static void main (String args[])
{ System.out.println(“Welcome to Java”);
}
}
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)
// 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
3. Compilation and Execution
(GUI Dr. Java)
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
(Why command line then?)
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
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)
Cont’d
Part III
Basic Elements
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:
A, a, Max, MAX, daysOfWeek (legal)
%right, 30days, #missing (illegal)
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
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
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
more examples of variable
declarations: (taken from
lab 2)
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
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
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
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)
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
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
Cont’d
Ex: evaluation tree of (a+b+c)/3
(a + b + c) / 3
+
/
1
2
3
result
+
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
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!
more examples of assignment statements:
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
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”, “_”, “ ”
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);
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)
Input (alternative)
use Scanner class
Input (alternative)
this is the result
quick reference for Console input/output, p776
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.
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
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
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
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
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);
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
Cont’d
Implementation (coding): translate the structure
chart into Java code. (next page).
Note the 1 to 1 correspondence between design
and code.
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;
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
Part IV
Selection
Structures
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
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
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.
– 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
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
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
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
2. Precedence of Operators
From highest to lowest:
( )
!
* / %
+ -
< <= > >=
== !=
&&
||
Cont’d
Ex: evaluation tree
1 > 2 || 2 > 1
>
||
>
1 2
3
true
false true
Cont’d
(1 >= 2) || (3 < 4) && (5 != 5)
>=
||
<
&&
!= 1 2 3
4
5
false true false
false
false
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
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”
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
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!”);
}
Its structure chart
grade>=60
print “you
passed”
“congratulations”
print “work
harder”
print “you
failed”
T F
There is a way to write
programs…
Write comments
Indent programs
“Well paired” { and }
Add blank lines/divide program into blocks
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.
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”);
}
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”);
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”);
}
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”);
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
pos
neg
T F
T F
Cont’d
if (x==0)
{ System.out.println(“zero”);
}
else
{
if (x>0)
{ System.out.println(“positive”); }
else
{ System.out.println(“negative”); }
}
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
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.
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)
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
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
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
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
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.
Cont’d
Meaning (flow chart)
exp=l1
exp=l2
exp=ln
default
break stmntn
break stmnt2
break stmnt1
t
f
t
f
t
f
Cont’d
Structure chart
Switch()
stmnt1 stmnt2 stmnt3 stmntn
exp=l1 exp=l2 exp=l3 exp=ln
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;
}
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
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:
Cont’d
Name Type Usage
score int hold input (number grade)
sscore String String for score
grd int Scaled-down of score
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
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
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
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; – }
Part V
Loops
1. while loop
Syntax: while (cond)
{ stmnt1;
…..
stmntn;
}
note: cond must be a boolean expression
loop
body
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
Cont’d
Meaning (in structure chart)
stmnt1 stmnt2 stmntn
cond
Cont’d
Ex: what’s the output of the code fragment?
counter = 1;
while (counter <= 5)
{ System.out.print(counter);
counter = counter + 1;
}
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)
Cont’d
Ex:
counter = 1;
while (counter < 5)
{ System.out.print(counter);
counter = counter + 1;
}
How many times will the body be executed?
Cont’d
Ex:
counter = 1;
while (counter > 0)
{ System.out.print(counter);
counter = counter + 1;
}
How many times will the body be executed?
Cont’d
Ex:
counter = 1;
while (counter < 0)
{ System.out.print(counter);
counter = counter + 1;
}
How many times will the body be executed?
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
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);
}
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”);
…………
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
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
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
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)
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
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
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
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
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
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
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
// 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");
// 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);
}
// compute average
avg = sum/n;
// dispaly result
System.out.println("The average
is:"+avg);
// termination
System.exit(0);
}
}
// end of program
2. For-Loop
Syntax:
for (<init>;<cond>;<incre>)
{
body
}
Ex: for (i=1;i<=10;i++)
{
System.out.println(i);
}
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
Cont’d
Meaning of the
example code:
i=1
Print i
i++
i<=10
t
f
For i=1 to 10,i++
Print i
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
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
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
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); }
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
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
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
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();
}
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
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++
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();
}
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
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
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++
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();
}
Part VI
Modular
Programming
1. Methods
Basic idea of modular programming: break down large and complicated programs into smaller and easy-to-handle programs (called modules).
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
1. Methods
Syntax of methods:
public static type method-name (parameter list)
{
body of method
}
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
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.
2. Program Structure
public class class-name
{
public static … method1(…)
{ …
}
public static …. method2(…)
{ ….
}
……………….
pubic static void main(String args[])
{ …..
}
}
call
call
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.)
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);
}
}
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
-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)
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; }
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
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.
Cont’d
method f(…)
{…..}
.. main(…)
{….. f (..) }
… class
call
create
Memory
area
erase
Memory area
Memory area
for local
variables in f
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
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
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
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
Cont’d
– Method display:
• purpose: display the
result
• type: int ()
• data structure
Name Type Usage
r int formal parameter
Cont’d
– Method main
• Purpose: default
• Type: default
• Data structure:
name type usage
num int hold input integer
result int hold 1+…+n. Output
Cont’d
Design: (structure chart for method main)
main(String args[])
result=
doComp(num)
num=
getN()
display
(result)
end
Cont’d
Structure chart for method getN
getN()
sn=JOpt… convert sn to n return n
Cont’d
Structure chart for method doComp
doComp(int n)
sum=0
sum=sum+i
return sum for i=1 to n
Cont’d
Structure chart for method display
display(int r)
print r
Cont’d
Implementation: left as a lab.
Part VII
Arrays
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)
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
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).
An alternative way to define arrays:
type[] var-name = new type [n];
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]
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]
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]
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
to printout the contents of array a,
for (k=0; k<10; k++)
{ System.out.println(a[k]); }
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]
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
Cont’d
will for (i=0; i<10; i++)
a[9-i] = a[i];
work? if not, what does it do?
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?
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
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
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.
}
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
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
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);
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);
– }
– }
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
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
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.
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.
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.
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.
Cont’d
Java implementation: left as a lab
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
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]
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
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
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
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]
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.
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
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
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
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
matrix multiplication
example
ASA (a special algorithm)
Ex 1
“new” last = middle -1
“new” first = middle +1
ex 1
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
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
Set, subset
Given a set, say, {a,b,c}, its subsets are
∅, 𝑎 , 𝑏 , 𝑐 , 𝑎, 𝑏 , 𝑎, 𝑐 , 𝑏, 𝑐 , 𝑎, 𝑏, 𝑐
You should get the idea of subsets now