Download Midterm Review - Boston College Computer Science Department

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CS-I MidTerm Review
Hao Jiang
Computer Science Department
Boston College
About Programs

Data and method (procedures, routines, functions) are two
fundamental elements of programming

Two basic tasks in constructing a program



Define data types and data elements
Define procedures that process data
Two schemes of building a program


Procedure oriented (what we have been learning)
Object oriented (to be covered soon)
Data Types

Java is a strong typed language: every data element (literal or
variable) has a “fixed” type

We have learned built-in types in Java, e.g., int, double, String
(We will learn how to define our data types later)

Before using a variable, you must make sure that its type has
been clearly “declared”

It is important to choose suitable data types in information
processing.
Built in Data Types

Numerical types are used for math computing

Numeric Types: byte, short, int, long, float, double





“int” literals: 10, -5
“long” literals: 1034678L
“double” literals: 1.234, -2.5, 1.0e10
“float” literals: 1.234f
Numerical Operators

Operators:


Binary operators: +, - , * , / , %
Unary operators: ++, -- (only for variables), +, -
Built in Data Types

Boolean types are for logic computing

Boolean Type: boolean


Operators:


liberals: true, false
&&(and), ||(or), ! (not)
Comparison

Boolean type can be generated by comparison operations:
>, <, >=, <=, ==, !=
For example, expression (a +c >= b) has a boolean type
Built in Data Types

Character and string types are for text processing

Character Type: char


literals: ‘a’, 3’, ‘+’, ‘/n’, ‘/t’, ‘#’
String Type: String


literal: “Hello World”, “1234”, “1+2”
Operator: +




“123” + “abc”=“123abc”
“123” + 4 = “1234”
“123” + ‘4’ = “1234”
Pay attention to the difference of


1 + 2 + “123”
“123” + 1 + 2
The Precedence of Operators
High
low
()
!, unary -, unary +, ++(post), --(post)
++(pre), --(pre)
*, /, %
+, <, <=, >, >=
==, !=
&&
||
=
Example: a++ > 5 || b < 6
((a++) > 5) || (b < 6)
a && b || c && d <=> (a &&b) || (c && d)
Type in Java

Every entity in Java that has a “value” has association with
specific data types.

Literals: 1.5, 2000, 1.0e20
Variables: n, m, counter, isPostive
Expressions: counter++, n+m
Functions: input and output must have clearly declared
variables with certain types.



Variables




Variables are data elements whose values can “change”
Variables are referenced by names
Each variable must be declared to be of some “type”
Assignment operation “=“
variable = expression;
int n;
double x, y;
n = 10 + 5 - 4;
int m = 20;
n = m + n;
x = 100 / n;
n = x;
How can you change
the value of a variable?
Special Assignments
promotion
illegal operation
n = (int) x;
+=
-=
*=
/=
The Scope of Variables

Variable Scope: the part of code where you can reference a
variable.
{ int y;
int x;
Scope
{ int z;
of y
Scope }
of x
Scope
}
of z
{
int x;
int y;
}
Different
x, y from
the previous
block
A block in Java is
usually enclosed by { }
for instance:
A function body,
or blocks in if, for or while
statements.
Array

Array is a data structure: a sequence of same type data
indexed by integers.

To construct a 1D array:
int[] a = new int[N]; // a is the address of the array
// a is of reference type
for (int i = 0; i < N; i++)
a[i] = I;
// array can be access by a[i]

You can also construct higher dimensional arrays:
int[][] a = new int[N][M];
for (int i = 0; i < N; i++)
for (int j = 0; j < M; J++)
a[i][j] = i + j;
Procedures

Java defines different language constructs for writing
procedures – an action or sequential of actions on data
elements.

The flow control statements




Straight-line code
“If statement” for conditional branches
“Loops” such as “while” loops or “for” loops for iterative
procedures.
Function (routine)


Function is a basic tool in Java for “information hiding”
The key of a function is the “interface”:

