Introduction to Computer Programming

Similar documents
Building Java Programs

Building Java Programs

Building Java Programs

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Topic 4 Expressions and variables

Lecture 2: Operations and Data Types

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Building Java Programs Chapter 2

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

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

CSE 142, Summer 2014

CSE 142, Summer 2015

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Building Java Programs

Lecture 3 Tao Wang 1

CSc 110, Spring 2017 Lecture 3: Expressions, Variables and Loops. Adapted from slides by Marty Stepp and Stuart Reges

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example

Building Java Programs

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Primitive data, expressions, and variables

Chapter Legal intliterals: 22, 1, and d Results of intexpressions:

Basics of Java Programming

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Course Outline. Introduction to java

CS 112 Introduction to Programming

Declaration and Memory

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Basic Operations jgrasp debugger Writing Programs & Checkstyle

COMP 202 Java in one week

CS111: PROGRAMMING LANGUAGE II

4 WORKING WITH DATA TYPES AND OPERATIONS

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

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Introduction to Computer Programming

CS 106A, Lecture 5 Booleans and Control Flow

Programming with Java

SSEA Computer Science: Track A. Dr. Cynthia Lee Lecturer in Computer Science Stanford

UNIT- 3 Introduction to C++

Full file at

Chapter 02: Using Data

Full file at

Chapter 2: Using Data

COMP 202. Java in one week

JAVA OPERATORS GENERAL

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

SSEA Computer Science: CS106A. Dr. Cynthia Lee Lecturer in Computer Science Stanford

COMP Primitive and Class Types. Yi Hong May 14, 2015

ECE 122 Engineering Problem Solving with Java

I. Variables and Data Type week 3

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Chapter 2 ELEMENTARY PROGRAMMING

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Chapter 2: Using Data

LECTURE 3 C++ Basics Part 2

Elementary Programming

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

What did we talk about last time? Examples switch statements

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

Operators. Java operators are classified into three categories:

Chapter 2. Elementary Programming

Controls Structure for Repetition

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CS313D: ADVANCED PROGRAMMING LANGUAGE

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CS 302: Introduction to Programming

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

CEN 414 Java Programming

Fundamentals of Programming Data Types & Methods

Program Fundamentals

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Chapter 1 Lab Algorithms, Errors, and Testing

by Pearson Education, Inc. All Rights Reserved. 2

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

Basic Computation. Chapter 2

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Values, Variables, Types & Arithmetic Expressions. Agenda

Information Science 1

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Java Simple Data Types

Introduction to Java Unit 1. Using BlueJ to Write Programs

CS 106 Introduction to Computer Science I

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

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

Ex: If you use a program to record sales, you will want to remember data:

Object-Oriented Programming

2.5 Another Application: Adding Integers

Program Control Flow

Program Control Flow

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

CS110: PROGRAMMING LANGUAGE I

Transcription:

Introduction to Computer Programming Lecture 2- Primitive Data and Stepwise Refinement Data Types Type - A category or set of data values. Constrains the operations that can be performed on data Many languages ask the programmer to specify types Examples: integer, real number, string

How Does the Computer Store Data? Internally, computers store everything as 1s and 0s 104 01101000 "hi" 01101000110101 Java's Primitive Types Primitive Types - 8 simple types for numbers, text, etc. Java also has object types, which we'll talk about later

Data Types in Java Name Description Example int Integers (up to 231-1) 42, -3, 0, 926394 double Real numbers (up to 10 308 ) 3.1, -0.25, 9.4e3 char Single text characters 'a', 'X', '?', '\n' boolean Logical values true, false Expressions Expression - A value or operation that computes a value. Examples: 1 + 4 * 5 (7 + 2) * 6 / 3 42 The simplest expression is a literal value. A complex expression can use operators and parentheses.

Arithmetic Operators Operator: Combines multiple values or expressions. + addition - subtraction (or negation) * multiplication / division % modulus (a.k.a. remainder) Evaluating Expressions As a program runs, its expressions are evaluated. 1 + 1 evaluates to 2 (3 * 4); prints 12 How would we print the text 3 * 4?

Integer Division With / When we divide integers, the quotient is also an integer. 14 / 4 is 3, not 3.5 3 4 52 4 ) 14 10 ) 45 27 ) 1425 12 40 135 2 5 75 54 21 Integer Division With / More examples: 32 / 5 is 6 84 / 10 is 8 156 / 100 is 1 Dividing by 0 causes an error when your program runs.

