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

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

Chapter 2: Data and Expressions

Overview (4) CPE 101 mod/reusing slides from a UW course. Assignment Statement: Review. Why Study Expressions? D-1

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

CSCE 120: Learning To Code

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.

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

Full file at

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

Basics of Java Programming

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

Basic Operations jgrasp debugger Writing Programs & Checkstyle

BASIC ELEMENTS OF A COMPUTER PROGRAM

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

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

Chapter 17. Fundamental Concepts Expressed in JavaScript

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

SKILL AREA 306: DEVELOP AND IMPLEMENT COMPUTER PROGRAMS

Values, Variables, Types & Arithmetic Expressions. Agenda

Outline. Data and Operations. Data Types. Integral Types

CEN 414 Java Programming

Arithmetic Expressions in C

Visual C# Instructor s Manual Table of Contents

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

Chapter Two PROGRAMMING WITH NUMBERS AND STRINGS

Chapter 2: Data and Expressions

Programming Language 2 (PL2)

CSI Lab 02. Tuesday, January 21st

Part 1 Arithmetic Operator Precedence

Full file at

Repetition Structures

CS112 Lecture: Working with Numbers

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

Chapter 2: Basic Elements of C++

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2

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

Chapter 2 Basic Elements of C++

Annotation Annotation or block comments Provide high-level description and documentation of section of code More detail than simple comments

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

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

Reserved Words and Identifiers

VBScript: Math Functions

UNIT- 3 Introduction to C++

Microsoft Visual Basic 2015: Reloaded

C++ Programming Language Lecture 2 Problem Analysis and Solution Representation

Part 1 Simple Arithmetic

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

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

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

Chapter 2: Data and Expressions

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

The C++ Language. Arizona State University 1

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

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

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Microsoft Visual Basic 2005: Reloaded

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

Computer Components. Software{ User Programs. Operating System. Hardware

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

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

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

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

VARIABLES & ASSIGNMENTS

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

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

Constructing Algorithms and Pseudocoding This document was originally developed by Professor John P. Russo

Motivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution

Lesson 3: Arithmetic & Casting. Pic 10A Ricardo Salazar

CHAPTER 3: CORE PROGRAMMING ELEMENTS

Chapter 2 Elementary Programming. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

LESSON 2 VARIABLES, OPERATORS, EXPRESSIONS, AND USER INPUT

PROGRAM READABILITY. A program's readability readability, which is a measure of how

Fundamental of Programming (C)

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

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

CS 112: Intro to Comp Prog

CS110: PROGRAMMING LANGUAGE I

Outline. Program development cycle. Algorithms development and representation. Examples.

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

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

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

Getting Started With Python Programming

WHOLE NUMBER AND DECIMAL OPERATIONS

Arithmetic Expressions Lesson #1 Outline

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

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

Arithmetic Operations

Objectives. In this chapter, you will:

Chapter 2 Working with Data Types and Operators

These are reserved words of the C language. For example int, float, if, else, for, while etc.

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

Arrays. Array Basics. Chapter 8 Spring 2017, CSUS. Chapter 8.1

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

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 Elementary Programming

Java Programming Unit 3: Variables and Arithmetic Operations

Transcription:

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

Algorithms They are the logic on how to do something how to compute the value of Pi how to delete a file how to load a webpage Examples: tying your shoes driving to Sac State making a peanut butter and jelly sandwich 3 Designing a Program 1. Design flowcharts and pseudocode help with this process 2. Write the code 3. Cleared code of syntax errors 4. Checked for logic errors. 5. If logic errors exist, debug the program 1-4 2

Two Steps of Designing a Program 1. Understand the tasks that the program is to perform 2. Determine the steps require for the task create an algorithm use flowcharts and/or pseudocode to solve 1-5 Procedural Programming Traditional approach to programming easy for humans to conceptualize it is based on how we do things Programs contain as a sequence of steps steps run in order from first to last repetition is performed with "looping" 6 3

Flow Charts Chapter 2.1 Flow Chart Overview Graphical representation each statement is a shape useful for conceptualizing an algorithm easy to understand and visualize Used everywhere programmers used to create charts first used extensively in business Worldwide 8 4

Start / End Indicates the start and end of an algorithm Represented by a rectangle with rounded sides There are typically two: one to start the flowchart one to end the flowchart 9 Input / Output Indicates data being: inputted into the computer outputted to the user Represented by a parallelogram Flowcharts can have many 10 5

Processes Indicates data: being processed also called "calculations" Represented by a rectangle This tends to be the most common symbol 11 Decisions Indicates a logical branch algorithm executes instructions if some criteria is met can contain a positive and negative branch Represented by a diamond 12 6

Input / Output Process Data Input / Output Pseudocode Chapter 2.1 7

What is Pseudocode? Description of an algorithm's logic not as formalized as English it can "look" like code, but this varies It is often useful lets you write down "something" to conceptualize the algorithm not worry about the implementation issues 15 Area of a Circle Pseudocode My area of a circle program Input radius Set Area = (pi x radius 2 ) Display "The area is", area 16 8

Flowchart vs. Pseudocode Display "What is the bill?" Input bill Set tip = bill * 0.15 Display "The tip is $", tip 17 Pseudocode in the Book The textbook, we are using in class, makes use of both flowcharts and pseudocode to describe program logic The pseudocode, throughout the book, is consistent - the same words and structure is used in every example 18 9

Book Pseudocode: Display Display is the "keyword" to show output to the screen When you see a line that starts with "display", you will known information will shown 19 Book Pseudocode: Display In computer science, a series of characters is called a string Display often uses string literals a sequence of characters delimited by double quotes 20 10

Examples of String Literals "Sac State" "Hornet" "Computer Science 10" "1850" "Tappa Kegga Bru" "Cuppa Kappa Chino" 21 Output Example In the following example, a string literal is output to the screen The book's pseudocode uses Display Display "Hello!" 22 11

Output Example When the program gets to the display statement, it will output the string literal Hello! 23 Output Example 2 You can output numbers and strings The following outputs the name and founding year of Sac State Display "Sacramento State" Display 1947 24 12

Output Example We will get into what the difference between the two pieces of data later Sacramento State 1947 25 Book Pseudocode: Input Input is the keyword to read values from the user These values need to be put somewhere we will put them in memory locations called variables 26 13

Output, Input and Variables Chapter 2.2 Output, Input, and Variables Input refers to data that is receives from the user allows the program to solve different sets of problems without change Output refers to data that is displayed to the user this includes prompts and the results of calculations 28 14

Output, Input, and Variables Variables storage locations in memory for data used to: perform calculations, store results, hold messages, etc they are vital to understand 29 Variable Declarations & Data Types Chapter 2.4 15

Data Types A data type defines the type of data you intend to store in a variable The names of data types and which ones are supported varies greatly between languages 31 Common Data Types Integer stores only whole numbers Real stores whole or decimal numbers String any series of characters 32 16

Variable Declarations & Data Types A variable declaration tells the programming language the name of a variable you want and what it will store Found in practically all programming languages 33 Explicit Variable Declaration Explicit variable declaration require the program to specify the name and type of each variable Prevents typo bugs (which are hard to find and fix) 34 17

Explicit Variable Declaration Commonly used in high-level & professional languages Examples: Java Visual Basic.NET C# C++ 35 Implicit Variable Declaration Implicit variable declaration creates a variable the moment it is first "seen" Typically used by scripting languages but few major languages 36 18

Implicit Variable Declaration Tends to be problematic since a simple typo will create new variables For example: the programmer uses value and valu (no e) it will create two variables even though the user meant value for both These can be hard to find and fix 37 Declaring Variables When you declare a variable you allocate space for it in memory and give this memory a unique name This unique name is called an identifier every programming language has different rules for how the identifier should look fortunately, the main rules are pretty consistent 38 19

Typical Naming Rules 1. Letter followed by zero or more letters or numbers 2. One word - no spaces 3. Generally, punctuation characters are avoided some languages allow underscores, dashes, etc 39 Multiple Word Identifiers Often variable names are more than one word Goal of the name is to make it "readable" not short! There are a couple of ways programmers format the name 40 20

Proper Case In proper case (aka pascal case), the first letter of each word is capitalized Standard convention for Visual Basic.NET and C# Examples: AverageScore TaxRate 41 Camel Case In camel case, the first letter of the first word is in lower case and the rest start with a capital Standard convention for C, C++, and Java Examples: averagescore taxrate 42 21

Declaration Example The follow declares a variable called age that can store integers The second variable, price, can store reals Declare Integer age Declare Real price 43 What Happens? Memory: year? Declare Integer year; 44 22

What Happens? Memory pi? Declare Real pi; 45 Variable Initialization When a variable is first declared and created what value does it have? In many languages, the initial value is unknown So, to avoid possible errors, variables should be initialized to 0 (or some other value) before it is used later 46 23

Variable Assignment A variable s value can be set through user input. It can also be set through an assignment statement 47 Book Pseudocode: Set The Set keyword designates an assignment statement It allows a value to be stored in a variable without reading from the user It is also used to store the result of a calculation 48 24

Declaration Example The first line creates the variable The second line, sets it to 18 Declare Integer age Set age = 18 49 What Happens? Memory: Declare Integer year Set year = 1947 Display year 50 25

What Happens? Memory: year? Declare Integer year Set year = 1947 Display year 51 What Happens? Memory: year 1947? Declare Integer year Set year = 1947 Display year 52 26

Flowchart for Previous Slide 53 Another Example Memory: Declare Integer score Set score = 98 Set score = 81 54 27

Another Example Memory: score? Declare Integer score Set score = 98 Set score = 81 55 Another Example Memory: score 98? Declare Integer score Set score = 98 Set score = 81 56 28

Another Example Memory: score 98 81 Declare Integer score Set score = 98 Set score = 81 57 Data Conversion Typecasting when one type of data is converted to another When the programming language converts the data implicitly, it is coerced When the programmer explicitly specifies how data will be converted, it is cast 58 29

Cast Example Memory: score? Declare Integer score Set score = 98.6 Display score 59 Cast Example Memory: score 98? Coerced to integer Declare Integer score Set score = 98.6 Display score 60 30

Declare & Initialize Many programming languages allow you to declare and initialize at the same time The book also uses this notation Declare Integer Age = 18 61 Assignment Example In the following example, the variable cash is set to the value 5.25 The number 5.25 is written explicitly in the program and is called a literal Set cash = 5.25 Display "I have ", cash, " dollars" 62 31

Assignment Example When the program gets to the display statement, it will use the current value of cash So, the variable can be used to output data I have 5.25 dollars 63 Assignment Example 2 Variables can be assigned more than once In this example, cash is set twice to different values Set cash = 5.25 Display "I have ", cash, " dollars" Set cash = 19.95 Display "Now I have ", cash, " dollars" 64 32

Assignment Example 2 Output The value of the variable will be printed using whatever value is currently has So, the program will print two different values I have 5.25 dollars Now I have 19.95 dollars 65 Variable Assignment & Calculations Chapter 2.3 33

Variable Assignment & Calculations The value assigned to a variable doesn't have to be literal (string, integer, etc..) Often it is the result of a mathematical expression 67 Expressions Expressions are mathematical formulas follows the format you know Operator Precedence order which operators are computed practically all languages have precedence levels 68 34

Arithmetic Operators Operator Name * Multiplication / Division + Addition - Subtraction (and unary minus) mod ^ Modulus (remainder) Exponent 69 Precedence (from first to last) Operator Name () Subexpression ^ Exponent - Unary minus * / mod Multiplication & Division + - Addition & Subtraction 70 35

Calculate Results Set sum = 11 * 2 + 8 * 4 7 Set sum = 22 + 8 * 4 7 Set sum = 22 + 32-7 Set sum = 54-7 Set sum = 47 71 Calculate 2 Results Set result = 7 + 3 ^ 2 * (4-1) Set result = 7 + 3 ^ 2 * 3 Set result = 7 + 9 * 3 Set result = 7 + 27 Set result = 34 72 36

Calculate Results With Variables Set x = 10 Set y = 2 Set value = x * 3 + -y Set value = x * 3 + -2 Set value = 30 + -2 Set value = 28 73 Named Constants Chapter 2.5 37

Named Constants A named constant is a name that represents a value that cannot be changed Think of it like a variable that is "written in stone" you can use it, but cannot change it 75 Named Constants Why use them? Makes programs more self explanatory If a change to the value occurs, it only has to be modified in one place 76 38

Named Constant Example The following declares a constant TAX_RATE Many languages like to type constants in all caps the book uses this approach Constant Real TAX_RATE = 0.07 77 Hand Tracing a Program Chapter 2.6 39

Hand Tracing a Program Hand tracing is a simple debugging process for locating hard to find errors in a program Involves creating a chart with a column for each variable, and a row for each line of code 79 Hand Tracing a Program You then pretend to be the computer (how fun!) Go line by line and update each variable as the program does This can help find bugs and help you understand the code 80 40

Hand Trace Example: Cube Pseudocode Side Volume Declare Integer Side?? Declare Integer Volume???? Set Side = 4 4? Set Volume = Side ^ 3 4 64 4 64 Display Volume 4 64 81 Hand Trace Example: Tax Pseudocode Price Tax Total Declare Real Price??? Declare Real Tax??? Declare Real Total?????? Set Price = 32.50 32.50?? Set Tax = Price * 0.08 32.50 2.60? Set Total = Price + Tax 32.50 2.60 35.10 32.50 2.60 35.10 Display Total 32.50 2.60 35.10 82 41

Documenting a Program Chapter 2.7 Documenting a Program Real-World programs can become large and complex As a result, efforts are needed keep them organized And, to make it easier for them to be understood and edited by others 84 42

External Documentation External documentation describes information that was written to benefit the user of the application It is designed to be understood by your typical user ideally being easy to understand by a novice So, this type of documentation is sometimes written by a technical writer 85 Internal Documentation Internal documentation is information left by the programmer for other programmers to read It is included with the program itself the end user will never read it or know it ever existed 86 43

Internal Documentation In computer science, we refer to this documentation as comments The comments depend on what the programmer is trying to tell the reader Vital to maintaining any complex program 87 Example Types of Comments Explanation of what a segment of code does Notes on future improvements Log changes made by a programmer what, when and why Bugs and other problems 88 44

Book Pseudocode: Comments The book denotes a comment by using two normal slashes Everything after the slashes is a comment and does not change the meaning of your program // This is a comment 89 Book Pseudocode: Comments In fact, comments never change your program they are passive But, programmers often "disable" code by "commenting it out" // Display "This is disabled" Display "This is not" 90 45

Commented Cube Example Declare real side Declare real volume //Read the side of a cube Input side //Width * length * depth //All three are equal on a cube Set volume = side ^ 3 91 92 46

Style Guide How to Format Your Code Style Guide Computer programs can become complex As a result, it is a good idea to follow a set of rules to make sure they are readable and easy to maintain 94 47

Variable Names Use descriptive names They should be long enough to describe the contents of the variable but keep them as short Using the correct naming convention & stick to it 95 Bad Variable Names The following variable names are far too long They are descriptive, yes, but take waaaaaay too much space Set taxrateinsacramentocounty = 0.08 Set taxonmybill = totalbillamount * taxrateinsacramentocounty 96 48

Better Variable Names Keep them short enough to not waste space But, still keep them descriptive Set taxrate = 0.08 Set tax = bill * taxrate 97 Comments are Your Friend Add comments to tell yourself (or a reader) what the program does It is also good to write down who edited the file and when Flowgorithm is pretty easy to understand, but many languages are not 98 49

Always Declare Variables First It is considered good style to put all your variable declarations at the beginning of the program Why? keeps them all in one place insures you declared the variable before you use it 99 Mixed-up Declarations The following mixes declares and assignment statements It is hard to read and easy to forget what you declared! Declare Real TaxRate Set taxrate = 0.08 Declare Real tax Set tax = bill * taxrate 100 50

Nice and Organized Notice that the code is easier to read As an added benefit: it is easy to we can check if the data types are consistent (e.g. all reals) Declare Real TaxRate Declare Real tax Set taxrate = 0.08 Set tax = bill * taxrate 101 51