0% found this document useful (0 votes)
8 views

Programming Chap 2

Uploaded by

osesayjr
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Programming Chap 2

Uploaded by

osesayjr
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 49

INPUT, PROCESSING, AND OUTPUT

•Designing a Program
•Output, Input, and Variables
•Variable, Assignment and Calculation
•Variable Declarations and Data Types
•Named Constants
•Hand Tracing a Program
•Documenting a Program
•Designing Your First Program
Designing a Program

Programs must be carefully designed before they are written.


During the design process, programmers use tools such as
pseudocode and flowcharts to create models of programs.

The process of designing a program can be summarized in the


following two steps:
1. Understand the task that the program is to perform.
2. Determine the steps that must be taken to perform the
task.
Understand the Task that the Program is to
Perform.
If you choose to become a professional software
developer, your customer will be anyone who asks you to
write programs as part of your job. As long as you are a
student, however, your customer is your instructor! In
every programming class that you will take, it’s practically
guaranteed that your instructor will assign programming
problems for you to complete. For your academic success,
make sure that you understand your instructor’s
requirements for those assignments and write your
programs accordingly.
Determine the Steps that must be taken to
Perform the Task.
Once you understand the task that the program will perform,
you begin by breaking down the task into a series of steps.

For example, suppose your little sister asks you how to boil
water. Assuming she is old enough to be trusted around the
stove, you might break down that task into a series of steps as
follows:
Pour the desired amount of water into a pot.
Put the pot on a stove burner.
Turn the burner to high.
Watch the water until you see large bubbles rapidly rising.
When this happens, the water is boiling.
This is an example of an algorithm, which is a set of well-
defined logical steps that must be taken to perform a task.
Example
Suppose you have been asked to write a program to
calculate and display the gross pay for an hourly paid
employee. Here are the steps that you would take:
•Get the number of hours worked.
•Get the hourly pay rate.
•Multiply the number of hours worked by the hourly pay
rate.
•Display the result of the calculation that was performed in
Step 3.
NOTE:
This algorithm isn’t ready to be executed on the computer.
The steps in this list have to be translated into code.
Programmers commonly use two tools to help them
accomplish this: pseudocode and flowcharts.
Pseudocode
The word pseudo means fake, so pseudocode is fake code.
It is an informal language that has no syntax rules, and is
not meant to be compiled or executed. Instead,
programmers use pseudocode to create models, or “mock-
ups” of programs.
Example of how you might write pseudocode for the pay
calculating program that we discussed in slide 5:

•Display "Enter the number of hours the employee worked."


•Input hours
•Display "Enter the employee's hourly pay rate."
•Input payRate
•Set grossPay = hours * payRate
•Display "The employee's gross pay is NLe", grossPay
Pseudocode (Continue)
Example 2:
Write a pseudocode statement that multiplies the variable
subtotal by 0.15 and assigns the result to the variable
totalfee

Set totalFee = subtotal * 0.15

Example 3:
Write a pseudocode statement that declares the variable
total so it can hold integers. Initialize the variable with the
value 0.

Declare Integer total = 0


Pseudocode (Continue)
Example 4:
A company has determined that its annual profit is typically
23 percent of totalsales. Design a program that asks the user
to enter the projected amount of totalsales, and then displays
the profit that will be made from that amount.
Hint: Use the value 0.23 to represent 23 percent.

Display "Enter the projected sales." // Get the sales amount.


Input salesTotal
Set profit = salesTotal * 0.23 // Calculate the projected profit.
// Display the projected profit.
Display "The projected profit is ", profit
Flowcharts
Flowcharting is another tool that programmers use to
design programs. A flowchart is a diagram that graphically
depicts the steps that take place in a program.

Note: There are three types of symbols in the flowchart:


ovals, parallelograms, and rectangles. The ovals, which
appear at the top and bottom of the flowchart, are called
terminal symbols. The Start terminal symbol marks the
program’s starting point and the End terminal symbol
marks the program’s ending point.

Flowchart for the pay calculating program


Flowcharts (Continue)
Output, Input, and Processing
Output is data that is generated and displayed by the
program. Input is data that the program receives. When a
program receives data, it stores it in variables, which are
named storage locations in memory.