Integer Remainder With % The % operator computes the remainder from integer division. 14 % 4 is 2 218 % 5 is 3 3 43 4 ) 14 5 ) 218 12 20 2 18 15 3 What is the result? 45 % 6 2 % 2 8 % 20 11 % 0 Applications Of % Operator Obtain last digit of a number: 230857 % 10 is7 Obtain last 4 digits: 658236489 % 10000 is6489 See whether a number is odd: 7 % 2 is1 42 % 2 is0

Precedence Precedence - Order in which operators are evaluated. Generally operators evaluate left-to-right. 1-2 - 3 = (1-2) - 3 = -4 But */%have a higher level of precedence than + -1 + 3 * 4 = 13 6 + 8 / 2 * 3 6 + 4 * 3 6 + 12 =18 Precedence and Parentheses Parentheses can force a certain order of evaluation: (1 + 3) * 4 = 16 Spacing does not affect order of evaluation 1+3 * 4-2 =11

Precedence Examples 1 * 2 + 3 * 5 % 4 \_/ 2 + 3 * 5 % 4 \_/ 2 + 15 % 4 \ / 2 + 3 \ / 5 1 + 8 % 3 * 2-9 \_/ 1 + 2 * 2-9 \ / 1 + 4-9 \ / 5-9 \ / -4 Precedence Questions What values result from the following expressions? 9 / 5 695 % 20 7 + 6 * 5 7 * 6 + 5 248 % 100 / 5 6 * 3-9 / 4 (5-7) * 4 6 + (18 % (17-12))

Real Numbers (Type double) Examples: 6.022, -42.0, 2.143e17 Placing.0 or. after an integer makes it a double. 62.0 13..5 The operators +-*/%() all still work with double. / produces 15.0 / 2.0 = 7.5 Precedence is the same: () before * / % before + - Real Number Example 2.0 * 2.4 + 2.25 * 4.0 / 2.0 \ / 4.8 + 2.25 * 4.0 / 2.0 \ / 4.8 + 9.0 / 2.0 \ / 4.8 + 4.5 \ / 9.3

Mixing Types When int and double are mixed, the result is a double. 4.2 * 3 is 12.6 The conversion is per-operator, affecting \ / only its operands. 7 / 3 * 1.2 + 3 / 2 \_/ 2 * 1.2 + 3 / 2 \ / 2.4 + 3 / 2 \_/ 2.4 + 1 \ / 2.0 + 10 / 3 * 2.5-6 / 4 2.0 + 3 * 2.5-6 / 4 \ / 2.0 + 7.5-6 / 4 \_/ 7 / 3 * 1.2 + 3 / 2 \_/ 2 * 1.2 + 3 / 2 \ / 2.4 + 3 / 2 \_/ 2.4 + 1 \ / 3.4 3 / 2 is 1 above, not 1.5 Mixing Types 2.0 + 10 / 3 * 2.5-6 / 4 \ / 2.0 + 3 * 2.5-6 / 4 \ / 2.0 + 7.5-6 / 4 \_/ 2.0 + 7.5-1 \ / 9.5-1 \ / 8.5

String Concatenation String concatenation - Using + between a string and another value to make a longer string. "hello" + 42 is "hello42" 1 + "abc" + 2 is "1abc2" "abc" + 1 + 2 is "abc12" 1 + 2 + "abc" is "3abc" "abc" + 9 * 3 is "abc27" "1" + 1 is "11" 4-1 + "abc" is "3abc" Use + to print a string and an expression's Receipt Example What's wrong with this program? public class Receipt { public static void main(string[] args) { /* Calculate total owed, assuming 8% tax / 15% tip */ ("Subtotal:"); (38 + 40 + 30); ("Tax:"); ((38 + 40 + 30) *.08); ("Tip:"); ((38 + 40 + 30) *.15); ("Total:"); (38 + 40 + 30 + (38 + 40 + 30) *.08 + (38 + 40 + 30) *.15); } } (38 + 40 + 30) is repeated So many println statements

Variables variable: A piece of the computer's memory that is given a name and type, and can store a value. Like preset stations on a car stereo, or cell phone speed dial: Declaration Variable declaration - Sets aside memory for storing a value. Variables must be declared before they can be used. Syntax: DataType VariableName; The variable'sname is an identifier. int x; double mygpa; x mygpa

