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

Similar documents
Programming Logic and Design Sixth Edition Chapter 2 Working with Data, Creating Modules, and Designing High-Quality Programs

A Beginner s Guide to Programming Logic, Introductory. Chapter 2 Working with Data, Creating Modules, and Designing High-Quality Programs

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

Test Bank for An Object Oriented Approach to Programming Logic and Design 4th Edition by Joyce Farrell

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

Chapter 4: Writing and Designing a Complete Program. Programming Logic and Design, Third Edition Introductory

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

Full file at

SKILL AREA 306: DEVELOP AND IMPLEMENT COMPUTER PROGRAMS

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

Microsoft Visual Basic 2005: Reloaded

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Basics of Java Programming

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

I. Variables and Data Type week 3

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

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d.

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

Programming Language 2 (PL2)

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

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

4. The is a diagram that graphically depicts the steps that take place in a program. a. Program b. Flowchart c. Algorithm d. Code e.

CS112 Lecture: Working with Numbers

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Chapter 2 Basic Elements of C++

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

The C++ Language. Arizona State University 1

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

Program Planning, Data Comparisons, Strings

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

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

Lecture 3 Tao Wang 1

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Microsoft Visual Basic 2015: Reloaded

Arithmetic Expressions in C

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

CMPT 125: Lecture 3 Data and Expressions

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

Skill Area 336 Explain Essential Programming Concept. Programming Language 2 (PL2)

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

BITG 1233: Introduction to C++

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

BASIC ELEMENTS OF A COMPUTER PROGRAM

Arithmetic Operations

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto

VARIABLES & ASSIGNMENTS

Section we will not cover section 2.11 feel free to read it on your own

Chapter 2 Working with Data Types and Operators

Chapter 3 - Simple JavaScript - Programming Basics. Lesson 1 - JavaScript: What is it and what does it look like?

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Pseudo Code and Flow Charts. Chapter 1 Lesson 2

The Java Language Rules And Tools 3

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Course Outline. Introduction to java

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Programming for Engineers Introduction to C

LECTURE 02 INTRODUCTION TO C++

DEPARTMENT OF MATHS, MJ COLLEGE

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

C: How to Program. Week /Mar/05

Variables, expressions and statements

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

Angela Z: A Language that facilitate the Matrix wise operations Language Reference Manual

1 Lexical Considerations

Section 1. The essence of COBOL programming. Mike Murach & Associates

2. Numbers In, Numbers Out

Programming Lecture 3

CSCE 120: Learning To Code

Introduction to TURING

Full file at

Chapter 1: An Overview of Computers and Logic

Fundamentals of Programming Session 4

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Data and Expressions

Introduction to Java Applications

III. Check if the divisors add up to the number. Now we may consider each of these tasks separately, assuming the others will be taken care of

Chapter 2 - Introduction to C Programming

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Unit 3, Lesson 2 Data Types, Arithmetic,Variables, Input, Constants, & Library Functions. Mr. Dave Clausen La Cañada High School

Introduction to Python Programming

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Visual C# Instructor s Manual Table of Contents

Variable A variable is a value that can change during the execution of a program.

CEN 414 Java Programming

Lecture 2 Tao Wang 1

Basic Operations jgrasp debugger Writing Programs & Checkstyle

CSc Introduction to Computing

Datatypes, Variables, and Operations

L-System Fractal Generator: Language Reference Manual

Transcription:

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

Objectives In this chapter, you will learn about: Declaring and using variables and constants Assigning values to variables [assignment statement] Initializing a variable Performing arithmetic operations The advantages of modularization Hierarchy charts [aka structure charts] Features of good program design Programming Logic and Design, 2

Declaring and Using Variables Data items and Constants All the text, numbers, and other information that are processed by a computer Stored in variables in memory Different forms Variables Literals ( unnamed constants ) Named constants ( cannot be modified ) 3

Working with Variables A variable is a named location in RAM where data is stored for use by a running program. Contents can vary or differ over time Declaration Statement that provides a data type and an identifier for a variable. Most programming languages require you to declare a variable before you try to use it in your program. Identifier Something you provide a name for: variable Assignment named constant module name 4 A variable gets a value as the result of an assignment statement

Working with Variables (continued) A later example will show declarations What are the names of the variables? Figure 2-1 Flowchart and pseudocode for the number-doubling program 5

Working with Variables (continued) Data type Classification that describes: What values can be held by the item How the item is stored in computer memory What operations can be performed on the data item Initializing a variable Providing a starting value for any variable Can be done as part of the declaration e.g. num count = 0 Variable s value before initialization depends on the computer language used. garbage zero (0) or Null Type Safety a feature of most languages that prevents assigning values of an incorrect data type 6

Mainline Logic Top-level flowchart for Java Start Declare global variables here main( ) Stop Variables can be global or local Figure 2-2 Flowchart and pseudocode of number-doubling program with variable declarations 7

