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

Slides:



Advertisements
Similar presentations
Chapter 4 Computation Bjarne Stroustrup
Advertisements

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.
Shlomo Hershkop1 Introduction to java Class 1 Fall 2003 Shlomo Hershkop.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
1 Course Lectures Available on line:
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
CIS Computer Programming Logic
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)
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
From C++ to Java A whirlwind tour of Java for C++ programmers.
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.
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.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
Algorithm Design.
Controlling Program Flow. Data Types and Variable Declarations Controlling Program Flow.
1 CS 007: Introduction to Computer Programming Ihsan Ayyub Qazi.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Java Basics Hussein Suleman March 2007 UCT Department of Computer Science Computer Science 1015F.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
COM S 207 Literal, Operator, and Expression Instructor: Ying Cai Department of Computer Science Iowa State University
CS-I MidTerm Review Hao Jiang Computer Science Department Boston College.
1 Introduction  Algorithms  Data structures  Abstract data types  Programming with lists and sets © 2008 David A Watt, University of Glasgow Algorithms.
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.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
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.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Topics introduced today (these topics would be covered in more detail in later classes) – Primitive Data types Variables Methods “for” loop “if-else” statement.
Repetition Statements
C++ LANGUAGE MULTIPLE CHOICE QUESTION
Information and Computer Sciences University of Hawaii, Manoa
Methods Chapter 6.
Primitive Data, Variables, Loops (Maybe)
Java Programming: From Problem Analysis to Program Design, 4e
Java Programming: Guided Learning with Early Objects
Control Structures – Selection
Introduction to Programming in Java
An Introduction to Java – Part I, language basics
In this class, we will cover:
Control Structure Chapter 3.
Chapter 2 Programming Basics.
In this class, we will cover:
Names of variables, functions, classes
Programming Languages and Paradigms
Review of Previous Lesson
Loops CGS3416 Spring 2019 Lecture 7.
Control Structure.
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 Types: 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.

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

String Functions The following functions can be used to process strings String s = “abcd”; Char c = s.charAt(2); Int l = s.length(); String t = s.substring(0,2); t = s.substring(2); c = ‘c’ l = 4 t = “ab” t = “cd” abcdefg position 0 Position 13

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: A function that returns a string that reverse the original one, e.g. if the input is “abc” the output is “cba”. Base case: If the input is has a single character, return itself. Reduction plan: Reverse the substring starting from the second character and then connected with the first character. String reverseString(String str) { if (str.length() == 1) return str; string s = reverseString(str.substring(1)) + str.charAt(0); return s; }

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

The Procedure based Programming Get initial time Draw the Panel Start the Clock int hour = Integer.parseInt(args[0]); int minute = Integer.parseInt(args[1]); int second = Integer.parseInt(args[2]); drawFace() while (true) { clearHandsDrawingRegion(); drawHands(hour, minute, second); hour = updateHour(hour, minute, second); minute = updateMinute(hour, minute, second); second = updateSecond(hour, minute, second); wait(1); } Function blocksProcedures in Java The clock:

public static void main(String[] args) { int hour = Integer.parseInt(args[0]); Int minute = Integer.parseInt(args[1]); int second = Integer.parseInt(args[2]); drawFace(); while (true) { clearHandsDrawingRegion(); drawHands(hour, minute, second); hour = updateHour(hour, minute, second); minute = updateMinute(hour, minute, second); second = updateSecond(hour, minute, second); wait(1); } public class Clock { public static void drawMarkers() { … } public static void drawLetters() { … } public static void drawFace() { drawMarkers(); drawLetters(); } public static void clearHandsDrawingRegion() { … } public static void drawHands(int h, int m, int s) { … } public static int updateHour(int h, int m, int s) { … } public static int updateMinute(int h, int m, int s) { … } public static int updateSecond(int h, int m, int s) { … } The structure of the whole program