Assignment Assignment - Stores a value into a variable. The value can be an expression; the variable stores its result. Syntax: VariableName = expression; int x; x = 3; double mygpa; mygpa = 1.0 + 2.25; x 3 mygpa 3.25 Using Variables Once given a value, a variable can be used in expressions: int x; x = 3; ("x is " + x); // x is 3 (5 * x - 1); // 5 * 3-1 You can assign a value more than once: int x; x = 3; x 3 (x + " here"); // 3 here x = 4 + 7; x 11 ("now x is " + x); // now x is 11

Declaration/Initialization A variable can be declared/initialized in one statement. Syntax: DataType VariableName = value; double mygpa = 3.95; mygpa 3.95 int x = (11 % 3) + 12; x 14 Assignment and Algebra Assignment uses =, but it is not an algebraic equation. = means, "store the value at right in variable at left" The right side expression is evaluated first, and then its result is stored in the variable at left. What happens here? int x = 3; x 3 x = x + 2; //??? x 5

Assignment and Types An int value can be stored in a double variable. The value is converted into the equivalent real number. double mygpa = 4; mygpa 4.0 double avg = 11 / 2; avg 5.0 Why does avg store 5.0 and not 5.5? Compiler Errors A variable can't be used until it is assigned a value. int x; (x); // ERROR: x has no value You may not declare the same variable twice. int x; int x; // ERROR: x already exists int x = 3; int x = 5; // ERROR: x already exists How can this code be fixed?

Printing A Variable's Value Use + to print a string and a variable's value on one line. double grade = (95.1 + 71.9 + 82.6) / 3.0; ("Your grade was " + grade); int students = 11 + 17 + 4 + 19 + 14; ("There are " + students + " students in the course."); Output: Your grade was 83.2 There are 65 students in the course. Receipt Question Improve the receipt program using variables. public class Receipt { public static void main(string[] args) { // Calculate total owed, // assuming 8% tax / 15% tip ("Subtotal:"); (38 + 40 + 30); ("Tax:"); ((38 + 40 + 30) *.08); ("Tip:"); ((38 + 40 + 30) *.15);

} ("Total:"); (38 + 40 + 30 + (38 + 40 + 30) *.15 + (38 + 40 + 30) *.08); } Receipt Answer public class Receipt { public static void main(string[] args) { // Calculate total owed, // assuming 8% tax / 15% tip int subtotal = 38 + 40 + 30; double tax = subtotal *.08; double tip = subtotal *.15; double total = subtotal + tax + tip; } } ("Subtotal: " + subtotal); ("Tax: " + tax); ("Tip: " + tip); ("Total: " + total);

Finding the Average Let s write a program that will find the average any 3 numbers we try: We now need to: 1. Find our three values 2. Add the values 3. Divide the sum by 3 4. Print the result Writing Average3b This first step becomes: 1.1 Find the first value 1.2 Find the second value 1.3 Find the third value 2. Add the values 3. Divide the sum by 3 4. Print the result

Writing Avg3 (continued) Since we want the computer to print out some kind of prompt, the first step becomes: 1.1.1 Prompt the user for the first value 1.1.2 Read in the first value 1.2.1 Prompt the user for the second value 1.2.2 Read in the second value 1.3.1 Prompt the user for the third value 1.3.2 Read in the third value 2. Add the values 3. Divide the sum by 3 4. Print the result Writing Avg3 (continued) We can prompt the user with: 1.1.1 ("Enter the first value?"); 1.1.2 Read in the first value 1.2.1 ("Enter the second value?"); 1.2.2 Read in the second value 1.3.1 ("Enter the third value?"); 1.3.2 Read in the third value 2.Add the values 3. Divide the sum by 3 4. Print the result

The Scanner Class Most programs will need some form of input. At the beginning, all of our input will come from the keyboard. To read in a value, we need to use an object belonging to a class called Scanner: Scanner keyb = new Scanner(System.in); Reading from the keyboard Once we declare keyb as Scanner, we can read integer values by writing: variable= keyb.nextint();

Writing the input statements in Average3b We can read in a value by writing: ("What is the first value\t?"); int value1 = keyb.nextint(); ("What is the second value\t?"); int value2 = keyb.nextint(); ("What is the third value\t?"); int value3 = keyb.nextint(); 2. Add the values 3. Divide the sum by 3 4. Print the result Writing the assignments statements in Average3b ("What is the first value\t?"); int value1 = keyb.nextint(); ("What is the second value\t?"); int value2 = keyb.nextint(); ("What is the third value\t?"); int value3 = keyb.nextint(); sum = value1 + value2 + value3; 3. Divide the sum by 3 4. Print the result Adding up the three values

Writing the assignments statements in Average3b ("What is the first value\t?"); int value1 = keyb.nextint(); ("What is the second value\t?"); int value2 = keyb.nextint(); ("What is the third value\t?"); int value3 = keyb.nextint(); sum = value1 + value2 + value3; average = sum / 3; 4. Print the result Calculating the average Writing the output statement in Average3b ("What is the first value\t?"); int value1 = keyb.nextint(); ("What is the second value\t?"); int value2 = keyb.nextint(); ("What is the third value\t?"); int value3 = keyb.nextint(); sum = value1 + value2 + value3; average = sum / 3; ("The average is " + average);

import java.util.scanner; public class Average3b { public static void main(string[] args) { int sum, average; Scanner keyb = new Scanner(System.in); ("What is the first value\t?"); int value1 = keyb.nextint(); ("What is the second value\t?"); int value2 = keyb.nextint(); ("What is the third value\t?"); int value3 = keyb.nextint(); } } sum = value1 + value2 + value3; average = sum / 3; ("The average is " + average);

Another example calculating a payroll We are going to write a program which calculates the gross pay for someone earning an hourly wage. We need two pieces of information: the hourly rate of pay the number of hours worked. We are expected to produce one output: the gross pay, which we can find by calculating: Gross pay = Rate of pay * Hours Worked Our Design for payroll 1. Get the inputs 2. Calculate the gross pay 3. Print the gross pay We can substitute: 1.1 Get the rate 1.2 Get the hours

Developing The Payroll Program We can substitute 1.1 Get the rate 1.2 Get the hours 1.1.1 Prompt the user for the rate 1.1.2 Read the rate 1.2.1 Prompt the user for the hours 1.2.2 Read the hours 2. Calculate the gross pay 3. Print the gross pay Coding the payroll program Before we code the payroll program, we recognize that the values (rate, hours and gross) may not necessarily be integers. We will declare these to be double, which means that they can have (but do not have to have) fractional parts. In Java, we usually declare our variables where they first appear in the program.

Developing The Payroll Program (continued) 1.1.1 Prompt the user for the rate 1.1.2 Read the rate 1.2.1 Prompt the user for the hours 1.2.2 Read the hours 2. Calculate the gross pay 3. Print the gross pay ("What is your hourly pay rate?"); double rate = keyb.nextdouble(); Developing The Payroll Program (continued) ("What is your hourly pay rate?"); double rate = keyb.nextdouble(); 1.2.1 Prompt the user for the hours 1.2.2 Read the hours 2. Calculate the gross pay 3. Print the gross pay ("How many hours did you work?"); double hours = keyb.nextdouble();

Developing The Payroll Program (continued) ("What is your hourly pay rate?"); double rate = keyb.nextdouble(); ("How many hours did you work?"); double hours = keyb.nextdouble(); 2. Calculate the gross pay 3. Print the gross pay double gross = rate * hours; Developing The Payroll Program (continued) ("What is your hourly pay rate?"); double rate = keyb.nextdouble(); ("How many hours did you work?"); double hours = keyb.nextdouble(); double gross = rate * hours; 3. Print the gross pay ("Your gross pay is $" + gross);

import java.util.scanner; public class Payroll { // This program calculates the gross pay for an // hourly worker // Inputs - hourly rate and hours worked // Output - Gross pay public static void main(string[] args) { Scanner keyb = new Scanner(System.in); // Get the hourly rate ("What is your hourly pay rate?"); double rate = keyb.nextdouble(); // Get the hours worked ("How many hours did you work?"); double hours = keyb.nextdouble(); } } // Calculate and display the gross pay double gross = rate * hours; ("Your gross pay is $" + gross);

Character Data All of our programs so far have used variables to store numbers, not words. We can store single characters by writing: char x, y; x and y can hold one and only one character For now, we use character data for input and output only. Character Strings We are usually interested in manipulating more than one character at a time. We can store more than one character by writing: String s = new String(); If we want s can hold to have some initial value, we can write: String s = new String("Initial value"); For now, we use character data for input and output and concatenation only.

A program that uses a character variable import java.util.scanner; public class Polite { // A very polite program that greets you by name public static void main(string[] args) { String name = new String(); Scanner keyb = new Scanner(System.in); // Ask the user his/her name ("What is your name?"); name = keyb.next(); // Greet the user ("Glad to meet you, " + name); } } Using Stepwise Refinement to Design a Program You should noticed that when we write a program, we start by describing the steps that our program must perform and we subsequently refine this into a long series of more detailed steps until we are writing individual steps. This is called stepwise refinement. Stepwise refinement is one of the most basic methods for developing a program.

Example A program to convert pounds to kilograms Our program will convert a weight expressed in pounds into kilograms. Our input is the weight in pounds. Our output is the weight in kilograms We also know that Kilograms = Pounds / 2.2 Pounds to Kilograms Program (continued) Our program must: 1. Get the weight in pounds 2. Calculate the weight in kilograms 3. Print the weight in kilograms

Pounds to Kilograms Program (continued) Our program must: 1. Get the weight in pounds 2. Calculate the weight in kilograms 3. Print the weight in kilograms 1.1 Prompt the user for the weight in pounds 1.2 Read the pounds Pounds to Kilograms Program (continued) Our program must: 1.1 Prompt the user for the weight in pounds 1.2 Read the pounds 2. Calculate the weight in kilograms 3. Print the weight in kilograms ("What is the weight in pounds?"); double lbs = keyb.nextint();

Pounds to Kilograms Program (continued) ("What is the weight in pounds?"); double lbs = keyb.nextint(); 2. Calculate the weight in kilograms 3. Print the weight in kilograms double kg = lbs / 2.2; Pounds to Kilograms Program (continued) ("What is the weight in pounds?"); double lbs = keyb.nextint(); double kg = lbs / 2.2; 3. Print the weight in kilograms ("The weight is " + kg + " kilograms");

import java.util.scanner; public class ConvertPounds { // Convert pounds to kilograms // Input - weight in pounds // Output - weight in kilograms public static void main(string[] args) { Scanner keyb = new Scanner(System.in); // Get the weight in pounds ("What is the weight in pounds?"); double lbs = keyb.nextint(); } } // Calculate and display the weight in // kilograms double kg = lbs / 2.2; ("The weight is " + kg + " kilograms"); Another Example The Area of A Rectangle Our program will calculate the area of a rectangle. Our input is the length and width. Our output is the area. We also know that Area = Length * Width

Our Program s Steps 1. Find the length and width 2. Calculate the area 3. Print the area Our Program s Steps (continued) 1. Find the length and width 2. Calculate the area 3. Print the area 1.1 Find the length 1.2 Find the width

Our Program s Steps (continued) 1.1 Find the length 1.2 Find the width 2. Calculate the area 3. Print the area 1.1.1 Prompt the user for the length 1.1.2 Read the length 1.2.1 Prompt the user for the width 1.1.2 Read the width Our Program s Steps (continued) 1.1.1 Prompt the user for the length 1.1.2 Read the length 1.2.1 Prompt the user for the width 1.1.2 Read the width 2. Calculate the area 3. Print the area ("Enter the length?"); double length = keyb.nextdouble(); ("Enter the width?"); double width = keyb.nextdouble();

Our Program s Steps (continued) ("Enter the length?"); double length = keyb.nextdouble(); ("Enter the width?"); double width = keyb.nextdouble(); 2. Calculate the area 3. Print the area double area = length * width; Our Program s Steps (continued) ("Enter the length?"); double length = keyb.nextdouble(); ("Enter the width?"); double width = keyb.nextdouble(); double area = length * width; 3. Print the area ("The area is " + area);

import java.util.scanner; public class CalculateArea { // Calculates the area of a rectangle // Inputs - The length and width of the rectangle // Output - The area of the rectangle public static void main(string[] args) { Scanner keyb = new Scanner(System.in); // Print an explanatory message for the user ("Given the width and length of a rectangle"); ("this program calculates its area." ); // Get the inputs ("Enter the length?"); double length = keyb.nextdouble(); ("Enter the width?"); double width = keyb.nextdouble(); } } // Calculate and display the area double area = length * width; ("The area is " + area);