Naming Variables Programmers should choose reasonable and descriptive names for variables Rules for creating identifiers Most languages allow letters and digits but you cannot start with a digit Some languages allow underscores ( _ ) You may not have spaces in a variable name in any language Some languages allow dollar signs ( $ ) or other special characters [Java allows a $] Different limits on the length of variable names 8

Naming Variables (continued) Camel casing Variable names such as hourlywage have a hump in the middle Pascal Casing first letter in first word of identifier is capitalized, for example: NumberDoubler Using _ hourly_wage, number_doubler, total_cost Variable names used throughout book Must be one word (no spaces) Should have a name which conveys meaning! 9

Understanding Literals and their Data Types literal - an unnamed constant value [magic number] Numeric: Specific numeric value Examples: 43-3 1415 2.35486 e8.6 5. 0 String: String of characters enclosed within quotation marks Examples: "Hello World", "Sum is ", "" (empty string) Character: A single character ( usually enclosed in single quotes ) Examples: A, c, \n [newline character in Java] 10

Understanding the Data Types of Variables Numeric variable Usually signed (may be negative or positive) Integer ( whole numbers only ) Real ( may contain decimal digits ) String variable Can hold any sequence of 0 or more characters Letters of the alphabet (upper- and lower-case), digits 0-9 Special characters such as punctuation marks Character variable Can hold a single character To assign a value to a variable, it must be of the same type ( numeric, string, character, etc. ) [Type Safety] 11

Declaring Named Constants Named constant Similar to a variable Can be assigned a value only once Assign a useful name to a value that will never be changed during a program s execution By convention, a named constant identifier uses all capital letters Magic number A literal Purpose is not immediately apparent Avoid this! Use a named constant instead 12

Assigning Values to Variables Assignment statement [set] myanswer = mynumber * 2 [ flowchart or pseudocode ] Assignment operator Valid Usually an Equal sign ( = ). Some languages use ( := ) Association is from right to left a = b = c = 0; set somenumber = 2 [ Note: Basic allows use of let ] somenumber = 2 set somenumber = someothernumber Not valid somenumber = someothernumber set 2 + 4 = somenumber [ variable must be on left side of assignment operator ] 13

Performing Arithmetic Operations Standard arithmetic operators: + plus sign addition minus sign subtraction * asterisk multiplication / slash division % percent sign remainder of integer division aka modulus The type of division may be floating-point or integer depending on the operands: Integer Division: 3 / 5 0 5 / 3 1 Floating-point Division: 3.0 / 5.6 5 / 3.0 1.6666667 7 / 5 1 (quotient) 7 % 5 2 (remainder) 3 % 5 3 14

Performing Arithmetic Operations Rules of precedence Also called the order of operations Dictates the order in which operations in the same statement are carried out 1. Expressions within parentheses are evaluated first 2. Multiplication and division are evaluated next [precedence] From left to right [associativity] 3. Addition and subtraction are evaluated next [precedence] From left to right [associativity] 15

Performing Arithmetic Operations (continued) Associativity Operations with the same precedence are usually evaluated from left to right. x = 5 * (7 / 3) + 6 2 + 3 * 5 To evaluate this, you use the the rules of precedence and associativity. 16

Performing Arithmetic Operations (continued) Table 2-1 Precedence and associativity of five common operators 17

Understanding the Advantages of Modularization Module Subunit of a programming problem Also called subroutine, procedure, function, or method Modularization Breaking down a large program into modules [functional decomposition] Reasons: Divide and conquer strategy, aka stepwise refinement Abstraction ( focus on mainline logic first ) Allows multiple programmers to work on a problem Reuse your work more easily 18

Modularization Provides Abstraction Abstraction Determine what tasks are to be performed this will be the basis for your modules Determine the sequence the modules should be performed in this will determine the sequence of your mainline logic Develop mainline program logic [ method main() ] Develop the logic of the modules ( statements that complete some task ) Create an algorithm (logic for a task) Implement the algorithm Newer high-level programming languages Use English-like vocabulary One broad statement corresponds to dozens of machine language instructions Modules provide the primary way to achieve abstraction 19

Modularization Allows Multiple Programmers to Work on a Problem More easily divide the task among various people Rarely does a single programmer write a commercial program Professional software developers can write new programs quickly by dividing large programs into modules Assign each module to an individual programmer or team 20

Modularization Allows You to Reusability Reuse Your Work Feature of modular programs Allows individual modules to be used in a variety of applications Many real-world examples of reusability Reliability Feature of programs that assures you a module has been tested and proven to function correctly 21

Modularizing a Program Main program Basic steps (mainline logic) of the program Java method main() Parts of a module Header <return type> <module name> <module parameter list> Body statements return statement Naming a module A module name is an identifier Similar to naming a variable Module names are usually followed by a set of parentheses 22

Modularizing a Program (continued) When a main program wants to use a module it calls the module [ more formally, it invokes it ] Flowchart Symbol used to call a module is a rectangle with a line across the top or along the sides Place the name of the module you are calling inside the rectangle Draw each module separately with its own terminal symbols ( module name / return ) 23

