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

Slides:



Advertisements
Similar presentations
Chapter 4 Computation Bjarne Stroustrup
Advertisements

Semantics Static semantics Dynamic semantics attribute grammars
Programming Languages and Paradigms The C Programming Language.
Fundamental Programming Structures in Java: Control Flow, Arrays and Vectors.
Expressions and Statements. 2 Contents Side effects: expressions and statements Expression notations Expression evaluation orders Conditional statements.
CS-I Final Review Hao Jiang Computer Science Department Boston College.
Variables Pepper. Variable A variable –box –holds a certain type of value –value inside the box can change Example –A = 2B+1 –Slope = change in y / change.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
CS-I MidTerm Review Hao Jiang Computer Science Department Boston College.
Libraries Programs that other people write that help you. #include // enables C++ #include // enables human-readable text #include // enables math functions.
Fundamentals of Python: From First Programs Through Data Structures
Fundamentals of Python: First Programs
1 Course Lectures Available on line:
CIS Computer Programming Logic
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
Introduction Algorithms and Conventions The design and analysis of algorithms is the core subject matter of Computer Science. Given a problem, we want.
CSE 131 Computer Science 1 Module 1: (basics of Java)
JAVA 0. HAFTA Algorithms FOURTH EDITION Robert Sedgewick and Kevin Wayne Princeton University.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Variables, Arithmetic, etc.)
Property of Jack Wilson, Cerritos College1 CIS Computer Programming Logic Programming Concepts Overview prepared by Jack Wilson Cerritos College.
Visual Basic Programming
Algorithm Design.
Java Programming Java Basics. Data Types Java has two main categories of data types: –Primitive data types Built in data types Many very similar to C++
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
Java Nuts and Bolts Variables and Data Types Operators Expressions Control Flow Statements Arrays and Strings.
2.1 Functions. Functions in Mathematics f x y z f (x, y, z) Domain Range.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CSI 3125, Preliminaries, page 1 Data Type, Variables.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
Language Find the latest version of this document at
11 PART 2 ARRAYS. 22 PROCESSING ARRAY ELEMENTS Reassigning Array Reference Variables The third statement in the segment below copies the address stored.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Lecturer: Nguyen Thi Hien Software Engineering Department Home page: hienngong.wordpress.com Chapter 2: Language C++
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
1 C++ Programming C++ Basics ● C++ Program ● Variables, objects, types ● Functions ● Namespace ● Tests ● Loops ● Pointers, references.
CS314 – Section 5 Recitation 9
C++ LANGUAGE MULTIPLE CHOICE QUESTION
Information and Computer Sciences University of Hawaii, Manoa
Definition of the Programming Language CPRL
GC211Data Structure Lecture2 Sara Alhajjam.
Programming Languages and Paradigms
Programming Paradigms
Type Conversion, Constants, and the String Object
Java Programming: From Problem Analysis to Program Design, 4e
Java Programming: Guided Learning with Early Objects
Control Structures – Selection
An Introduction to Java – Part I, language basics
In this class, we will cover:
Coding Concepts (Basics)
Chapter 6: Repetition Statements
The structure of programming
In this class, we will cover:
Programming Languages and Paradigms
Presentation 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: L “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 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

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  “123”  “123”

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)

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 “=“ int n; double x, y; n = ; 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?

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.

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;

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 Straight line code If condition f() Else g() loops Main()f() g()

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

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 }

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 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:

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:

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)

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

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 = ; 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: