Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS-I MidTerm Review Hao Jiang Computer Science Department Boston College.

Similar presentations


Presentation on theme: "CS-I MidTerm Review Hao Jiang Computer Science Department Boston College."— Presentation transcript:

1 CS-I MidTerm Review Hao Jiang Computer Science Department Boston College

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

3 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.

4 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), +, -

5 Built in Data Types Boolean types are for logic computing Boolean Type: boolean liberals: true, false Operators: &&(and), ||(or), ! (not) Comparison Boolean type can be generated by comparison operations: >, =, <=, ==, != For example, expression (a +c >= b) has a boolean type

6 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

7 The Precedence of Operators ( ) !, unary -, unary +, ++(post), --(post) ++(pre), --(pre) *, /, % +, -, >= ==, != && || = High low Example: a++ > 5 || b < 6  ((a++) > 5) || (b < 6) a && b || c && d (a &&b) || (c && d)

8 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.

9 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 “=“ int n; double x, y; n = 10 + 5 - 4; int m = 20; n = m + n; x = 100 / n; n = x; illegal operation n = (int) x; promotion variable = expression; += -= *= /= Special Assignments How can you change the value of a variable?

10 The Scope of Variables Variable Scope: the part of code where you can reference a variable. { int y; int x; { int z; } Scope of y Scope of x { int x; int y; } Different x, y from the previous block Scope of z A block in Java is usually enclosed by { } for instance: A function body, or blocks in if, for or while statements.

11 Array Array is a data structure: a sequence of same type data indexed by integers. To construct a 1D array: You can also construct higher dimensional arrays: 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] 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;

12 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.

13 The Flow of a Program Straight line code If condition f() Else g() loops Main()f() g()

14 Straight Line Code Logic group1 Logic group 2 Logic group 3 Good program structure Logic group 3 Logic group 2 Logic group1 Bad program structure

15 If Statements Nested if statement: if (isA) doA; if (isB) doB; if (isC) doC; if (isA) doA; else if (isB) doB; else if (isC) doC; If (condition) { statements } else { statements } or If (condition) { statements }

16 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.

17 While Loops double s = 0; int n = 0; while ( !StdIn.isEmpty() ) { double x = StdIn.readDoulbe(); s += x; n ++; } s = s / n; while(s.charAt(0) ==‘ ‘) s = s.substring(1); While (n%2 == 0) { n = n/2; } Average: Remove white space: Remove factor 2:

18 For Loops int N = 100; int s = 0; for (int i = 0; i < N; i++) { s += i; } 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(“ “); } Sum: Harmonic number: Checker board:

19 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.

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

21 1. The loop will terminate somehow 2. Some loop invariant holds in each each loop. 3. When the loop terminates, we obtain the desired result. Checking a Loop public static boolean isPowerOf2(int n) { while (n % 2 == 0) { n = n / 2; } if (n == 1) { return true; } else { return false; }

22 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; }

23 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

24 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”.

25 Math Functions Math functions double x = -1000.0; double y = Math.abs(x); Others: Math.sin() Math.cos() Math.random() Math.round() Math.max() …

26 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.

27 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); }

28 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).

29 Java Style A good programming style enables us to write correct programs. Check this out: http://www.javaranch.com/style.jsp


Download ppt "CS-I MidTerm Review Hao Jiang Computer Science Department Boston College."

Similar presentations


Ads by Google