Figure 2-3 Program that produces a bill using only main program logic 24

Modularizing a Program (continued) Determine when to break down any particular program into modules Does not depend on a fixed set of rules Programmers do follow some guidelines Part of the process of abstraction Statements should contribute to the same job (task) Functional cohesion 25

Declaring Variables and Constants within Modules Place any statements within modules input, processing, and output statements variable and constant declarations Variables and constants declared in a module are usable only within that module [ local variables ] Visibility Scope Lifetime 26

What are the variables? What are the named constants? Figure 2-5 The billing program with a module and constants 27

Declaring Variables and Constants within Modules (continued) Global variables and named constants Declared at the program level Not declared inside of a module This is the problem with declarations in the Mainline Logic Visible to and usable in all the modules called by the program Local variables and named constants Declared at the module level Visible only within the module 28

Understanding the Most Common Configuration for Mainline Logic Mainline logic of almost every procedural computer program follows a general structure Declaration of global variables and constants Declaration of modules Housekeeping tasks [ initialization ] Detail loop tasks [ processing loop ] End-of-job tasks [ finalization ] Most newer languages require you to create a module for the mainline logic with a specific name, such as main. [Java main()] Some languages do not have a named mainline logic module. 29

Understanding the Most Common Configuration for Mainline Logic (continued) Here is another flowchart symbol used to represent a module. This is the symbol you use in Visio. Figure 2-6 Flowchart and pseudocode of mainline logic for a typical procedural program 30

Creating Hierarchy Charts Hierarchy chart Shows the overall picture of how modules are related to one another Tells you: which modules exist within a program which modules call other modules Specific module may be called from several locations within a program A useful abstraction planning tool Planning tool Develop the overall relationship of program modules before you write them Documentation tool 31

Example Hierarchy Chart module used in multiple locations 32

Features of Good Program Design Use program comments where appropriate Identifiers should be well-chosen Strive to design clear statements within your programs and modules Write clear prompts and echo input Continue to maintain good programming habits as you develop your programming skills 33

Using Program Comments Program comments // /* */ -- Written explanations Not part of the program logic Serve as documentation for readers of the program Syntax used differs among programming languages Flowchart Use an annotation symbol to hold information that expands on what is stored within another flowchart symbol 34

Using Program Comments (continued) Figure 2-12 Pseudocode that declares some variables and includes comments 35

An assumption in this book is that variables declared in the "mainline" module will be global variables, accessible by all other modules. This is NOT the case in most programming languages, such as Java, C++, C#, and Visual Basic. Figure 2-13 Flowchart that includes some annotation symbols Sixth Edition 36

Choosing Identifiers General guidelines: Give a variable or a named constant a name that is a noun quantity, cost, count, rate Give a module an identifier that is a verb getrecord, processrecord, printdetailline Use meaningful names Self-documenting Use pronounceable names Be judicious in your use of abbreviations Avoid digits in a name 37

Choosing Identifiers (continued) General guidelines (continued) Use the convention in your language to name identifiers with names composed of multiple words. printdetailline Print_Detail_Line Name named constants using all uppercase letters separated by underscores ( _ ) Organizations sometimes enforce different rules for programmers to follow when naming variables Hungarian notation strname, intcount, dblrate 38

Avoiding Confusing Line Breaks Most modern programming languages are free-form Take care to make sure your meaning is clear Generally, you should not combine multiple statements on one line 39

Designing Clear Statements Use temporary variables and write multiple statements rather than one long complex statement Figure 2-14 Two ways of achieving the same salespersoncommission result 40

Using Temporary Variables to Clarify Long Statements Temporary variable Work variable Not used for input or output Working variable that you use during a program s execution Consider using a series of temporary variables to hold intermediate results 41

Using Temporary Variables to Clarify Long Statements (continued) Figure 2-14 Two ways of achieving the same salespersoncommission result 42

Writing Clear Prompts and Echoing Input Prompt Message displayed on a monitor to ask the user for a response Used both in command-line and GUI interactive programs Echo input Repeat input back to a user either in a subsequent prompt or in output. 43

Writing Clear Prompts and Echoing Input (continued) Figure 2-15 Beginning of a program that accepts a name and balance as input 44

Figure 2-16 Beginning of a program that accepts a name and balance as input and uses a separate prompt for each item Sixth Edition 45

Maintaining Good Programming Habits Every program you write will be better if you: PLAN BEFORE YOU CODE!!! Maintain the habit of first drawing flowcharts or writing pseudocode Desk-check your program logic on paper Think carefully about the variable and module names you use Design your program statements to be easy to read and use 46

Summary Variables Named memory locations with variable contents Equal sign is the assignment operator Break down programming problems into reasonable units called modules Include a header, a body, and a return statement Mainline logic of almost every procedural computer program can follow a general structure As your programs become more complicated: Need for good planning and design increases 47