COMP 110-001 Mid-Term Review Yi Hong May 27, 2015.

Slides:



Advertisements
Similar presentations
Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
Advertisements

Lecture 2 Introduction to C Programming
Introduction to C Programming
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Introduction to Programming with Java, for Beginners Primitive Types Expressions Statements Variables Strings.
10-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
CMT Programming Software Applications
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
COMP 110 Primitive Types, Strings, and Console I/O Tabitha Peck M.S. January 23, 2008 MWF 3-3:50 pm Philips
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
COMP 110 Branching Statements and Boolean Expressions Tabitha Peck M.S. January 28, 2008 MWF 3-3:50 pm Philips
Introduction to C Programming
Hello, world! Dissect HelloWorld.java Compile it Run it.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
COMP Classes Yi Hong May 22, Announcement  Lab 2 & 3 due today.
COMP More About Classes Yi Hong May 22, 2015.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Catie Welsh January 12, 2011 MWF 1-1:50 pm Sitterson
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Primitive Types, Strings, and Console I/O Chapter 2.1 Variables and Values Declaration of Variables Primitive Types Assignment Statement Arithmetic Operators.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
CPS120: Introduction to Computer Science
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
COMP 110 switch statements and while loops Luv Kohli September 10, 2008 MWF 2-2:50 pm Sitterson
Introduction to Java Java Translation Program Structure
COMP Flow of Control: Branching 1 Yi Hong May 19, 2015.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs -
COMP 110 Worksheet review, debugger Luv Kohli September 29, 2008 MWF 2-2:50 pm Sitterson 014.
COMP Primitive and Class Types Yi Hong May 14, 2015.
COMP 110 Classes Luv Kohli October 1, 2008 MWF 2-2:50 pm Sitterson 014.
Catie Welsh February 2,  Program 1 Due Today by 11:59pm today  Program 2 Assigned Today  Lab 2 Due Friday by 1:00pm 2.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Catie Welsh February 23,  Lab 4 due on Friday  Lab 5 will be assigned on Friday 2.
By Mr. Muhammad Pervez Akhtar
CPS120: Introduction to Computer Science Variables and Constants.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
COMP 110: Spring Announcements Lab 1 due Wednesday at Noon Assignment 1 available on website Online drop date is today.
A Sample Program public class Hello { public static void main(String[] args) { System.out.println( " Hello, world! " ); }
COMP 110 Branching Statements and Boolean Expressions Luv Kohli September 8, 2008 MWF 2-2:50 pm Sitterson
Catie Welsh January 31,  Project 1 Due Wednesday  Lab 1 Grades are posted 2.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Catie Welsh March 4,  Midterm on Monday, March 14th ◦ Closed books, no notes, no computer  No office hours during Spring Break ◦ However, I will.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
COMP Review of Chapter 1 & 2
Information and Computer Sciences University of Hawaii, Manoa
Michele Weigle - COMP 14 - Spr 04 Catie Welsh February 21, 2011
Yanal Alahmad Java Workshop Yanal Alahmad
COMP 110 Review for midterm exam
CET 3640 – Lecture 2 Java Syntax Chapters 2, 4, 5
Introduction to C++ Programming
Chapter 2 Edited by JJ Shepherd
Expressions and Assignment
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Primitive Types and Expressions
Presentation transcript:

COMP Mid-Term Review Yi Hong May 27, 2015

Announcement  Midterm on Friday, May 29 Closed books, no notes, no computer

Today  A whirlwind tour of almost everything we have covered so far  You should start preparing for mid-term if you haven’t  Finish the mid-term practice before Thursday  Review slides and textbook  Review your lab / assignment code

Hardware vs. Software  Hardware - physical machine CPU, Memory  Software - programs that give instructions to the computer Windows XP, Games, Eclipse 4

Hardware  CPU – the “brain” of your computer  Memory – stores data for the computer How much the “brain” can remember Main memory: RAM Auxiliary memory: Hard Drive 5

Memory  Measured in bytes  1 byte = 8 bits  Bit is either 0 or 1  Language of the computer is in bits 6

Programming Languages 7 Your Program Compiler Machine Language (Bits) High-level language (human readable) Low-level language (computer readable)

Algorithms and Pseudocode  Algorithm – a set of instructions for solving a problem  Pseudocode – combination of code and English used to express an algorithm before writing algorithm into code We can also use flow-chat to write pseudocode 8

Variables  Used to store data in a program  The data currently in a variable is its value  Name of variable is an identifier Letters, digits, underscore Cannot start with digits  Can change value throughout program  Choose variable names that are meaningful! 9

How to Use Variables  Declare a variable int number;  Assign a value to the variable number = 37;  Change the value of the variable number = 513; 10

Keywords  Reserved words with predefined meanings  You cannot name your variables keywords  if, else, return, new 11

Data Type  What kind of value the variable can hold  Two kinds of types. Primitive type - indecomposable values Names begin with lowercase letters int, double, char, float, byte, boolean, and others Class type - objects with both data and methods Names by convention begin with uppercase letter Scanner, String, Student 12

Assignment Statements  Change a variable’s value  Syntax variable = expression;  Example sleepNeeded = 8; sleepDesired = sleepNeeded * 2; 13

Assignment Compatibilities int x = 5; double y = 12.7; y = x;  = x = y;  = 14 OK Not OK byte  short  int  Long  float  double

Type Casting x = (int) y;  = 15 (int) OK

Arithmetic Operators  Unary operators +, -, ++, --, !  Binary arithmetic operators *, /, %, +, - rate*rate + delta 1/(time + 3*mass) (a - 7)/(t + 9*v) 16

Modular Arithmetic: %  Remainder  7 % 3 = 1 (7 / 3 = 2, remainder 1)  8 % 3 = 2 (8 / 3 = 2, remainder 2)  9 % 3 = 0 (9 / 3 = 3, remainder 0) 17

Parentheses and Precedence  Expressions inside parentheses evaluated first (cost + tax) * discount cost + (tax * discount)  Precedence rules Highest Precedence First: the unary operators +, -, !, ++, and -- Second: the binary arithmetic operators *, /, % Third: the binary arithmetic operators + and – Lowest Precedence 18

Errors  Syntax error – grammatical mistake in your program Java will not compile programs with syntax error  Run-time error – an error that is detected during program execution E.g., exceptions during execution  Logic error – a mistake in a program caused by the underlying algorithm 19

Strings  A string (lowercase) is a sequence of characters “Hello world!” “Enter a whole number from 1 to 99.”  String (capital S) is a class in Java, not a primitive type 20

String String animal = “aardvark”; System.out.println(animal); aardvark 21

String Concatenation String animal = “aardvark”; String sentence; sentence = “My favorite animal is the ” + animal; My favorite animal is the aardvark 22

String’s Methods  myString.length();  myString.equals(“a string”);  myString.toLowerCase();  MyString.indexOf(‘ ’);  myString.trim();  …  For other methods, check Java API 23

String Indices 24 UNCisGreat String output = myString.substring(1, 8);

String Indices 25 UNCisGreat String output = myString.substring(1, 8);

Escape Characters 26 \”Double quote \’Single quote \\Backslash \nNew line \rCarriage return \tTab

Keyboard Input Scanner keyboard = new Scanner(System.in); int num = keyboard.nextInt(); 27

Comments // this is a comment /* This is also a comment. it ends here --->*/ 28

Boolean Expressions  An expression that is either true or false  Examples: It is sunny today (true) 10 is larger than 5 (true) Today is Saturday (false) 29

if/else Statements 30 Is input greater than 10? Yes No Prompt user for integer Print: “big number” Print: “small number” import java.util.*; public class FlowChart { public static void main(String[] args) { System.out.println("Give me an integer:"); Scanner keyboard = new Scanner(System.in); int inputInt = keyboard.nextInt(); if (inputInt > 10) { System.out.println("big number"); } else { System.out.println("small number"); } } }

If-else-if for Multi-Branch Selections if ( case1 ) { // branch 1 } else if ( case2) { // branch 2 } else if ( case3 ) { … } else { … } if (year==1) { System.out.println(“Freshman”); } else if (year==2) { System.out.println(“Sophomore”); } else if (year==3) { System.out.println(“Junior”); } else { System.out.println(“Senior”); }

Java Comparison Operators for Primitive Values 32 == Equal to != Not equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to Example expressions: variable <= 6 myInt > 5 5 == 3 The result is a boolean value (true/false)

Boolean Type  Can be either true or false boolean sunny = true; boolean cloudy = false; if (sunny || cloudy) { // walk to school } 33

&&, || operators  AND if ((temperature > 50) && (temperature < 75)) { // walk to school }  OR if (sunny || cloudy) { // walk to school } 34

The ! (NOT) operator  !true is false  !false is true  Example: walk to school if it is NOT cloudy if (!cloudy) { // walk to school } 35

Loops  Loop: part of a program that repeats  Body: statements being repeated  Iteration: each repetition of body  Stopping condition 36 Start Enough sandwiches? Distribute sandwiches No Yes Make sandwich

Types of Loops  while Safest choice Not always the best  do-while Loop iterates AT LEAST once  for Similar to while, but often more convenient syntax Most useful when you have a known number of iterations you need to do 37

Using a while Loop int n = 1; while (n <= 10) { System.out.println(n); n = n + 1; } 38

Using a for Loop int n; for (n = 1; n <= 10; n++) { System.out.println(n); } 39

Infinite Loop Example int n; for (n = 1; n <= 10; n = 0) { System.out.println(n); } 40

The break statement for (int item = 1; item <= 5; item++) { System.out.print(“Enter cost of item #” + item + “: $”); amount = keyboard.nextDouble(); total = total + amount; if (total >= 100) { System.out.println(“You spent all your money.”); break; } System.out.println(“Your total so far is $” + total); } System.out.println(“You spent $” + total); 41

Ending a Loop  Count-controlled loops If you know the number of loop iterations for (count = 0; count < iterations; count++)  User-controlled loops Change the value of control variable E.g., Ask-before-iterating, or sentinel value ( if user input is smaller than 0) E.g., booleans, matching is found 42

Nested Loops Example for (int i = 1; i<10; i++) { for (int j = 1; j<=i; j++) { System.out.print( i + ”*” + j + “=“ + (i * j) + “\t“); } System.out.println(); } 43 Inner loop Outer loop

Classes, Objects, and Methods  Class: a definition of a kind of object  Object: an instance of a class Contains instance variables (data) and methods  Methods Methods that return a value Methods that return nothing 44

Class  A class is the definition of a kind of object A blueprint for constructing specific objects 45

Objects, Instantiation Object Name: patsCar amount of fuel: 10 gallons speed: 55 miles per hour license plate: “135 XJK” Object Name: suesCar amount of fuel: 14 gallons speed: 0 miles per hour license plate: “SUES CAR” Object Name: ronsCar amount of fuel: 2 gallons speed: 75 miles per hour license plate: “351 WLF” Instantiations, or instances, of the class Automobile

 Create an object jack of class Student Student jack = new Student(); Scanner keyboard = new Scanner(System.in);  Create an object keyboard of class Scanner Creating an Object Create an object Return memory address of object Assign memory address of object to variable

 Data defined in the class are called instance variables public String name; public int classYear; public double gpa; public String major; Instance Variables public: no restrictions on how these instance variables are used (more details later – public is actually a bad idea here) Data type: int, double, String… variables

 Two kinds of methods Methods that return a value Examples: String’s substring() method, String’s indexOf() method, etc. Methods that return nothing Perform some action other than returning an item Example: System.out.println() 49 Methods

public String getMajor() { return major; } public void increaseYear() { classYear++; } 50 Methods returns a String returns nothing return type

 Object, followed by dot, then method name, then () Order, type, and number of arguments must match parameters specified in method heading  Use them as Java statements Student jack = new Student(); jack.classYear = 1; jack.increaseYear(); System.out.println(“Jack’s class year is ” + jack.classYear); 51 Calling Methods That Return Nothing

 Object, followed by dot, then method name, then () (the same as before)  Use them as a value of the type specified by the method’s return type Student jack = new Student(); jack.major = “Computer Science”; String major = jack.getMajor(); System.out.println(“Jack’s full name is ” + jack.getName()); System.out.println(“Jack’s major is ” + major); 52 Calling Methods That Return a Value

 Instance variables Declared in a class Confined to the class Can be used in any method in this class  Local variables Declared in a method Confined to the method Can only be used inside the method 53 Local / Instance Variables public class Student { public String name; public int classYear; public String major; public void printInfo(){ String info = name + “:” + major + “:” + classYear; System.out.println(info); } public void increaseYear(int inc) { classYear += inc; }

An Example public class Student { public String name; public int classYear; public String major; public void printInfo() { String info = name + “: ” + major + “: ” + classYear ; System.out.println(info); } public void increaseYear(int inc) { classYear += inc; } 54 classYear and name are instance variables can be used in any method in this class info is a local variable declared inside method printInfo() can only be used inside method printInfo()

public class Student { public String name; public int classYear; public String major; public void printInfo() { String info = name + “: ” + major + “: ” + classYear ; System.out.println(info); } public void increaseYear(int inc) { classYear += inc; info = “info changed a bit”; } } 55 An Example Java will not recognize info ✗

 Parameters are used to hold the value that you pass to the method  Parameters can be used as (local) variables inside the method public int square(int number) { return number * number; } Methods with Parameters Parameters go inside parentheses of method header

 Multiple parameters separated by commas public double getTotal(double price, double tax) { return price + price * tax; } Methods with Multiple Parameters

public class SalesComputer { public double getTotal(double price, double tax) { return price + price * tax; } //... } SalesComputer sc = new SalesComputer(); double total = sc.getTotal(“19.99”, Color.RED); double total = sc.getTotal(19.99); double total = sc.getTotal(19.99, 0.065); int price = 50; total = sc.getTotal(price, 0.065); Method Parameters and Arguments Automatic typecasting ✗ ✗ ✓ ✓

Calling Methods from Methods  In a method’s body, we can call another method receiving_object.method();  If calling a method in the same class, we do not need receiving_object: method();  Alternatively, use the this keyword this.method();

Several Common Mistakes  Unwanted semicolon after if / for statements if (a>b); // this semicolon causes an empty if-branch c++; // this line is always executed for(int i = 0; i<10; i++); // this semicolon indicates an empty loop body c++; // this is executed only once  Unpaired brackets Use indentation to help checking Use Eclipse’s auto format function

Indentation  Indentation Makes code easier to read Helps with finding syntax and logic errors Indent code that goes between { and }  Be consistent! 61

Next Class  Go through questions from mid-term practice worksheet  Q&A