CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

Similar documents
CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 9: OCT. 4TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Information Science 1

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 14: OCT. 25TH INSTRUCTOR: JIAYIN WANG

Decision Making in C

Information Science 1

Flow Control. CSC215 Lecture

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Building Java Programs Chapter 2

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

Building Java Programs Chapter 2. bug. Primitive Data and Definite Loops. Copyright (c) Pearson All rights reserved. Software Flaw.

Building Java Programs Chapter 2

Building Java Programs

Information Science 1

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

Repetition Structures

Programming Lecture 4

Introduction. C provides two styles of flow control:

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Information Science 1

CS110D: PROGRAMMING LANGUAGE I

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

5. Control Statements

Chapter 17. Fundamental Concepts Expressed in JavaScript

Operators. Java operators are classified into three categories:

Recap: Assignment as an Operator CS 112 Introduction to Programming

Full file at

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Course Outline. Introduction to java

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

REPETITION CONTROL STRUCTURE LOGO

Programming Logic and Design Seventh Edition Chapter 2 Elements of High-Quality Programs

CS 106 Introduction to Computer Science I

Programming Lecture 4

The for Loop. Lesson 11

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

IT 374 C# and Applications/ IT695 C# Data Structures

CS 112 Introduction to Programming

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

The simplest way to evaluate the expression is simply to start at the left and work your way across, keeping track of the total as you go:

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Introduction to Software Development (ISD) Week 3

Repetition with for loops

CSc Introduction to Computing

Lab # 2. For today s lab:

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CS 374 Fall 2014 Homework 2 Due Tuesday, September 16, 2014 at noon

C: How to Program. Week /Mar/05

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

1. The programming language C is more than 30 years old. True or False? (Circle your choice.)

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Following is the general form of a typical decision making structure found in most of the programming languages:

CSI33 Data Structures

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Computer Science II Lecture 1 Introduction and Background

1 Lexical Considerations

Object Oriented Software Design

QUIZ Friends class Y;

Computer Programming : C++

CSE 142. Lecture 1 Course Introduction; Basic Java. Portions Copyright 2008 by Pearson Education

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

3 The L oop Control Structure

Quiz 1: Functions and Procedures

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

CS 231 Data Structures and Algorithms, Fall 2016

Basics of Java Programming

Repetition CSC 121 Fall 2014 Howard Rosenthal

DATA AND ABSTRACTION. Today you will learn : How to work with variables How to break a program down Good program design

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

Datatypes, Variables, and Operations

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

Introduction to C Programming

Software Design & Programming I

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Full file at C How to Program, 6/e Multiple Choice Test Bank

Primitive data, expressions, and variables

Loops (while and for)

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

We have written lots of code so far It has all been inside of the main() method What about a big program? The main() method is going to get really

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

printf( Please enter another number: ); scanf( %d, &num2);

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Sudoku-4: Logical Structure

CT 229 Java Syntax Continued

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

Transcription:

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG 1

Notice Prepare the Weekly Quiz The weekly quiz is for the knowledge we learned in the previous week (both the class on Tuesday and Thursday) Review the class quiz Review the class slides, especially the review part I will mark the important knowledge in red in the class slides Requests for the weekly quiz Open book, but no electronic devices allowed The first two weekly quiz are considered as practice, no impacting for your finial grading Assignments The Class 8 Exercise for today is posted here. The homework 2 and posted it here They are due this coming Sunday, at 11:59 PM. 2

Review The for loop In programming, we often do the same thing many times To make this possible programming languages provide loops The simplest kind of loop is the for loop Suppose you wanted to print the first 5 perfect squares We need to repeat something 5 times, changing a value each time 3

The for loop A for statement has two major parts Three statements inside parentheses that control the loop A series of statements executed with each pass through the loop The series of statements are called the loop body... and are enclosed in curly braces, { } Here is the format for the for loop for (INITIALIZATION; CONTINUATION_TEST; UPDATE) { } STATEMENT;... 4

The for loop The code inside the parentheses controls the loop It consists of three separate statements on the same line separated by semi- colon ; 5

The for loop Declare the variable Assign it its first value It s done before entering the loop An expression that returns a boolean value The loop will continue if the continuation test is true Otherwise, the loop will stop The update changes the value after the loop statements have been executed before the continuation test i is called control variable or loop variable It s used to count the number of pass trough the loop It must be an integer The traditional names for such variable is i, j, or k 6

The for loop in Action Here is the flow chart for a for loop Give the control variable its starting value This happens only once Evaluate the test condition If the test is true: Execute all statements. Then, update the control variable If the test is false, jump out of the loop 7

Common Programming Error: Forgetting Curly Braces One of the most common Java programming errors is forgetting to use curly braces The curly braces mark the beginning and end of the loop body The loop body is the series of statements... that are executed with each pass through the loop It prints Hi! 10 times and Ho! once 8

for Loop Patterns The three control statements in a for loop can be used many ways. But some patterns are more common than others The most common for loop pattern is the following for (int LOOP_VARIABLE = 1; LOOP_VARIABLE <= n; LOOP_VARIABLE++) { } STATEMENT;... This loop starts with the control variable set to 1 and executes the statements contained in the loop body n times So the following code will produce this output: 9

for Loop Patterns Often, it is more convenient to start counting from 0 instead of one Here is the pattern for (int LOOP_VARIABLE = 0; LOOP_VARIABLE < n; LOOP_VARIABLE++) { } STATEMENT;... There are two differences between this pattern and the previous one The control variable is initialized to 0 instead of 1 And the continuation test uses < instead of <= 10

for Loop Patterns Usually the update statement increases the value of the loop variable But you can also run a for loop backwards Here the the pattern for a decrementing loop for (int LOOP_VARIABLE = n; LOOP_VARIABLE >= 1; LOOP_VARIABLE- - ) { STATEMENT;... } 11

Nested for Loops The for loop executes one or more statements But the for loop is, itself, a statement That means you can have one for loop inside another for loop This is called a nested loop Here's an example Each loop has its own, distinct, loop variable It s easier to read nested loops from the inside out The innermost loop runs five times to print a message The outmost loop runs the innermost loop tem times Notice the control variable for each loop must be different 12

Nested for Loops One more example The inner loop prints the value of the control variable as it goes from 1 to 3 The output loop executes the inner loop 6 times The output is 13

New Material Outline Scope The Scope of for Loop Variable Code Block Pseudocode Reusing Existing Code Class Constants 14

Scope As programs get longer you have to be careful... that different part of the code do not conflict with each other One way programming languages deal with this problem... is using a concept call scope The scope of a an identifier is the part of the program where it can be used Scope applies to Variables Methods When an variable or method is outside its scope that the compiler does not know about it so it is invisible 15

Scope of Static Method The scope of a static method... is the entire class in which it appears So any static method can call any other static method... no matter which comes first... if they are in the same class They can also call static methods in other classes... but then they have to give the class name 16

Scope of Static Method In the following code, scope of the static method sayhello... is all the sections of the program shown in red 17

Scope of Variable The scope of variables is different In general, the scope of a variable starts where it is declared... and ends which the closing curly brace that encloses it The way to identify the scope of a variable is: find the pair of curly braces that directly encloses the variable declaration the scope is from the point where it s declared to the closing curly brace 18

Scope of Variable So in the in the code above the scope of the variable message is shown in light blue... The same variable name can be used in different methods without the compiler becoming confused A variable declared inside a method is called local variables It s a good programing practice to declare variables in the smallest scope possible. This is called localizing variables 19

Outline Scope The Scope of for Loop Variable Code Block Pseudocode Reusing Existing Code Class Constants 20

The Scope of for Loop Variable The general scope rule for variables does not work for loop variables The scope of a loop variable is The part of the code between the for loop curly braces And the part of the code between the parentheses that starts the loop So the scope of the loop variable i is 21

The Scope of for Loop Variable You will get a syntax error if the code is written as follows: 22

Outline Scope The Scope of for Loop Variable Code Block Pseudocode Reusing Existing Code Class Constants 23

Code Block The part of a Java program between an open curly brace, {... and the matching closing curly brace, }... is called a code block A code block is section of code that is surrounded... by a matched pair of curly braces, { } We can use the idea of a code block to describe the scope of a variable The scope of a variable starts with the line where it is declared... and continues to the end of the code block in which it is declared 24

Outline Scope The Scope of for Loop Variable Code Block Pseudocode Reusing Existing Code Class Constants 25

Pseudocode When you write more complex algorithms, it s hard to write the entire algorithm immediately One way to deal with this is to use pseudocode When we write pseudocode, we write steps to solve a problem in simple English Then we break down these steps into simpler steps We keep doing this until we have an English description of the steps that can then be translated into Java code 26

Pseudocode Suppose we wanted to write a program to print following triangle Our first crack at the pseudocode might look like this draw a downward pointing triangle of 5 lines using asterisks But if you think for a moment, you will realize that this is not enough The following figure is a downward pointing triangle but is not what we want 27

Pseudocode So let's refine our pseudocode: draw a downward facing triangle of 5 lines using asterisks with no space between them But the following triangle would also satisfy this description So let's try again draw a downward facing triangle of 5 lines using asterisks with no space between them and the downward sides are of equal length Up to now, we have just refined our description of what needs to be done This is an important first step 28

