






























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!































Computer science is about problem solving, be it writing a program ( software ) to solve a problem or designing a new method of solving a problem or designing physical devices ( hardware ) that can follow the instructions in a program to solve a problem.
Problem solving is not new to you. You have been solving problems since you were an infant. Think of some of the problems you solved in the last week. Many of them you solved without much conscious thought: getting ready for the day or driving from home to the video store. Other problems required more thought and planning, such as moving your belongings from your summer residence to the residence you will occupy while you go to school or how to meet new friends. And there are always those dreaded “word problems”: you want to go to McBurp’s for a BurpBurger, fries and a drink that cost $3.97 and to a movie that costs $6.00. You have $10.00. Exactly how much will you have to borrow from your little brother so you’ll have enough to buy a small popcorn ($1.25) when you get there?
Whoever you are or whatever your interests, solving problems is an ordinary part of your world. And, since programming is really nothing more than solving a problem yourself and then telling a computer what to do to produce the solution, there is much you already know about the process.
People approach problem solving in different ways. By thinking about the characteristics of “successful” and “less successful” problem solvers, we can gain an insight into how we can become more successful problem solvers.
Successful problem solvers:
Less successful problem solvers often:
may be enough detail to get the task accomplished. Even with the original, three-step algorithm the task is often accomplished successfully because the user has enough experience to fill in the details.
Notice that this algorithm is written in an abbreviated form of English. These are not complete sentences. It is simply a series of steps. This could be called a “pseudo” language. It is not English in its true form, but is similar and understandable to someone who knows the English language.
There are three basic types of instructions, sequential, selection, and repetition. These different types of instructions control the order that operations are executed.
Sequential statements are performed in sequential order, one after another. In the algorithm above most of the statements are of this type. For example: Set bottle down This statement is done and then you move onto the next statement.
Selection statements control whether certain operations will or will not be executed depending on a condition. The algorithm above does not have one of these. We could add one. For example: If water is warm, wet hair otherwise adjust the temperature of the water Notice how this statement determines which action will be taken based on the condition. The condition is “water is warm”. The action will be “wet hair” when the condition is true and “adjust the temperature of the water” when the condition is false.
Repetition statements repeat a set of instructions. The algorithm above has us repeat eight steps two times, the first time and then one more time.
In computer science these are called control structures. We will learn about and use these control structures throughout the course.
So far, we have looked at a very basic definition of an algorithm: a step-by-step set of instructions to accomplish a task. In computer science, we have five very specific requirements of an algorithm:
This is crucial to the successful completion of the task. Consider the following hair washing algorithm:
Rub shampoo through hair until lather covers hair Wet hair Pick up shampoo bottle Open the bottle Pour some shampoo on your hand Put lid back on the shampoo bottle
Set bottle down Put shampoo on hair Rinse hair until all lather is removed Repeat the previous steps once
Notice that the order of one step has been changed. The step Rub shampoo through hair until lather covers hair may seem like the most important step in the process of washing hair. However, putting this step first causes the entire procedure to be incorrect. When writing an algorithm, each instruction must be in the correct order.
Each step must be clearly defined and organized in a way that there is no doubt how to proceed. Consider the following instruction: Pour some shampoo in your hand or get another bottle
This is ambiguous. How is one to determine which thing to do? The instructions must be clear in specifying what is to be done in any situation. The above choice could be written as: If the bottle has shampoo in it, pour some in your hand; otherwise, get another bottle.
This instruction makes it clear what to do when the bottle has shampoo in it and what to do otherwise. It covers all cases and leaves no doubt how to proceed.
Another example of ambiguity is found in of simple set of shampoo bottle instructions we saw previously. lather rinse repeat
The ambiguity comes in the last statement, repeat. What is to be repeated? Does the person following the instructions repeatedly lather and rinse or just repeat the rinse? To clear this up, one might write: lather rinse repeat the previous two steps
For a set of instructions to be an algorithm, there can be no ambiguity.
It is possible to write a set of instructions that, when followed exactly, would never end. For example, look our shampoo instructions again. lather rinse repeat the previous two steps
Read through the problem statement and identify these different elements. Sometimes the problem statement will not clearly identify each of the first four components. So first focus on the output to determine the result the program is to produce. Have a clear understanding of the desired outcome of the program. To do this think up some example inputs and manual produce the expected outputs. As you generate this output you will see what needs to be done. This will help to identify what input is needed and what process(es) must be accomplished by the program. You may find it helpful to underline or circle the different requirements or set them up in a table, as shown in the following example.
Consider the problem statement: Write a program that gets the height, width, and depth of a box from the user and reports the volume of the box.
Starting with output: We can identify that the volume of the box is the required result of the program. List this under output. Then look for what will be supplied to the program, the input. The problem states the height, width, and depth of the box will be provided by a user. List these three items under input. There are no values given in the problem statement. The process to be performed is the calculation of volume. Put this under the process category. Note that we are not yet concerned with how to calculate the volume, only that it must be done.
Input Given Values Processing Output Examples
height none calculate volume volume of box A box with a height width of 7, a width of 8, and
depth a depth of 3 will produce a volume of 168
Now reread the problem to see if you understand what is to be accomplished. You should only proceed to the next step in the programming process when you have a sound understanding of the problem, If you are not comfortable with your understanding of the problem statement seek help, ask questions. The instructor and the tutors are available to answer questions and clarify details. It is much better to get a clear view of the problem at this stage than to proceed with a gap in your understanding. Often, those gaps, if left unattended, will require additional time and unnecessary effort, and will likely produce errors later in the process.
Once you have clearly defined the problem, it is time to organize the solution. Write down the major steps that need to be accomplished as a simple outline. Try to break the problem up into smaller parts. This technique is called top-down design.
In the previous step you identified the tasks that need to be accomplished; in this step, you begin to organize those tasks. Consider whether any steps need to be repeated or if there are alternate steps to be followed, for example what to do if there is no warm water. List the steps and establish the order in which they must be performed. Outline them in the correct order. Note that we are still not concerned with the processing details, only with what has to be done. Of course, for simple problems you may immediately recognize how to do the processing. But, the problems you will be solving will increase in difficulty and/or complexity. If you follow the design process as it is being described, you will be able to produce an accurate outline of the program without having to worry about the details. Think of the operation as writing an outline for an assistant who will perform the details to accomplish the broad tasks you specify. (Of course, you will eventually have to specify those details; but for now the focus is designing the solution.)
Example: For the problem statement analyzed in Step 1: Write a program that gets the height, width, and depth of a box from the user and reports the volume of the box.
There are no steps to be repeated, there are no alternate steps to follow, and the order is straightforward. Our simple English outline would look like: Get height, width and depth of the box from user Calculate the volume of the box Output the volume of the box
As your problem solving ability and programming expertise increase, you may find that you can combine this step with the next one—developing the algorithm.
Since our ultimate goal is to write a series of instructions that can be carried out by a computer, we have to think about what needs to be done in terms of what a computer is able to do. We are not yet ready to write the instructions in a programming language. At this stage we are designing the solution. As we develop the design, we will keep in mind that we will be solving the problem with a computer program. The steps we develop will be steps that can be carried out by a computer.
Remember an algorithm is a step-by-step set of instructions to accomplish a task. In this step you simply write this list of instructions.
It is during this step that we add many of the details. What will our interaction with the user be? What formulas will we need to make the calculations? For the problem statement analyzed in Step 1 and Step 2: Write a program that gets the height, width, and depth of a box from the user and reports the volume of the box.
The algorithm would look like: Print “Enter the height of the box: “ Get height from user Print “Enter the width of the box: “
height width depth volume 3 5 4 60
Print “The volume of the box is “ The volume of the box is
Print volume 60
This step brings us to the process of coding in a language that the computer can understand. The computer actually only understands machine language, a language consisting of 1s and 0s. This is a difficult language for people to work with. High-level programming languages like C++ or Java have been developed to provide a language that is easier for people to understand and work with. They follow exact syntax rules. The exactness of the language makes it possible for tools such as a compiler to translate the programming language the machine’s language of 0s and 1s.
In this course, we will be using the programming language C++. This is a powerful language and there are many details to learn. We will use the text, Starting Out with C++, 6th^ edition by Tony Gaddis to learn about the details of the C++ language.
This is the most rewarding step of all. As you use a computer to execute the code you have designed and written you get to see firsthand the results of your labors. You will be informed of any syntax errors you have made. Luckily, these can be easily corrected and the program can be rerun. And since you have taken the time to carefully and thoughtfully develop and test your algorithm, you should have, if not a final product, then one very close to final. You will have the satisfaction of seeing that you can write a complete solution that causes a computer to produce the desired results. Not bad!
There are different types of documentation, including documentation designed for the user. However, in this course we will only be concerned with internal documentation that is designed for programmers. The documentation should make it easy for another programmer to understand your program and revise it, if necessary. (It will also help you remember what the program is doing when you look at the program 2 weeks or six months from now!) We will learn to add comments that are ignored by the compiler, but which clarify details and explain the purposes and methods of our programs.
Maintenance involves keeping programs updated and secure. This topic is not specifically covered in this course.
This course reader covers the first 4 steps. This process of analyzing the program, outlining the solution, developing an algorithm, and testing the algorithm is the core of good program development. When these steps are done effectively, better solutions are produced in less time.
Algorithms for computers can be expressed in many different ways, or if you will, in different “languages”. Ultimately we want an algorithm expressed in a specific programming language. However, programming languages have very rigid rules dealing with the way we can write an instruction. These grammar rules are called the syntax of the language. It is very difficult, error- prone, and time-consuming to try to write a program of any size or complexity directly in a programming language. The programmer tends to get bogged down in the details of the language and loses sight of the more important aspects of solving the problem.
Several “algorithmic languages” have been developed to help the programmer first solve the problem. These include
Our pseudo-code language will include the following elements:
We will be using the following key words. Each word has a specific function. We will discuss how they work when we first use them. Get Print And Or If Else End If Repeat End Repeat While End While
There is one operator that has a very specific use in computer science that is different than how you have used it in math. It is the assignment operator: =
This operator looks like the equality operator used in algebra but it performs a different operation. It is the assignment operator. This operator takes the value on the right hand side and stores that value in the storage location specified on the left hand side.
The value on the right hand side can be a number, a variable, or an expression that produces a value. The left hand side must be a place that a value can be stored – a variable.
Examples: result = 365 * 92 + 12
area = length * width
age = 92
Note: Order is important here. The assignment operator works from right to left only. The following is not correct: length * width = area
The default operation of most computers is to execute program instructions sequentially, one after another. However, it is often necessary to have the computer choose between two sets of instructions. For example, the computer may need to execute one set of instructions for calculating pay if the employee is salaried and a different set if the employee is on commission.
Also, since a major advantage of using a computer to solve a problem is its ability to quickly and accurately perform the same calculations with different data, we often want to set up a series of instructions and have the computer perform them repeatedly. For example, we might want to calculate pay for all 48 employees in the firm. The way we do this is to set up the instructions on how to calculate the pay and tell the computer to do it 43 times. The beauty of this is that it would be just as easy to do it for 798 employees!
So, we see that we need to be able to control the order in which instructions will be performed, or as we say in programming, the order in which instructions will be executed.
Computer scientists have proven mathematically that any problem that is solvable by computer can be solved using, at most, three different kinds of control structures.
They are:
As mentioned, this is the “native” mode of execution. In a sequence structure, the instructions are completed in series, one right after another. Most of the hair washing hair algorithm is this type, for example, pick up shampoo bottle, take lid off bottle.
This structure is used to select which steps will be executed, depending on whether a certain condition is true or false. We are all familiar with the concept of “if”. We saw an if in the hair- washing algorithm with respect to the availability of warm water. The step “get another bottle of shampoo”, will only be performed if the condition, “the bottle is empty”, is true.
In a repetition structure, a set of instructions are repeated. “Repeat the previous two steps once” sets up a repetition structure. In this case it instructs the "shampooer" (processor) to perform a series of steps one more time. Repetition structures may be set up so that a group of instructions is repeated a certain number of times or until a condition changes, for example, "While there are more employees"…(set of instruction to be repeated).
A requirement of an algorithm is that it produces a result. Often this result is some type of output. This output may be displayed on a monitor or written to a file. When we want to produce output we will use the keyword Print.
Output may take different forms, for example: a message to the user; the value of a variable; the result of a computation. When we wish to indicate that a series of specific characters are to be output, we will enclose the characters in quotation marks, " ". (A series of characters is referred to as a string. ) When we want to output the value of a variable, we simply refer to the variable by name.
Examples: Print "Welcome!" This command will display the string Welcome! Notice that the quotation marks are used to identify the beginning and end of the string and are not actually printed.
Print volume This command will display the current value of the variable named volume. When referring to variables use only the name of the variable (no quotation marks.)
Print height * width This command will first do the calculation height * width and then display the result.
When displaying output it is important to label it. Labeling output is simply displaying information that explains the values being output. For example:
Print "The volume of the box is " Print volume
This example uses two Print commands. The first is just the label and the second is the actual value that is to be output. It is possible to combine multiple outputs in a single Print command. To Print multiple outputs, simply separate the outputs with a comma. The comma will not be output. The following single Print command will produce the same output as the two Print commands above. Print "The volume of the box is ", volume
to solve the problem. It is important to recognize that this is an emotional response and does not reflect one's intellectual ability.
If you suffer from such anxiety, here are a couple more ideas that may help.
Back to our problem—
Step 1 - Analyze the problem
a. Identify what we want to produce, the output: total cost of bags sales tax total sale
b. Look for the input: There will be three numbers in a file. They are quantity of small bags ordered quantity of medium bags ordered quantity of large bags ordered
c. Look for Given Values This problem statement gives us several values that are needed to do the calculations. We will want to make a note of these values. price of a small bag - $2. price of a medium bag - $3. price of a large bag - $4. the sales tax rate – 7%
d. What processing will need to be done? We will need to calculate total cost calculate the amount of sales tax calculate the total sale
You may find it helpful to put these in lists so the information can be easily seen: Input Values Given Processing Output quantity of small bags price of small $2.50 calculate total cost total cost of bags quantity of medium bags
price of medium $3.25 calculate sales tax sales tax quantity of large bags price of large $4.00 calculate total total sale sales tax rate 7%
Examples If the file contains 5 8 10 the result will be cost: $78. sales tax: $5. total: $83.
If the file contains 45 82 63 the result will be cost: $ sales tax: $44. total: $675.
If the file contains 318 264 91 the result will be cost: $ sales tax: $141. total: $2158.
After extracting all this information from the problem statement, read the problem again to make sure you understand what it is asking for.
Step 2: Outline the solution.
Make a list of what needs to be done. It is critical at this point to make sure the steps are in the correct order. In this problem there are no choices to be made and the computations are only done once, so it can all be done with sequence structures. Set the initial prices of the bags Set the value of the tax rate get the numbers from the file calculate cost calculate sales tax calculate total print the results to the screen
Step 3: Develop an algorithm
In this step fill out the outline by adding the details. Notice we use variables to store all the values even though they don’t change. See how we wrote 7%. Also, the prices could have been written different. The zeros at the end do not change the values so we could have used 2.5, 3.25, and 4 and produced the same result.
small_price = 2. medium_price = 3. large_price = 4. tax_rate =.
output is expected to be in dollar and cents. The problem arises when we multiply by .07. Lets add an additional step that resolves the problem:
small_price = 2. medium_price = 3. large_price = 4. tax_rate =. Get smallQty, mediumQty, largeQty cost = small_price * smallQty + medium_price * mediumQty + large_price * largeQty sales_tax = cost * tax_rate round sales_tax to 2 decimal places total = cost + sales_tax Print "The cost of the bags is ", cost Print "The sales tax is ", sales_tax Print "The total sale is ", total
small_price = 2.50 small_price
medium_price = 3.25 small_price medium_price 2.50 3. large_price = 4.00 small_price medium_price large_price 2.50 3.25 4. tax_rate = .075 small_price medium_price large_price tax_rate 2.50 3.25 4.00. Get smallQty, mediumQty, largeQty small_price medium_price large_price tax_rate 2.50 3.25 4.00.
smallQty mediumQty largeQty 5 8 10 cost = small_price * smallQty + medium_price * mediumQty + large_price * largeQty
small_price medium_price large_price tax_rate 2.50 3.25 4.00.
smallQty mediumQty largeQty cost 5 8 10 78. sales_tax = cost * tax_rate small_price medium_price large_price tax_rate 2.50 3.25 4.00.
smallQty mediumQty largeQty cost sales_tax 5 8 10 78.50 5. round sales_tax to 2 decimal places small_price^ medium_price^ large_price^ tax_rate 2.50 3.25 4.00.
smallQty mediumQty largeQty cost sales_tax 5 8 10 78.50 5. total = cost + sales_tax small_price medium_price large_price tax_rate 2.50 3.25 4.00.
smallQty mediumQty largeQty cost sales_tax total 5 8 10 78.50 5.50 84.
Print "The cost of the bags is ", cost The cost of the bags is 78. Print "The sales tax is ", sales_tax The sales tax is 550 Print "The total sale is ", total The total sale is 84.
A condition is a question whose answer is either true or false. (A value that can take on one of only two possible values is called a Boolean value, after the mathematician George Boole) We will use these questions as we develop selection and repetition structures.
Often we ask these kinds of questions by using comparison operators such as the following: < Less Than > Greater Than = = Equal To (the double equal sign is used to distinguish it from the assignment operator: = , which assigns a value to a variable) ! = Not Equal To < = Less Than or Equal To > = Greater Than or Equal To
Examples: elevation = = 10000 Question: Is the value stored in elevation equal to 10000? This condition will be true only when the value in elevation is 10000. (Note that we do not use commas in large numbers.)
size < 12 Question: Is the value stored in size less than 12? This condition will be true when the value stored in size is less than 12. Note that the condition will be false when the value in size is exactly12.
quantity >= 100 Question: Is the value stored in quantity greater than or equal to 100? This condition will be true when the value stored in quantity is greater than 100 and will also be true when the value stored in quantity is equal to 100. It will only be false when the value stored in quantity is less than 100.
92.5 > cost Question: Is 92.5 greater than the value stored in cost? This condition will be true when the value stored in cost is less than 92.5. Note the condition will be false when the value in cost is 92.5.
volume! = 78. Question: Is the value stored in volume not equal to 78.9? This comparison is sometimes confusing to read, but if you just take a moment to think about what you are asking, you should be OK. This condition will be true when the value stored in volume is not 78.9. It will be false only when the value stored in volume is 78.9. You're probably wondering why we would want to ask a question in this way. You will discover that we frequently want to repeat a series of instructions as long as the user does not enter some specific value or that we only want to execute a series of steps when a certain situation does not exist. Hang in there, and it will make more sense when you have more experience.