Introduction To Programming And Essentials Of Psychology Only For The Tutor John Mureithi
Introduction to Programming By
Lisa T. Cordeiro
About the Author
Lisa T. Cordeiro served in the Marines Corps in Okinawa, Japan, working in telecommunications. She later earned two bachelor degrees from the University of Massachusetts at Amherst and a master’s degree from Harvard University’s Extension School. Ms. Cordeiro has worked as a Web manager and technical writer and editor for 13 years. She has written several study guides for Penn Foster on topics such as the Internet, Microsoft Office, and Adobe products. In addition, Ms. Cordeiro has written articles and books.
Copyright © 2015 by Penn Foster, Inc.
All rights reserved. No part of the material protected by this copyright may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage and retrieval system, without permission in writing from the copyright owner.
Requests for permission to make copies of any part of the work should be mailed to Copyright Permissions, Penn Foster, 925 Oak Street, Scranton, Pennsylvania 18515.
Printed in the United States of America
All terms mentioned in this text that are known to be trademarks or service marks have been appropriately capitalized. Use of a term in this text should not be regarded as affecting the validity of any trademark or service mark.
INSTRUCTION TO STUDENTS 1
LESSON ASSIGNMENTS 5
LESSON 1: INTRODUCTION TO PROGRAMMING 7
GRADED PROJECT—LESSON 1 15
LESSON 2: MAKING DECISIONS 17
GRADED PROJECT—LESSON 2 27
LESSON 3: ARRAYS AND MENU-DRIVEN PROGRAMS 29
GRADED PROJECT—LESSON 3 37
LESSON 4: ADVANCED PROGRAMMING 39
GRADED PROJECT—LESSON 4 51
iii
C o
n t
e n
t s
C o
n t
e n
t s
YOUR COURSE Welcome to your course in computer programming. In this course, you’ll learn the basics of computer programming and logic. You won’t learn a specific programming language; rather, you’ll examine the basic logic common to all programming languages. You’ll come away from this course with solid knowledge of how to create your own programs. You’ll also learn guidelines on how to incorporate good design into your programs. You’ll walk away from this course with a solid understanding of programming concepts that you can use in your own designs.
This course is designed for beginner programmers. You don’t need any previous programming experience or an extensive math background; the text is written in nontechnical lan- guage, making it easy for beginners to follow the logic. You also don’t need to focus on a specific programming language. This course focuses on basic guidelines and best practices for developing good programming skills.
OBJECTIVES When you complete this course, you’ll be able to
n Describe basic programming steps
n Create modules and hierarchy charts
n Use Boolean expressions
n Create loops
n Add control breaks
n Create arrays
n Search and sort arrays
n Validate input
1
In s
t r
u c
t io
n s
In s
t r
u c
t io
n s
n Solve problems with recursion
n Use UML diagrams to design classes
n Design graphical user interfaces
n Write event handlers
YOUR TEXTBOOK Your textbook for this course is Programming Logic and Design, Third Edition, by Tony Gaddis. The textbook contains the material on which you’ll be tested. You should become familiar with this text prior to beginning your studies.
Begin by skimming the brief contents on page v. Here, you’ll see a list of the chapter titles, which give you an overall idea of what you’ll learn in this course. The contents, which begins on page vii, provides a more detailed listing of the topics you’ll learn in each chapter. Read the preface beginning on page xiii to explore how the text is organized.
The main part of your textbook (pages 1–583) is the study material for the course. Each chapter begins with a list of topics, followed by the study material itself. Each chapter also includes checkpoints to make sure you understand the content. At the end of each chapter are review questions and exercises; you’ll find the answers to these questions and exercises on your student Web site. Log in to the Student Area at http://www.pennfoster.edu, go to Student portal, and look for the Solutions link associated with your course.
Three appendices—A, B, and C—are located at the end of the text. An index begins on page 601. A fourth appendix is located on the CD included at the back of the textbook. This appendix includes answers to the checkpoints in the text. The index includes important topics covered in your textbook, along with page references where you can locate material relating to each term.
Instructions to Students2
Instructions to Students
COURSE MATERIALS This course includes the following materials:
1. This study guide, which contains an introduction to your course, plus
n A lesson assignments page with a schedule of study assignments
n Assignment introductions emphasizing the main points in the textbook
n Four graded projects, one for each of the lessons in this course
2. Your course textbook, Programming Logic and Design, Third Edition, which contains the assigned reading mate- rial for this course
A STUDY PLAN 1. Note the pages for each assignment and read the intro-
ductory material in this study guide.
2. Study the assigned pages, paying attention to all details, especially the main concepts.
3. Complete the checkpoints in the textbook. After answering the checkpoints, check your answers with those provided in Appendix D on the CD. If you miss any of the ques- tions, review the pages in the textbook that cover those questions. These questions are designed to reveal weak points that you should review. Do not send the answers to these questions to the school. They’re for only you to eval- uate your understanding of the material.
3. Complete the review questions and all assigned exercises at the end of the chapter to review the material. When you’re finished, go to http://www.pennfoster.edu and log in to your Student Area. Go to student portal and look for the Solutions link associated with this course. The review questions and assigned exercises are for you to practice the course material; do not send your answers to the school.
3
4. After you’ve completed and checked answers for the assignments for Lesson 1, complete the graded project for Lesson 1 and follow the directions for submitting your projects. Follow Steps 1–4 for Lessons 2–4.
You can e-mail your instructor for assistance at any time. You’re now ready to begin. Good luck!
Instructions to Students4
Remember to check your student portal regularly. Your instructor may
post additional resources that you can access to enhance your learn-
ing experience.
Lesson 1: Introduction to Programming For: Read in the Read in study guide: the textbook:
Assignment 1 Pages 8–9 Pages 1–26
Assignment 2 Pages 10–12 Pages 27–78
Assignment 3 Pages 12–14 Pages 79–119
Graded Project 41882700 Material in Lesson 1
Lesson 2: Making Decisions For: Read in the Read in study guide: the textbook:
Assignment 4 Pages 17–20 Pages 121–168
Assignment 5 Pages 20–22 Pages 169–224
Assignment 6 Pages 22–23 Pages 225–265
Assignment 7 Pages 24–25 Pages 267–279
Graded Project 41882800 Material in Lesson 2
Lesson 3: Arrays and Menu-Driven Programs For: Read in the Read in study guide: the textbook:
Assignment 8 Pages 29–31 Pages 281–335
Assignment 9 Pages 31–33 Pages 337–374
Assignment 10 Pages 33–35 Pages 375–428
Assignment 11 Pages 35–36 Pages 429–474
Graded Project 41882900 Material in Lesson 3
5
A s
s ig
n m
e n
t s
A s
s ig
n m
e n
t s
Lesson 4: Advanced Programming For: Read in the Read in study guide: the textbook:
Assignment 12 Pages 40–41 Pages 475–496
Assignment 13 Pages 41–42 Pages 497–517
Assignment 14 Pages 43–47 Pages 519–564
Assignment 15 Pages 47–50 Pages 565–583
Graded Project 41883000 Material in Lesson 4
Lesson Assignments6
7
L e
s s
o n
1
L e
s s
o n
1
Introduction to Programming If you’re new to programming, you might be intimidated by code and flowcharts. You might even wonder how you’ll ever understand them. This lesson offers some basic ideas and programming examples with which you can follow along. You’ll soon understand the logic behind software programs.
In your first assignment, you’ll read an introduction to com- puters and programming. In the second assignment, you’ll learn the steps in creating a program. In the third assign- ment, you’ll learn about modules and the best practices for creating a software program.
OBJECTIVES When you complete this lesson, you’ll be able to
n Describe basic programming concepts and steps
n Declare variables
n Describe documentation
n Discuss the importance of structure
n Create modules
n Pass arguments
n Describe global variables and constants
This study guide is designed to break down the material into easy-to-understand chunks so that you aren’t intimidated by the material. Follow the directions outlined in the assign- ments, read the assigned text, and answer the questions to get the most from this course. You’ll soon understand the basics of programming.
Introduction to Programming8
ASSIGNMENT 1: AN OVERVIEW OF COMPUTERS AND PROGRAMMING Read this assignment, and then read pages 1–26 in your text- book. When you’re comfortable with the material presented in the text, answer the review questions in the textbook and com- plete the assigned exercises to gauge your progress. If there are any areas with which you don’t feel comfortable, reread those sections in the textbook before returning to the study guide. When you feel you’ve mastered the material in Chapter 1, move on to the next assignment.
Computers are a big part of people’s lives today, but what makes them capable of doing such powerful tasks? The answer is that they’re programmed to perform tasks, or what someone tells them to do. A program is a set of instructions for the computer to follow; programs are often referred to as software. Someone who creates programs or software is known as a programmer or software developer.
Hardware refers to the physical parts of a computer. You’ll read examples of different types of hardware, such as memory, a central processing unit (CPU), storage devices, input devices, and output devices.
A computer needs both hardware and software to perform its four major functions: input, processing, output, and storage. Programmers tell the computer what to do by using programming languages, such as Visual Basic and C#. The programming language must follow certain rules, called syntax, for it to be understood. The commands that tell the computer what to do also must follow a certain sequence, or logic, so the computer can process the request.
Computers store data in bytes, which are tiny storage loca- tions. Each byte is divided into eight smaller units called bits. These bits act like switches because they’re either “on” or “off.” When bits represent numbers, or binary numbers,
Note: Make sure to answer the checkpoints in the textbook as you
read along. Check your answers in Appendix D, which is located on
a PDF file on the CD included at the back of your textbook.
Lesson 1 9
they’re assigned the number 0 when off and 1 when on. You’ll read more about how numbers and characters are stored in this chapter.
Machines understand machine language, which is difficult for people to communicate in. Therefore, program languages that instruct computers on what to do have been created. Types of programming languages include C, C++, Java, JavaScript, and Visual Basic, as well as several more. These are known as high-level languages. Programmers write statements known as source code. High-level languages need to be translated into machine language. A program that handles this transla- tion is called a compiler.
After programs are created, they’re store on a storage device, such as a disk drive. When the CPU runs, or executes, a program, it follows three steps:
1. Fetch
2. Decode
3. Execute
Lastly, you’ll read about types of software. System software manages computer operations and includes operating sys- tems and software development tools. Application software is used for tasks, which include word processing, e-mail, and spreadsheets.
Now, answer the review questions at the end of Chapter 1, then complete Exercises 1–4 on page 26 of your textbook. Log in to your Student Area at http://www.pennfoster.edu. Go to Student portal and look for the Solutions link associ- ated with this course. After you complete the review questions and exercises, move on to the next assignment.
Introduction to Programming10
ASSIGNMENT 2: INPUT, PROCESSING, AND OUTPUT Read this assignment, and then read pages 27–78 in your text- book. When you’re comfortable with the material presented in the text, answer the review questions in the textbook and com- plete the assigned exercises to gauge your progress. If there are any areas with which you don’t feel comfortable, reread those sections in the textbook before returning to the study guide. When you feel you’ve mastered the material in Chapter 2, move on to the next assignment.
Programmers perform five steps when creating a program (Figure 1).
Syntax is the programming language’s rules. Debugging refers to fixing any errors in the code so the program will work correctly. You’ll read about each of these steps in greater detail in this chapter.
When planning the logic of a program, programmers will often use flowcharts or pseudocode. A flowchart is a pictorial representation of the steps in a pro- gram. Pseudocode is an English-like representation of the steps. See Appendix B and Appendix C in your textbook for more information on flowcharts and pseudocode.
Computer programs work by following these three steps:
1. Receive input (data)
2. Perform a process
3. Produce output (such as displaying informa- tion or performing a task)
Program code can become quite complicated. When a collection of program statements becomes difficult to read, it’s called spaghetti code because it’s like following a noodle in a bowl of spaghetti. Therefore, keep your code simple by using struc-
FIGURE 1—Steps of Program Creation
Note: Make sure to answer the checkpoints in the textbook as you
read along. Check your answers in Appendix D, which is located on
a PDF file on the CD included at the back of your textbook.
Lesson 1 11
tures. A sequence is one kind of structure (Figure 2). You can stack structures on each other at entrance or exit points. Putting one structure within another is called nesting.
Programmers create variables that stand for dif- ferent values. The name of a variable should be no more than one word. Programmers end pro- grams by creating a decision, which is represented in a flowchart by a diamond. If the flowchart runs onto another page, they use a connector. When assigning values to variables, programmers often use the equal sign (=).
Many programs require some sort of calculation to be performed, such as addition or multiplica- tion. In this chapter, you’ll read about these and other common math operations, as well as the order of operations.
In most programs, variables must be declared before they can be used. This means that you must name the memory location and specify the type of data. Variable names are usually nouns, such as payRate, and types are the type of data the variable will hold (numbers or letters, for example).
Two types of documentation are generated during the pro- gramming process. Internal program documentation is for the programmer and includes program comments that identify the logic of the program. External documentation is for the people who use your programs—the end users—who will need documentation to know how to use your program. This type of documentation is also called user documentation.
Now, answer the review questions at the end of Chapter 2. In addition, complete the following exercises at the end of the chapter:
n Algorithm Workbench 1, 5, and 11
n Debugging Exercises 1 and 2
n Programming Exercises 1 and 7
FIGURE 2—A Sequence
Introduction to Programming12
Log in to the Student Area at http://www.pennfoster.edu. Go to Student portal and look for the Solutions link associ- ated with this course. After you complete the review questions and exercises, move on to the next assignment.
ASSIGNMENT 3: MODULES Read this assignment, and then read pages 79–119 in your textbook. When you’re comfortable with the material presented in the text, answer the review questions in the textbook and complete the assigned exercises to gauge your progress. If there are any areas with which you don’t feel comfortable, reread those sections in the textbook before returning to the study guide. When you feel you’ve mastered the material in Chapter 3, move on to the next assignment.
Programmers usually break down a program into separate units called modules. Modularization, or breaking programs into modules, is beneficial because it
n Uses simpler code
n Promotes code reuse
n Enables better testing
n Allows multiple programmers to work on a program
When naming a module, be sure to give it a one-word name that identifies it. Module names are often verbs, such as calculatePayment. A separate flowchart is created for each module. The module is called by placing the module’s name in a rectangle with bars across the sides (Figure 3). Note that modules can also call other modules.
To keep track of modules, you can create a hierarchy chart, which shows the relationship between modules
and demonstrates which modules call which other modules (Figure 4).
FIGURE 3—In a flowchart, modules
are depicted by a rectangle with a
bar across the top.
Note: Make sure to answer the checkpoints in the textbook as you
read along. Check your answers in Appendix D, which is located on
a PDF file on the CD included at the back of your textbook.
Lesson 1 13
Local variables are those declared inside modules. Global variables are those that can be accessed by all modules in a program; they’re declared outside modules.
Arguments are pieces of data sent into modules. Parameters are variables that receive arguments passed into modules. You’ll read about various ways to pass arguments into mod- ules, such as passing arguments by value and by reference.
When you create a program, you should develop a plan before you start so that you create a sound program design. One way to facilitate sound program design is to store your programming components in separate files so that you can easily find, read, and reuse segments. Another good practice is to choose suitable names for variables and modules. The following list contains some tips for naming variables and modules:
n Use meaningful names.
n Use names that are easily pronounced.
n Choose abbreviations that are easily understood by others.
n Avoid using numbers.
n Use both upper- and lowercase letters (camel case), if possible, in multiword names, or use dashes or under- scores to separate words.
n Use verbs in status names.
FIGURE 4—A hierarchy
chart shows the relation-
ships between modules
just, as a company’s orga-
nizational chart shows the
relationships within the
company or department.
Introduction to Programming14
To create programs with good design, you should also divide your line breaks consistently. Note that shorter lines are easier to read and follow. In addition, consider using tempo- rary variables when you have a long statement so that you can organize multiple variables.
Finally, you should use constants instead of numbers in your programs when possible. For example, suppose you have a value for an employee’s pay rate. Preferably, you should store the value as payRate rather than 10 (for $10 an hour), because the employee’s pay rate might change if he or she receives a raise.
Now, answer the review questions at the end of Chapter 3. In addition, complete the following exercises at the end of the chapter:
n Algorithm Workbench 1 and 2
n Debugging Exercises 1 and 4
n Programming Exercise 1
Check your answers by logging in to the Student Area at http://www.pennfoster.edu. Go to Student portaland look for the Solutions link associated with this course.
After completing the review questions and exercises, complete the first graded project. After you complete the graded project, move on to Lesson 2.
15
G ra
d e
d P
ro je
c t
G ra
d e
d P
ro je
c t
Lesson 1 Graded Project
Project Number: 41882700
This graded project will test your knowledge of what you’ve learned in this course so far. If you’ve read all the material in each assignment and completed the checkpoints, review questions, and assigned exercises in the text, you shouldn’t have any problems successfully completing these tasks.
Complete Exercise 6 on page 118 by creating both
n Pseudocode
n A flowchart
Scenario A personal trainer asks you to create a program to calculate and displays client’s body mass index (BMI). Use the information in Exercise 6 on page 118 to create this program by
1. Creating the pseudocode for this program
2. Creating a flowchart for this program
Hint: Use Visio or Microsoft Word’s Drawing toolbar.
Submitting Your Project Follow this procedure to submit your assignment online:
1. On your computer, save a revised and corrected version of your project. Make sure to include the project number (41882700) to identify the project.
2. Go to http://www.pennfoster.edu and log in.
3. Go to Student portal.
4. Click on Take Exam next to the lesson on which you’re working
5. Enter your e-mail address in the box provided. (Note: This information is required for online submission.)
Graded Project16
6. Attach your file or files as follows:
n Click on the Browse box.
n Locate the file you wish to attach.
n Double-click on the file.
n Click on Upload File.
7. Click on Submit Files.
Grading Your instructor will grade your project as follows:
n Used the lessons learned in this course to create the pseudocode for this program 25 points
n Created the modules for an effective program 25 points
n Created a flowchart for this program using lessons learned in this course 25 points
n Used the appropriate flowchart shapes to create a flowchart 25 points
TOTAL POINTS 100 points
17
L e
s s
o n
2
L e
s s
o n
2
Making Decisions In this lesson, you’ll learn how to create and structure deci- sions in your programs. You’ll learn how to create loops and when to use loop-type structures in your programs. You’ll learn how you can use functions, which are available in many language libraries. You’ll also learn about the input validation loop and defensive programming.
OBJECTIVES When you complete this lesson, you’ll be able to
n Insert Boolean expressions for comparisons
n Create decision structures
n Use case structures and logical operators
n Create different types of loops
n Write and use functions
n Create an input validation loop
n Describe defensive programming
ASSIGNMENT 4: DECISION STRUCTURES AND BOOLEAN LOGIC Read this assignment, and then read pages 121–168 in your textbook. When you’re comfortable with the material presented in the text, answer the review questions in the textbook and complete the assigned exercises to gauge your progress. If there are any areas with which you don’t feel comfortable, reread those sections in the textbook before returning to the study guide. When you feel you’ve mastered the material in Chapter 4, move on to the next assignment.
Note: Make sure to answer the checkpoints in the textbook as you
read along. Check your answers in Appendix D, which is located on
a PDF file on the CD included at the back of your textbook.
Introduction to Programming18
In decision structures, programs can perform actions only when certain conditions are met. You can design a computer program that makes decisions and then performs tasks accordingly. The way to program these decisions is with Boolean expressions. With Boolean expressions, two scenarios are possible—one true and one false, which are indicated by a 0 or a 1. For instance, in the expression “Is this number greater than 10?” you may assign the number 0 to “yes” and 1 to “no.” Keep the following tips in mind when using Boolean expressions:
n If there are two possible outcomes, use a dual-alternative structure. This structure is also called the If-Then-Else structure because if one condition is true, then the pro- gram does one thing; if the condition is false, then the program does something else.
n If there’s only one possible outcome, use a single-alternative decision structure. This structure is also called the If- Then structure because the program does only one thing.
Figure 5 lists some typical Boolean operators. Note that some programming languages vary in their use of Boolean operators.
An AND decision is a situation in which two conditions are true, such as a worker being a full-time employee and having worked at the company for more than five years. AND decisions need a nested decision or a nested If-Then statement, so
BOOLEAN OPERATORS
Operator Meaning Description
> Greater than The first value is greater than the second value.
< Less than The first value is less than the second value.
>= Greater than or equal to
The first value is greater than or equal to the second value.
<= Less than or equal to The first value is less than or equal to the second value.
== Equal to The two values are equal.
!= Not equal to The first value isn’t equal to the second value.
FIGURE 5—Common
Boolean Operators
Lesson 2 19
you should ask one question before another. Generally, you first should ask the question that’s less likely to be true to speed the processing of the program. AND decisions are usu- ally represented by the AND operator.
Similarly, you can use an OR decision when you wish to exe- cute an action if one or another condition is true. For instance, a worker is either full-time or the worker has worked at the company for more than five years. However, in this case, you first ask the question that’s more likely to be true.
Most programming languages allow you to combine AND and OR statements in expressions. In such expressions, AND state- ments have precedence because they’re executed first.
You can compare strings to see whether they’re equal. You can also compare strings to see if one is greater than or equal to another (or less than or equal to another). If you wish to test multiple conditions, you can nest one decision structure inside another.
An alternative structure you could use in some situations is a case structure, which is an alternative to using a series of decisions based on a value for one variable. You might use a case structure if there are several possible values for a vari- able. For instance, a program fee might be based on a sliding scale according to income.
You must structure your code for the following reasons:
n It keeps the code clear.
n It’s the way professional programmers write code.
n It’s more efficient.
n It’s easier to maintain.
n It can be broken down into modular pieces.
If you come across code that isn’t structured, you can struc- ture it. Again, think of a bowl of spaghetti. Your job is to follow a noodle through the bowl and untangle it from the other noodles. Essentially, you’re separating the noodles and rearranging them.
Introduction to Programming20
Now, answer the review questions at the end of Chapter 4. In addition, complete the following exercises that follow the review questions:
n Debugging Exercise 2
n Programming Exercise 6
Check your answers by logging in to the Student Area at http://www.pennfoster.edu. Go to Student portal and look for the Solutions link associated with this course. After completing the review questions and assigned exercises, move on to the next assignment.
ASSIGNMENT 5: REPETITION STRUCTURES Read this assignment, and then read pages 169–224 in your textbook. When you’re comfortable with the material presented in the text, answer the review questions in the textbook and complete the assigned exercises to gauge your progress. If there are any areas with which you don’t feel comfortable, reread those sections in the textbook before returning to the study guide. When you feel you’ve mastered the material in Chapter 5, move on to the next assignment.
Looping is a key feature of computer programming. It enables you to create instructions for working with multiple sets of data. For example, suppose you’ve created a program for a payroll program. By including a loop, you can run through your instructions on how to determine pay, overtime, tax withholding, Social Security deductions, and so on for one employee after another (Figure 6).
Note: Make sure to answer the checkpoints in the textbook as you
read along. Check your answers in Appendix D, which is located on
a PDF file on the CD included at the back of your textbook.
Lesson 2 21
Loop control variables determine whether or not the program should continue using a loop. You can stop a loop by com- paring a loop control value with a sentinel value.
A loop functions in the following way:
1. It asks a question.
2. It performs a procedure, if the answer dictates it.
3. If it performed a procedure, it goes back and asks the question again.
Three specific types of loops are the While loop, the Do–While loop, and the Do–Until loop. Here are the characteristics of these loops:
n The While loop does a task while a condition is true.
n The Do–While loop ensures that the loop runs at least once. A program begins and ends after one iteration, so this loop checks to see if the condition is still met before continuing.
n The Do–Until loop also ensures that the loop runs at least once. A program begins and runs statements until a condition is false.
Another way to control looping is to use a count-controlled loop to keep track of how many times an event has occurred. You can increment, or add to, the variable. Likewise, you can decrement, or subtract from, the variable. You can also control looping with a variable sentinel value, which means that the value you’re using in your loop can change.
FIGURE 6—Basic Loop
Structure
Introduction to Programming22
You also can use a loop to add, or accumulate, totals. You would use a variable called an accumulator, which is like a counter, except that it can add a value greater than one. (With a counter, you can increment only by one.)
A loop within a loop is called a nested loop. The loop that’s within another loop is called the inner loop; the outer one is called the outer loop.
Now, answer the review questions at the end of Chapter 5. In addition, complete the following exercises that follow the review questions:
n Debugging Exercise 2
n Programming Exercise 1
Check your answers by logging in to the Student Area at http://www.pennfoster.edu. Go to My Courses and look for the Solutions link associated with this course. After completing the review questions and exercises, move on to the next assignment.
ASSIGNMENT 6: FUNCTIONS Read this assignment, and then read pages 225–265 in your textbook. When you’re comfortable with the material presented in the text, answer the review questions in the textbook and complete the assigned exercises to gauge your progress. If there are any areas with which you don’t feel comfortable, reread those sections in the textbook before returning to the study guide. When you feel you’ve mastered the material in Chapter 6, move on to the next assignment.
In Assignment 3, you learned about modules. Now you’ll learn about a specific type of module called a function, which is a special type of module that returns a value back to the program part that called it. Functions are useful in certain situations, such as when you want the user of your program to input data. For instance, perhaps your program requires
Note: Make sure to answer the checkpoints in the textbook as you
read along. Check your answers in Appendix D, which is located on
a PDF file on the CD included at the back of your textbook.
Lesson 2 23
the user’s age to perform a calculation. A function would be useful for getting the data from the user and performing whatever calculation you program.
Many functions are built into programming languages so you can call them at any time. These pre-written functions are called library functions. For instance, the random function generates a random number, such as a computer game in which a player rolls dice.
Common library functions are
n Mathematical
n Data type conversion
n Formatting
n String
You can write your own functions in most programming lan- guages. You can write functions to return numbers, strings of characters, or Boolean values (true or false).
To write a function, write
n The function header
n The function body
n A return statement
Turn to page 234 in your text to see an example of a sum function written in pseudocode, and then turn to page 236 to see a flowchart of the same sum function.
Now, answer the review questions at the end of Chapter 6. In addition, complete the following exercises that follow the review questions:
n Algorithm Workbench 1, 2, and 4
n Debugging Exercise 1
n Programming Exercise 7
Check your answers by logging in to the Student Area at http://www.pennfoster.edu. Go to student portal and look for the Solutions link associated with this course. After completing the review questions and exercises, move on to the next assignment.
Introduction to Programming24
ASSIGNMENT 7: INPUT VALIDATION Read this assignment, and then read pages 267–279 in your textbook. When you’re comfortable with the material presented in the text, answer the review questions in the textbook and complete the assigned exercises to gauge your progress. If there are any areas with which you don’t feel comfortable, reread those sections in the textbook before returning to the study guide. When you feel you’ve mastered the material in Chapter 7, move on to the next assignment.
Computer programmers use the phrase “garbage in, garbage out” in reference to the fact that computers can’t differentiate between good and bad data. To try to prevent bad data from being entered, programmers use input validation, which refers to testing data to make sure it’s valid.
One way to test data is to create an input validation loop that repeats as long as the data that’s entered is bad data. For example, in a payroll program that has a maximum of 40 hours a week per employee, if a user enters a three-digit number, such as 100 hours instead of 10 hours, the data would be rejected.
To test input before beginning a loop, you would create a priming read, which aims to get the first input value to be tested in the validation loop.
Input validation is a type of defensive programming, which aims to prevent potential errors from happening by designing a program to avoid those errors.
Now, answer the review questions at the end of Chapter 7. In addition, complete the following exercises that follow the review questions:
n Algorithm Workbench 4 and 5
n Debugging Exercises 1 and 2
n Programming Exercise 4
Note: Make sure to answer the checkpoints in the textbook as you
read along. Check your answers in Appendix D, which is located on
a PDF file on the CD included at the back of your textbook.
Lesson 2 25
Check your answers by logging in to the Student Area at http://www.pennfoster.edu. Go to Student portal and look for the Solutions link associated with this course. After completing the review questions and exercises, com- plete the second graded project. After you complete the graded project, move on to Lesson 3.
Introduction to Programming26
NOTES
Lesson 2 Graded Project
Project Number: 41882800
For this graded project, you’ll complete several tasks to test your knowledge of the material you’ve learned in this course so far. If you’ve read all the material in each assignment and have completed the checkpoints, review questions, and assigned exercises in the text, you shouldn’t have any problems success- fully completing these tasks.
For this graded project, you’ll generate the following items:
n Pseudocode
n A flowchart
Scenario John Raymond was so pleased with the program you created for his clients that he refers you to his coworker, a nutritionist in the same fitness facility. The nutritionist would like you to create a program that calculates fat grams and calories. Read Programming Exercise 3 on page 279 for the information for your program, then
1. Create the pseudocode for this program.
2. Create a flowchart for this program.
Hint: Use Visio or Microsoft Word’s Drawing toolbar.
Submitting Your Project Follow this procedure to submit your assignment online:
1. On your computer, save a revised and corrected version of your project. Make sure to include the project number (41882800) to identify the project.
2. Go to http://www.pennfoster.edu and log in.
3. Go to Student portal.
4. Click on Take Exam next to the lesson on which you’re working
27
G ra
d e
d P
ro je
c t
G ra
d e
d P
ro je
c t
5. Enter your e-mail address in the box provided. (Note: This information is required for online submission.)
6. Attach your file or files as follows:
n Click on the Browse box.
n Locate the file you wish to attach.
n Double-click on the file.
n Click on Upload File.
7. Click on Submit Files.
Grading Your instructor will use the following grading guidelines to grade your project:
n Used the lessons learned in this course to create the pseudocode for this program 20 points
n Created the main module for an effective program 20 points
n Created a function for the program 20 points
n Used the appropriate flowchart shapes to create a flowchart 20 points
n Created a flowchart for this program using lessons learned in this course 20 points
TOTAL POINTS 100 points
Graded Project28
29
L e
s s
o n
3
L e
s s
o n
3
Arrays and Menu-Driven Programs In this lesson, you’ll learn about arrays and menu-driven programs. First, you’ll learn about arrays and the various types of arrays you can create. You’ll learn how to use algo- rithms to sort and search arrays. Then, you’ll learn about file input and output and how to process files. And finally, you’ll learn about menu-driven programs and how you can use them in your programs.
OBJECTIVES When you complete this lesson, you’ll be able to
n Describe and create arrays
n Search and sort arrays
n Process files and records
n Describe control break logic
n Describe and use menu-driven programs
ASSIGNMENT 8: ARRAYS Read this assignment, and then read pages 281–335 in your textbook. When you’re comfortable with the material presented in the text, answer the review questions in the textbook and complete the assigned exercises to gauge your progress. If there are any areas with which you don’t feel comfortable, reread those sections in the textbook before returning to the study guide. When you feel you’ve mastered the material in Chapter 8, move on to the next assignment.
Note: Make sure to answer the checkpoints in the textbook as you
read along. Check your answers in Appendix D, which is located on
a PDF file on the CD included at the back of your textbook.
Introduction to Programming30
Arrays are lists of variables in the computer’s memory that have the same name. They’re distinguished from each other by subscripts or numbers that indicate the variable’s position in the array. An example of an array is a set of file folders in a file cabinet that are alphabetized from A through Z.
Declaring an array involves declaring a program structure with multiple variables. Each variable is an element that has the same name and same data type. You also must declare the size of the array, which determines how many elements the array can contain. A simple way to declare and initialize an array is to write one statement that defines the type, name, and quantity of elements for the array.
Some special types of arrays include the following:
n Parallel arrays—These arrays involve two arrays in which each element in the first array is associated with the ele- ment in the same position in the second array.
n Two-dimensional arrays—These arrays store multiple data sets in several identical arrays.
n Multidimensional arrays—These arrays model data in multiple sets.
When searching for an array to find a value, you must
1. Create a variable.
2. Use a loop to test each array element.
3. Set a flag for when a match is found.
Also, keep the following in mind when creating arrays:
n You often can replace multiple nested decisions by using a variable as a subscript to an array.
n Make sure your subscript values don’t go out of the range of legal subscripts.
n When comparing a value with a range of values in an array, store either the highest or lowest value of the range for comparison.
Lesson 3 31
FIGURE 7—An Example of Ascending Order
Now, answer the review questions at the end of Chapter 8. In addition, complete the following exercises that follow the review questions:
n Algorithm Workbench 1, 3, 5, and 8
n Debugging Exercises 1 and 2
n Programming Exercise 3
Check your answers by logging in to the Student Area at http://www.pennfoster.edu. Go to Student portal and look for the Solutions link associated with this course. After completing the review questions and exercises, move on to the next assignment.
ASSIGNMENT 9: SORTING AND SEARCHING ARRAYS Read this assignment and then read pages 337–374 in your textbook. When you’re comfortable with the material presented in the text, answer the review questions in the textbook and complete the assigned exercises to gauge your progress. If there are any areas with which you don’t feel comfortable, reread those sections in the textbook before returning to the study guide. When you feel you’ve mastered the material in Chapter 9, move on to the next assignment.
To keep your records organized, you can sort them in sequential order. The order you choose may be ascending (for example, A to Z) or descending (for example, Z to A) (Figure 7). Sometimes when you sort records you may have to swap two values, in which case you can create a temporary variable to hold one of the variables while you swap them.
Note: Make sure to answer the checkpoints in the textbook as you
read along. Check your answers in Appendix D, which is located on
a PDF file on the CD included at the back of your textbook.
Apples
Bananas
Cantaloupe
Grapes
Pears
Plums
Raspberries
Introduction to Programming32
In this chapter, you’ll learn about three different types of sorting algorithms:
n Bubble sort
n Selection sort
n Insertion sort
A bubble sort is a simple kind of sorting technique in which pairs of list items are compared. With this sorting algorithm, one item is swapped with the one below it (ascending bubble sort) or the one above it (descending bubble sort).
A selection sort is a sorting algorithm that moves each value in an array into its final position through steps. It’s more efficient than a bubble sort because it takes fewer steps. An ascending selection sort assumes that the first element is the smallest and stores its position. Each element is then tested, and if an element is smaller than the first value, it switches places with the first element. That value is then compared with other elements.
An insertion sort also looks at pairs of elements in an array. If it finds an element that’s out of order, it moves backward until it locates a smaller element. A new position is then created for the out-of-order element, and all elements following it move down one position. Like a selection sort, an insertion sort is also more efficient than a bubble sort.
A search algorithm you’ll read about is the binary search algorithm, which finds items in an array by dividing the array in half multiple times. Through each division, it removes half of the array that doesn’t contain the item for which you’re searching. It’s more efficient than a sequential search.
Now, answer the review questions at the end of Chapter 9. In addition, complete the following exercises that follow the review questions:
n Algorithm Workbench 2, 3, and 4
n Debugging Exercise 1
n Programming Exercise 3
Lesson 3 33
Check your answers by logging in to the Student Area at http://www.pennfoster.edu. Go to My Courses and look for the Solutions link associated with this course. After completing the review, move on to the next assignment.
ASSIGNMENT 10: FILES Read this assignment, and then read pages 375–428 in your textbook. When you’re comfortable with the material presented in the text, answer the review questions in the textbook and complete the assigned exercises to gauge your progress. If there are any areas with which you don’t feel comfortable, reread those sections in the textbook before returning to the study guide. When you feel you’ve mastered the material in Chapter 10, move on to the next assignment.
Information is stored on a computer in what’s known as a data hierarchy, which is a database that contains files, with the files containing records and the records containing fields. Data consists of characters, such as letters or numbers.
Program data can be saved to files so you can use them at a later time. Files are saved on disks, such as a computer’s hard disk. Programmers refer to the process of saving data to files as writing data to the file; when they retrieve it, they read data from the file. The two types of files are text and binary. Since files can contain a lot of data, programs often use loops to process the data.
To use a file, a program must
1. Open the file.
2. Process the file.
3. Close the file.
File data is often stored in records, which contain a set of data for an item. Each piece of data in the item record is known as a field. For example, a university file might contain student information in records. Each record is for an individual stu- dent. Each item about a student, such as his or her first name or address, is a field.
In control break logic, a program’s processing is paused to perform a different action. The pause occurs when a control variable is changed. A control break occurs when a program’s
Introduction to Programming34
logic takes a temporary detour. For example, if you create an inventory for a CD store with CDs arranged by categories and you have a subtotal for the retail amount of each category, you’ve created a control break report. Another example of a control break would be placing page breaks in your report after each group of data, such as a CD category. Control break reports must be arranged in sequential order.
If you’re comparing data from one record to see if it matches data from another, you can create a control break field, which is a special variable that “remembers” the data to which a variable is being compared.
Control break logic is often used to print reports with cate- gories. Sometimes, you may need to put control data within the control break module itself, such as in a heading or footer. Say, for instance, that your CD inventory report’s page title reads Department category(), in which category() defines the CD category, such as “Classical” or “Rock.” You can use control data to print the appropriate department.
A complete single-level control break report can be set up to perform the following tasks:
n Print totals for previous groups of data
n Roll up the current-level totals to the next level
n Reset the current level totals to zero
n Perform other control break processing, if needed
n Update the control break field
In a multiple-level control break report, the control breaks away for special processing.
Lastly, you’ll learn about print spacing charts, which are paper sheets with grids on them. The paper is divided up like a grid and each square holds a character. Programmers often use X’s to represent characters in variables and 9’s to represent digits in variables.
Lesson 3 35
Now, answer the review questions at the end of Chapter 10. In addition, complete the following exercises that follow the review questions:
n Algorithm Workbench 1, 3, and 8
n Debugging Exercises 1 and 2
n Programming Exercise 1
Check your answers by logging in to the Student Area at http://www.pennfoster.edu. Go to student portal and look for the Solutions link associated with this course. After com- pleting the review questions, move on to the next assignment.