Upload
ralf-terry
View
215
Download
1
Tags:
Embed Size (px)
Citation preview
Problem Solving via Problem Solving via ComputersComputersCS 1428 Week 1
Texas State UniversityTom O’HaraSpring 2011
Chapter 1 SynopsisChapter 1 SynopsisImportant
◦Sections 2, 3Useful
◦Sections 1, 4, 5, 6Ignore
◦Section 7◦Table 1-1 (programming languages)◦Serendipity Booksellers project
OverviewOverviewSyllabus and textProblem solving via algorithmsModels for computersHardware and softwareFeatures of C++ programming
languageGenerating machine code from
C++
Computer ScienceComputer ScienceComputers are general-purpose
machines for performing calculations◦Originally just a glorified calculator◦Now quite versatile and pervasive
Computer science studies of how to solve problems on computers◦Focused on abstract model of computers◦Avoids vendor specifics (e.g., IBM vs.
Apple)◦More than just computer programming
Problem Solving via Problem Solving via ComputerComputerAlgorithms: precise specification of how
to solve a particular problemFlowcharts: schematic representation
of steps in solving a problem (old school)
Pseudo-code: instructions that combine aspects of programming languages and natural language
Program: instructions in artificial language designed for computer problem solving
Sample algorithmSample algorithm
For each hour of dayLet temp be current temperatureIf temp less than 32 then
print "Below freezing"Otherwise
print "At or above freezing"Wait one hour
Note: displays hourly status about freezing temperature
Sample flow chartSample flow chart
Sample pseudo-codeSample pseudo-code
hour = 0while (hour < 24) do
temp = read_value() if (temp < 32) then
print("Below freezing") else
print("Above freezing") hour = hour + 1
end while
Sample C++ ProgramSample C++ Program#include <iostream> // standard I/O operations
using namespace std; // import standard names
int main () {
double temperature; // temperature in Farhenheit
for (int hour = 0; hour < 24; hour++) {
cout << "Enter current temperature: ";
cin >> temperature;
if (temperature < 32) {
cout << "It is below freezing" << endl;
}
else {
cout << "It is at or above freezing" << endl;
}
}
return (0);
}
AlgorithmAlgorithmPrecise specification on solving a
problemCentral to computer science
◦First solve problem via algorithm◦Then implement algorithm via program
Example◦Goal: Drive from South Austin to Texas State◦High-level Algorithm
Get on I35 at exit 226 (Slaughter Lane)Drive 20 miles southTake right on exit 206 (Aquarena Springs Drive)
Characteristics of Bad Characteristics of Bad AlgorithmsAlgorithms
Vague descriptionsex: Take I35 to San Marcos
Omits important detailsNot mentioning exit 206 in San Marcos
Overly wordy descriptionsex: Get on I35 by Walmart, taking access road along South Park Meadows, passing I30 toll, ...
In C++ or another programming language
This is a program not an algorithm
Characteristics of Good Characteristics of Good AlgorithmsAlgorithms
Mostly in a natural language (e.g., English)
Precise specification of problemGet on I35 at exit 226, drive for 20 miles south, get off I35 at exit 206, ...
Avoids technical terms and jargonDepress the decelerator if state officer
detected=> Hit the breaks if you spot a trooper
Minimal use of "programeese"Not written using C++ syntax
Algorithm DevelopmentAlgorithm DevelopmentApproach
◦Top-level from high-level description of task
◦Stepwise refinement from English into high-level pseudo-code (but not program)
Example:◦Task: Convert dollars to pesos◦Initial algorithm
Get amount of dollarsGet currency exchange for pesosDivide dollars by exchange rate
Group Exercise on Group Exercise on AlgorithmsAlgorithmsDone in separate groups
◦Have one person record algorithm to hand in
Task: Write algorithm to do following◦Convert Celsius to Fahrenheit
Fahrenheit = 9/5 Celsius + 32
◦Also give clothing advice for temperature ex: Wear heavy parka if temperature below 32
Tip:◦Be specific but not overly wordy◦Write as if explaining to a younger sibling
Computer HardwareComputer HardwareCPU: combines control unit and ALURegisters: high speed storage in CPU
◦Usually just few dozen given expense Main Memory: temporary storage for
dataSecondary Storage: persistent
memory for dataInput Devices: keyboards, mice, etc.Output Devices: monitors, printers,
etc.
Computer SoftwareComputer SoftwarePrograms and associated dataTypes
◦System Operating System Device Drivers System utilities
◦Application Word processing and other office
applications Web browsers
Turing MachineTuring MachineNote: For CS1428, this is mainly FYI material
Early model of computerDesigned by English mathematician Alan
Turing◦Famous for cracking German Enigma machine
Important in computational theoryFeatures
◦Infinite tape◦Operates only on current cell based on contents◦Can just change symbols or erase
Turing Machine ExampleTuring Machine Example
von Neumann Machinevon Neumann MachineModel developed by John von Neumann
◦Mathematician at Princeton◦Pronounced as /noy man/
Foundation for modern computers◦Thus very important (see CS 1428 objectives)
Features:◦Programs and data both reside in memory:
“stored program computer”◦Control unit for fetch/decode/execute cycle◦Separate unit for basic operations (add, etc.)
Example von Neumann Example von Neumann MachineMachine
Programming Language Programming Language TypesTypesMachine: based on CPU
operations10001001000011011100000010000011
Assembly: symbolic version of aboveADL $13, %eax
High-level: usual mathematical notationx + 13
C LanguageC LanguageDeveloped at Bell Labs in early
70’sHigh-level languageSome lower-level features
Direct access to memorySomewhat cryptic
*p++; // result = *p; p = p + 1;
rate = (age>17) ? adult : child;
C++ LanguageC++ LanguageDeveloped circa 1980 by Bjarne
StroustrupAdds additional features to C
◦Object-oriented programming◦Namespaces◦Templates◦Exception handling◦Operator overloading
Not covered in depth until CS 2308
Program Elements in C++Program Elements in C++Variables: user names for
memoryConstants: numbers and stringsOperators: mathematical and
logicalComments: notes about programKeywords: reserved wordsFunctions: user-defined
operations
Currency Conversion Currency Conversion ProgramProgram
#include <iostream> // standard I/O operations
using namespace std; // simplify access to internals
int main ()
{
double rate = 13.07;
double dollars, pesos;
// Get number of dollars and convert to pesos
cout << "Amount in dollars: ";
cin >> dollars;
pesos = dollars * rate;
// Output result with optional qualification
cout << "In pesos: " << pesos << endl;
if (pesos < 100) cout << "Pobrecito!" << endl;
return (0);
}
Miscellaneous C++ IssuesMiscellaneous C++ IssuesLines versus statements
Statements don’t end until semicolon occursEx: value = 1 * digit4 + 2 * digit3
+ 4 * digit2 + 8 * digit1;Syntax versus Semantics
Syntax indicates format of expressions, etc.; semantics determines how interpreted.
Procedural versus Object-orientedStep by step specification versus use of agent-like
objects that encapsulate their behavior.
From C++ to Machine From C++ to Machine CodeCodePreprocessor
◦Loads common definitions: Ex: #include <iostream>
◦Performs miscellaneous text substitutions
Compilation◦Creates relocatable machine code
Linking◦Adds library code and creates
executable
Student ExerciseStudent ExerciseDone by each studentConvert Celsius to Fahrenheit
◦Fahrenheit = 9/5 Celsius + 32 Tip
◦Use currency conversion program as sample
◦Don't panic: just to get you thinking in C++