Pseudocode But now we have to start thinking about how we will describe this to the computer using actions it can perform It seems clear we will need a for loop, so let's start with that But each line is different Each line must print a different number of spaces before it prints the asterisks So we need to increase the number of spaces in each line starting with 0 So let's refine our pseudocode 29

Pseudocode But once we have the right number of spaces and asterisks... we need to go to the next line So let's try again The next step is to calculate the number of asterisks and spaces... needed for each line If we number the lines 1 through 5... we want the following values for each line 30

Pseudocode There is a simple algebraic relationship... between the line number... and the number of spaces and asterisks The number of spaces is equal to the line number minus 1 The number of asterisks is trickier Notice that the number of asterisks decreases by two with each line But what about the first line? If we add 2 to 9 we get 11 So if we start with 11... and subtract 2 at each line... we get the right number of asterisks for each line 31

Pseudocode Let's add this to the for loop in our pseudocode The lines to write asterisks and spaces each need a for loop 32

Pseudocode Translating this into Java, we get When we run this code we get 33

Outline Scope The Scope of for Loop Variable Code Block Pseudocode Reusing Existing Code Class Constants 34

Reusing Existing Code Sometimes the easiest way to write a program... is to modify some existing code Let's say you want to write a program to draw the following We might be able to use DrawDownwardTriangle.java instead If you look carefully, you will see that the 1st line of DrawDownwardTriangle... is the same as the 5th line of the figure we want... And so on 35

Reusing Existing Code So all we have to do to get the figure we want is change the direction of counting in the outer for loop of DrawDownwardTriangle In DrawDownwardTriangle.java the outer loop counted from 1 to 5 For this code, we want the outer loop to count from 5 to 1 Here is how we do it 36

Outline Scope The Scope of for Loop Variable Code Block Pseudocode Reusing Existing Code Class Constants 37

Class Constants For the code in DrawCone.java for ( int i = 1; i <= (11 - (2 * line_number)); i++) Someone reading the code for the first time might ask "Why 11?" Programmers call values like this magic numbers They make the program work but it is not clear how Magic numbers make for bad code Whenever we can, we should replace such numbers with an expression... and those expressions should use constants A constant is like a variable except its value cannot be changed 38

Class Constants When creating a constant, you must use the keyword final... using the following format final DATA_TYPE CONSTANT_NAME = VALUE; like this final inthours_in_a_day = 24; By convention, constant names are spelled using ALL_CAPITALS The best place to put a constant is inside the class but outside all the methods. Such constants are called class constants. That way they are available to all methods in the class. The format is like this: public static final DATA_TYPE CONSTANT_NAME = VALUE; 39

Class Constants So our new version of DrawCone will look like this Add the class constant NUMBER_OF_LINES Change from 5 to NUMBER_OF_LINES Add the variable stars and change the magic number 11 to the expression using the new constant Use the new variable stars in continuation test 40

Class 8 Quiz 1. What do you call the series of statements that are executed with each pass through the loop? the loop body 2. What is a code block? all the statements between an open curly brace and the corresponding closing curly brace 3. What is scope? the part of a code in which an identifier (name) has meaning 4. What is the scope of a method? the entire class in which it is defined 41

Class 8 Quiz 5. What is the scope of a variable that is not a loop variable? from where it is defined to the end of the code block in which it is defined 6. What is the scope of a loop variable? the parentheses after the keyword for as well as the loop body 7. What is a constant? a "variable" whose value never changes 8. What is the scope of a constant that is not a class constant? the same as a variable. From where it is defined to the end of the code block in which it is defined 42

Class 8 Quiz 9. What is the scope of a class constant? The entire class in which it is declared 10. Write the statement that declares the integer constant DAYS_IN_WEEK. public static final int DAYS_IN_WEEK = 7; 43

Weekly Quiz1 1. What must the name of the source code file for the Java class CountToTenbe? CountToTen.java 2. If you want to run a Java program from the command line, what must the source code file contain inside the class definition? a main method 3. What is the first line of a method called? method header 4. What is a method? a group of statements that performs a specific task 44

Weekly Quiz1 5. Write the Java statement that prints "Hello world!"? System.out.println("Hello world!"); 6. In the previous statement, what does Java call "Hello world!"? a string literal 7. Write the escape sequence for the Tab character? \t 8. Can you use a Java keyword as an identifier? no 45

Weekly Quiz1 9. Is 1st_try a valid Java identifier? no 10. Write a one line comment that contains the text "This is a one line comment" // This is a one line comment 46