Computer programs typically perform the following three-


step process:
•Input is received.
•Some process is performed on the input.
•Output is produced.
Output, Input, and Processing (Continue)
The input, processing, and output of the pay calculating
program.
Displaying Screen Output
Perhaps the most fundamental thing that you can do in a
program is to display a message on the computer screen. As
previously mentioned, all high-level languages provide a way
to display screen output. We use the word Display to write
pseudocode statements for displaying output on the screen.
Here is an example:
Display “Hello world”

The purpose of this statement is to display the message Hello


world on the screen. Notice that after the word Display, we
have written Hello world inside quotation marks. The
quotation marks are not to be displayed. They simply mark
the beginning and the end of the text that we wish to display.
Example. Write a pseudocode program that displays your
name and address on the computer screen and also draw the
flowchart.
Strings
Programs almost always work with data of some type.
Example, uses the following three pieces of data:
"Kate Austen"
"1234 Walnut Street"
"Asheville, NC 28899"
These pieces of data are sequences of characters. In
programming terms, a sequence of characters that is used
as data is called a string. When a string appears in the
actual code of a program, it is called a string literal. In
program code, or pseudocode, a string literal is usually
enclosed in quotation marks. As mentioned earlier, the
quotation marks simply mark where the string begins and
ends
Variables and Input
A variable is a storage location in memory that is
represented by a name. For example, a program that
calculates the sales tax on a purchase might use a variable
named tax to hold that value in memory. And a program
that calculates the distance from Earth to a distant star
might use a variable named distance to hold that value in
memory.

The word Input is an instruction to read a piece of data from


the keyboard. The word hours is the name of the variable in
which that the data will be stored. When this statement
executes, two things happen:
The program pauses and waits for the user to type
something on the keyboard, and then press the Enter key.
When the Enter key is pressed, the data that was typed is
stored in the hours variable
Variables and Input(Continue)
A simple pseudocode program that demonstrates the Input
statement.

1 Display "What is your age?"


2 Input age
3 Display "Here is the value that you entered:"
4 Display age
Variables Name
All high-level programming languages allow you to make
up your own names for the variables that you use in a
program. You don’t have complete freedom in naming
variables, however. Every language has its own set of rules
that you must abide by when creating variable names.
Although the rules for naming variables differ slightly from
one language to another, there are some common
restrictions:
•Variable names must be one word. They cannot contain
spaces.
•In most languages, punctuation characters cannot be
used in variable names. It is usually a good idea to use
only alphabetic letters and numbers in variable names.
•In most languages, the first character of a variable name
cannot be a number.
Displaying Multiple Items with one Display
Statement
Most programming languages provide a way to display
multiple pieces of data with one statement. Because this is
a common feature of programming languages, frequently
we will write Display statements in our pseudocode that
display multiple items.

1 Display "What is your age?"


2 Input age
3 Display "Here is the value that you entered: ", age

Notice that the string literal "Here is the value that you
entered: " ends with a space. That is because in the
program output, we want a space to appear after the
colon, as shown here:
Variable Assignment and Calculations
Variable Assignment
In the previous section, you saw how the Input statement
gets a value typed on the keyboard and stores it in a
variable. You can also write statements that store specific
values in variables. The following is an example, in
pseudocode:
Set price = 20
This is called an assignment statement. An assignment
statement sets a variable to a specified value. In this case,
the variable price is set to the value 20. When we write an
assignment statement in pseudocode, we will write the
word Set, followed by the name of the variable, followed
by an equal sign (=), followed by the value we want to
store in the variable.
Variable Assignment (Continue)
Example 1:
Set dollars = 2.75
Display "I have ", dollars, " in my account.“

NOTE: Variables are called “variable” because they can


hold different values while a program is running. Once you
set a variable to a value, that value will remain in the
variable until you store a different value in the variable. For
example,
1 Set dollars = 2.75
2 Display "I have ", dollars, " in my account."
3 Set dollars = 99.95
4 Display "But now I have ", dollars, " in my account!"
Flowchart for the example above
Example 2
Suppose your cell phone calling plan allows you to use 700
minutes per month. If you use more than this limit in a month,
you are charged an excess fee of 35 percent's for each excess
minute. Your phone shows you the number of excess minutes
that you have used in the current month, but it does not show
you how much your overall fee currently is. Design a program
that will simplify the task.

Computer Algorithm
1.Get the number of excess minutes as input.
2.Calculate the overall fee by multiplying the number of
excess minutes by 0.35.
3.Display the overage fee.
Example 2 (Continue)
Pseudocode

1. Display "Enter the number of excess minutes."


2. Input excessMinutes
3. Set overallFee = excessMinutes * 0.35
4. Display "Your current overage fee is $", overageFee
Flowchart
The Order of Operations
In most programming languages, the order of operations can
be summarized as follows:
1.Perform any operations that are enclosed in parentheses.
2.Perform any operations that use the exponent operator to
raise a number to a power.
3.Perform any multiplications, divisions, or modulus operations
as they appear from left to right.
4.Perform any additions or subtractions as they appear from
left to right
Mathematical expressions are evaluated from left to right.
When two operators share an operand, the order of operations
determines which operator works first. Multiplication and
division are always performed before addition and subtraction,
so the statement
The Order of Operations (Continue)
Expression Value
(5 + 2) * 4 28
10 / (5 - 3) 5
8 + 12 * (6 - 2) 56
(6 - 3) * (2 + 7) / 3 9
The Order of Operations (Continue)
Determining the average of a group of values is a simple
calculation: Add all of the values and then divide the sum by the
number of values.
Although this is a straight for ward calculation, it is easy to make
a mistake when writing a program that calculates an average.
For example, let’s assume that the variables a, b, and c each
hold a value and we want to calculate the average of those
values.
If we are careless, we might write a statement such as the
following to perform the calculation:

Set average = a + b + c / 3 // Produce an error


Set average = (a + b + c )/ 3 // Correct statement
The Order of Operations (Continue)
Algorithm1
1.Get the first test score.
2.Get the second test score.
3.Get the third test score.
4.Calculate the average by adding the three test scores and
dividing the sum by 3.
5.Display the average.
The Order of Operations (Continue)
Pseudocode
1.Display "Enter the first test score.“
2.Input test1
3.Display "Enter the second test score.“
4.Input test2
5.Display "Enter the third test score.“
6.Input test3
7.Set average = (test1 + test2 + test3) / 3
8.Display "The average score is ", average
The Order of Operations (Continue)
Flowchart

Set average=(test1+test2+test3)/3
The Order of Operations (Continue)
Notice that the flowchart uses a new symbol:

This is called a connector symbol and is used when a flowchart


is broken into two or more smaller flowcharts. This is
necessary when a flowchart does not fit on a single page, or
must be divided into sections. A connector symbol, which is a
small circle with a letter or number inside it, allows you to
connect two flowcharts.
Variable Declarations and Data Type
Most programming languages require that you declare all of the
variables that you intend to use in a program. A variable
declaration is a statement that typically specifies two things about
a variable:
•The variable’s name
•The variable’s data type
A variable’s data type is simply the type of data that the variable
will hold. Once you declare a variable, it can be used to store
values of only the specified data type. In most languages, an error
occurs if you try to store values of other types in the variable.
The data types that you are allowed to use depend on the
programming language. For example, the Java language provides
four data types for integer numbers, two data types for real
numbers, one data type for strings, and others.
Variable Declarations and Data Type (Continue)
Example 1:
Declare Integer length
Declare Real grossPay
Declare String name
Declare Integer length, width, height

NOTE: In addition to a String data type, many programming


languages also provide a Character data type. The difference
between a String variable and a Character variable is that a
String variable can hold a sequence of characters of virtually
any length, and a Character variable can hold only one
character
Variable Declarations and Data Type (Continue)
Example 2:
1.Declare Integer age
2.Display "What is your age?“
3.Input age
4.Display "Here is the value that you entered:“
5.Display age
Variable Declarations and Data Type (Continue)
Example 3:
1.Declare Real test1
2.Declare Real test2
3.Declare Real test3
4.Declare Real average
5.Set test1 = 88.0
6.Set test2 = 92.5
7.Set test3 = 97.0
8.Set average = (test1 + test2 + test3) / 3
9.Display "Your average test score is ", average
Variable Initialization
When you declare a variable, you can optionally assign a value
to it in the declaration statement. This is known as
initialization. For example, the following statement declares a
variable named price and assigns the value 49.95 to it:
Declare Real price = 49.95
We would say that this statement initializes the price variable
with the value 49.95.
The following statement shows another example:
Declare Integer length = 2, width = 4, height = 8
This statement declares and initializes three variables. The
length variable is initialized with the value 2, width is
initialized with the value 4, and height is initialized with the
value 8.
Data Type
Read on Data Type
Name Constants
A named constant is a name that represents a value that can’t
be
changed during the program’s execution.
Constant Real INTEREST_RATE = 0.069
Block Comment and Line Comment
Programmers generally write two types of comments in a
program: block comments and line comments. Block
comments take up several lines and are used when lengthy
explanations are required. For example, a block comment
often appears at the beginning of a program, explaining what
the program does, listing the name of the author, giving the
date that the program was last modified, and any other
necessary information.
The following is an example of a block comment:
// This program calculates an employee's gross pay.
// Written by Matt Hoyle.
// Last modified on 12/14/2010
Block Comment and Line Comment (Continue)
Line comments are comments that occupy a single line, and
explain a short section of the program.
The following statements show an example:
// Calculate the interest.
Set interest = balance * INTEREST_RATE
// Add the interest to the balance.
Set balance = balance + interest
Block Comment and Line Comment (Continue)
Example:
Suppose we have been given the following programming
problem: Scientists have determined that the world’s ocean
levels are currently rising at about 1.5 millimeters per year.
Write a program to display the following:
•The number of millimeters that the oceans will rise in five
years
•The number of millimeters that the oceans will rise in seven
years
•The number of millimeters that the oceans will rise in ten
years
Block Comment and Line Comment (Continue)
Algorithm:
1.Calculate the amount that the oceans will rise in five years.
2.Display the result of the calculation in Step 1.
3.Calculate the amount that the oceans will rise in seven
years.
4.Display the result of the calculation in Step 3.
5.Calculate the amount that the oceans will rise in ten years.
6.Display the result of the calculation in Step 5.
Block Comment and Line Comment (Continue)
Pseudocode:
// Declare the variables
Declare Real fiveYears
Declare Real sevenYears
Declare Real tenYears
// Create a constant for the yearly rise
Constant Real YEARLY_RISE = 1.5
// Display the amount of rise in five years
Set fiveYears = YEARLY_RISE * 5
Display "The ocean levels will rise ", fiveYears, " millimeters in
five years."
Block Comment and Line Comment (Continue)
// Display the amount of rise in seven years
Set sevenYears = YEARLY_RISE * 7
Display "The ocean levels will rise ", sevenYears, " millimeters
in seven years."
// Display the amount of rise in ten years
Set tenYears = YEARLY_RISE * 10
Display "The ocean levels will rise ", tenYears, " millimeters in
ten years."
Designing your first Program
In baseball, batting average is commonly used to measure a
player’s batting ability. You use the following formula to
calculate a player’s batting average:
Batting Average = Hits / Times at Bat
In the formula, Hits is the number of successful hits made by
the player, and Times at Bat is the number of times the player
was at bat. For example, if a player is at bat 500 times during
a season, and gets 150 hits, that player’s batting average is
300. Design a program to calculate any player’s batting
average.
// Declare the necessary variables.
Declare Integer hits
Declare Integer atBat
Declare Real battingAverage
// Get the number of hits.
Display "Enter the player's number of hits."
Input hits
// Get the number of times at bat.
Display "Enter the player's number of times at bat."
Input atBat
Set battingAverage = hits / atBat // Calculate the batting average.
// Display the batting average.
Display "The player's batting average is ", battingAverage
Declare Integer hits
Declare Integer atBat
Declare Real battingAverage
EXERCISE:
Assuming there are no accidents or delays, the distance that a
car travels down the
interstate can be calculated with the following formula:
Distance = Speed × Time
A car is traveling at 60 miles per hour. Design a program that
displays the following:
● The distance the car will travel in 5 hours
● The distance the car will travel in 8 hours
● The distance the car will travel in 12 hours

You might also like