the input and output of the function.
The Flow of a Program
Main()
f()
Straight line code
If condition
f()
Else
g()
g()
loops
Straight Line Code
Logic group1
Logic group1
Logic group 2
Logic group 2
Logic group 3
Logic group 3
Good program structure
Bad program structure
If Statements
If (condition) {
statements
}
else {
statements
}
If (condition) {
statements
}
Nested if statement:
if (isA)
doA;
else if (isB)
doB;
else if (isC)
doC;
or
if (isA) doA;
if (isB) doB;
if (isC) doC;
Loops
while statement:
while (condition) {
statements
}
for statement:
for(initialization; condition; update) {
statements
}
• while loop is a general one. If you do not know the number of
Iterations, you should use a while loop.
• For loop is more compact when dealing with counting up or
down a control variable.
• Prefer “for” loop when possible.
• Do not use “for” loop is “while” loop is more appropriate.
While Loops
Average:
double s = 0;
int n = 0;
while ( !StdIn.isEmpty() ) {
double x = StdIn.readDoulbe();
s += x;
n ++;
}
s = s / n;
Remove
white space: while(s.charAt(0) ==‘ ‘)
s = s.substring(1);
Remove
factor 2:
While (n%2 == 0) {
n = n/2;
}
For Loops
int N = 100;
int s = 0;
Sum: for (int i = 0; i < N; i++) {
s += i;
}
Harmonic number:
Checker
board:
double p = 0;
for (int k = N ; k >= 1; k --) {
p = p + (1.0/K) ;
}
for (int i = 0; i < N; i++) {
StdOut.println();
for (int j = 0; j < N; j ++) {
if ( i % 2 == 0 && j % 2 == 0)
StdOut.print(“*”);
else if (I % 2 == 1 && j % 2 ==1)
StdOut.print(“*”);
else StdOut.print(“ “);
}
}
More about Loops

We can solve many problems using iterative methods.

But, how do I know a loop is correct?
There are quite a lot of things going on in a loop. Interestingly,
the most important feature you should pay attention to is not
something that changes but something that does not change.
Loop Invariant
int N = 100;
int s = 0;
for (int i = 0; i < N; i++) {
s += i;
}
loop invariant: After each iteration, s equals the summation from 0 to i.
int v = 1;
while (v <= N/2)
v = 2*v;
loop invariants: At the beginning of each loop, v <= N/2
After each loop v <= N
v is a power of 2 (true for both the beginning
and the end of a loop)
Checking a Loop
1. The loop will terminate somehow
2.
3.
Some loop invariant holds in each each loop.
When the loop terminates, we obtain the desired result .
public static boolean isPowerOf2(int n) {
while (n % 2 == 0) {
n = n / 2;
}
if (n == 1) {
return true;
}
else {
return false;
}
}
Input and Output

Standard Input and Standard output




Read from standard input, e.g., StdIn.readInt()
Write to standard output, e.g., StdOut.print(x)
Redirection: we can read from a file by using standard input and output.
Data Processing
“Boston”
2
“San Diego” 40
…
--------------------------------------------------------int lowestTemperature = 200;
String coldestCity = “”;
while (!isEmpty()) {
String city = StdIn.getString();
int temperature = StdIn.getInt();
if (temperature < lowestTemperature) {
lowestTemperature = temperature;
coldestCity = city;
}
}
Function

Information Hiding



Using functions, we can hide the details of a procedure.
This is the basic way of constructing large systems.
The most important feature of a function is its “interface”
public static TYPE functionName(TYPE a1, TYPE a2, …)
output
input

Design by contract

Each function is a “contract”.

From the client side (the caller): the function requires that the
client must fulfill some condition before calling some procedure.
For instance, function Math.sqrt(x) requires that x >= 0.

The function is a service provider: it must complete some
specified task. For instance, Math.sqrt(x) will compute the square
root of x when the function returns.

The client condition is termed as “precondition” and the service
condition is called “postcondition”.
Math Functions

Math functions
double x = -1000.0;
double y = Math.abs(x);
Others: Math.sin()
Math.cos()
Math.random()
Math.round()
Math.max()
…
Recursion

Recursion is an important method to construct functions to
solve problems.

To construct a recursive function:



You should have a method to “reduce” your problem into smaller
same problems that can be combined to solve the current
problem.
You know how to solve the trivial base problem.
You make sure that the reeducation plan will NOT go infinitely.
Recursion Example:

Example: Test whether a number is a power of 2.
boolean isPowerOfTwo(int n)
{
if (n == 1)
return true;
if (n % 2 == 1)
return false;
return isPowerOfTwo(n/2);
}
Iteration or Recursion?

Even though iteration is more appealing at first thought,
recursion solution is usually easier to construct (bug free).

Some times recursion is not efficient (to compute a Fibonacci
sequence).
Java Style


A good programming style enables us to write correct
programs.
Check this out:
http://www.javaranch.com/style.jsp