Algorithms and Problem Solving Lec01 1. Outline 1.1 What is a Computer? 1.2 What is Programming? 1.3...
-
Upload
rodney-casey -
Category
Documents
-
view
217 -
download
1
Transcript of Algorithms and Problem Solving Lec01 1. Outline 1.1 What is a Computer? 1.2 What is Programming? 1.3...
Outline1.1 What is a Computer?1.2 What is Programming?1.3 The Anatomy of a Computer (schematic)1.4 Translating Human-Readable Programs to Machine Code (use high level language)1.5 Programming Languages1.6 The Evolution of C++1.7 Becoming Familiar with Your Computer (save ur works)
1.8 Compiling a Simple Program1.9 Errors1.10 The Compilation Process1.11 Algorithms?
Why are we here?
• To study “Computer Programming”Simple answer right?
4
Why do we study computer programming ?
• Subject name: Computer Programming I
• What is a computer?
• What is programming?
6
What is computer programming?
1.1 What Is a Computer?
• Good at repetitive tasks• Faster than humans; not smarter• Stores data• Interacts with devices• Flexible: can handle a wide range of tasks.
Runs programs to handle different tasks:– Record daily expenses and incomes– Create/View/Edit presentation slides– Play games
What is a Computer?
• Executes a huge number of primitive operations
• Gives the illusion of smooth interaction because it executes these operations at great speed
Fact: History of “Computer” nameThe ENIAC and the Dawn of Computing• electronic numerical integrator and computer• First usable electronic computer• Designed by J. Presper Eckert & John Mauchly, at Upenn• Completed in 1946 – 2 years before transistors• Many cabinets, in a large room• 18,000 vacuum tubes• Programmed by connecting wires on panels (patch panels)• Supported by Navy, for ballistic calculations• Before ENIAC, people who did these calculations were called
"computers"• Later used for tabulating US Census data, etc.
1.2 What is Programming?
• Programming — act of designing and implementing programs
• Most users (word processing, spreadsheeting) are not programmers
• Programming is an essential skill for a computer scientist and IT professional
The Anatomy of a ComputerCPU• Central Processing Unit• Performs program control, arithmetic, and data
movement• One operation at a time• Locates and executes program instructions• Consists of a single, or small number of, chip(s) made
of plastic, metal and mostly silicon• Composed of several million transistors• Enormously complicated wiring
The Anatomy of a Computer
Memory• RAM (Random Access Memory): read-write memory, the
opposite is the sequential memory• ROM (Read Only Memory): contains certain programs that
must always be present, the opposite is read/write memory• Secondary storage (e.g., a hard drive) provides persistent
storage
Bus• Bus: a set of electrical lines that connect the CPU, RAM, slots
and other connectors
The Anatomy of a Computer
Motherboard• The motherboard holds the CPU, memory, and bus,
as well as card slots and other connectors
The Anatomy of a ComputerPeripherals• Allow the computer to interact with user and
other computers:– Display / Monitor / LCD– Printer– Mouse– Keyboard– Speakers– Network card– Modem / WiFi Modem
The Anatomy of a Computer
Networks• Allow a computer to talk to other devices:
– Other computers– Central data storage– Shared printer
1.4 Translating Human-Readable Programs to Machine Code
Machine instructions:• Human language:
– Move memory contents location 40000 to a register– Subtract the value 100 from a register– If result is positive, jump (go) to another instruction at location 11280
• Extremely primitive. Encoded as numbers: 161 40000 45 100 127 11280
where 161 = move, 45 = substract, 127 = jump if >0• Thousands of instructions for a simple program• Each processor has its own set of machine instructions• Adding numeric codes manually is tedious and error prone
Translating Programs to Machine CodeAssembler• Use computer to translate• Assigns short names (mnemonic) to commands: mov 40000, %eax
sub 100, %eax
jg 11280• Makes reading easier for humans• Translated into machine instructions by the assembler• Can give names to memory locations• -'ve: Still processor dependent• -'ve: Still a great many instructions
// move memory contents location 40000 to a register// eax = processor register
// subtract the value 100 from a register
// if result is positive, jump to another instruction at location 11280// jg = jump if greater than 0
Translating Programs to Machine CodeHigher-level languages:• Easiest for humans to read and write: int eax = loc40000; (int loc40000 = 150;)eax = eax – 100;if (eax > 0) cout << “Positive number”;
• Helped/Translated by compilers into machine instructions– Very sophisticated programs– Translate logical statements into sequences of computations 161 40000 45 100 127 11280 – Find memory locations for all variable names
• Independent of the underlying hardware
1.5 Programming Languages• Designed for a variety of purposes• Machine independent (generally)• E.g. of Programming Languages: C++(also C),
Java, C#, Python• Much easier to read, but...• Much stricter than spoken languages.
– Compilers are less forgiving. For eg, if you omit the the second quotation mark of a C++ statement, the C++ compiler will get confused and complain that it cannot translate an instruction containing this error.
1.6 The Evolution of C++• Many languages are created with a specific purpose
– database processing– "artificial intelligence"– multimedia processing
• General purpose languages can be used for any task• C: developed to be translated efficiently into fast
machine code, with minimal housekeeping overhead• C++: adds "object oriented programming" aspects to
C
Programming Language Design and Evolution
History of C• Initially designed in 1972 (Kernighan & Ritchie)• Features were added from time to time in
response to perceived shortcomings• Resulted in different dialects
– Bad for portability
• 1989 — ANSI standard of C completed
Programming Language Design and Evolution
C++• 1979 — Bjarne Stroustrup of AT&T adds
object oriented features to C, called C with Classes
• 1985 — rename to C++• Other features added over the years• 1998 — First ISO C++98 standard published• 2003 — minor revision to the ISO std, ISO C++03
• 2009 — major revision expected, ISO C++0x
Programming Language Design and Evolution
C++• Most commonly used language for systems
such as:– Database– OS
• Growing popularity in embedded systems
Fact: What standard for?Standards Organizations• 2 groups have jointly developed the C++ standard:
– ISO — Int'l Organization for Standardization– ANSI — American National Standards Institute
• Associations of industry professionals• Many standards:
– Car tires– Shape of ATM cards– Programming languages– etc.
1.7 Becoming Familiar with Your Computer
• Log In• Locate the C++ compiler• Understand files and folders• Write a simple program• Save your work
Hint: ProductivityBackup Copies• Use a thumb drive, memory stick, external drive, or Internet
Storage• Back up often• Rotate backups. For eg, use three folders for backups and rotate
them• Back up source files only• Pay attention to the backup direction
– eg: copy from C: drive to D: drive or D to C. If you do it the wrong direction, you will overwrite a newer file with an older version
• Check your backups once in a while• Relax, then restore: when you lose a file and need to restore it from backup
1.8 Compiling a Simple Program// line comment/* block comment */
/* my first program in C++ with block comment */
#include <iostream>
using namespace std;
int main (){ cout << "Hello, World!\n"; // says Hello World!
return 0;}
> g++ “Lec01 hello world.cpp”> a.exe
31
C++ Comments ?
C++ Comments are pieces of source code discarded from the code by the compiler. They do nothing. Their purpose is only to allow the programmer to insert notes or descriptions embedded within the source code.
C++ supports two ways to insert comments:
// line comment/* block comment */
32
Layout of a Simple C++ Program ?#include <iostream>// other header files
using namespace std;
int main(){
variable_declarations
statement_1statement_2…statement_last
return 0;}
Compiling a Simple Program
• #include<iostream> — read the iostream header file
• using namespace std; — all names in the program belong to the "std" namespace
• int main () { ... } defines the main function– All C/C++ programs have a main() function
Compiling a Simple Program
• statements (instructions) inside the body of the main function:– executed one by one, in order (by sequence
control flow)– Each statement ends with a semicolon ;
• return is the end of the main function– 0 value signals that the program ran successfully
Compiling a Simple Program• Characters enclosed in double quotes ("Hello, World\
n") called a string• \ is the escape character:
• Escape sequence \n indicates a newline• Some others:
– \r = carriage return– \" = print a double quotation mark – \\ = print a single backslash– \t = tab– \a = alarm alert with beep sound
Compiling a Simple Program
Output• cout — the class output stream object (output
onto the screen)• << — the “insert" operator to output onto the
screen– Understands all built-in types– E.g., to print an integer: cout << 3 + 4 ; // 7
1.9 Errors
Syntax (or compile-time) errors• are faulty input, not quite legal C++. E.g., cot << "Hello, World!\n"; cout << "Hello, World!\"; // second double quote is missing
• Something violates the language rules• Compiler finds the errors, reports them: hello.cpp:7: error: 'cot' was not declared in this scope hello.cpp:7: error: missing terminating " character • Cascade: always start fixing errors from the top• Also, do not ignore warnings (ask if students want example)
ErrorsLogic or run-time error• Program compiles fine (input is legal) but Program doesn't do
what it's supposed to do• Much harder to find• Program author must test and find the error
cout << "Hell, World\n";
Overflow errors• Result falls outside computer's numeric range i.e., too big
(many digit) or too small (many decimal points). Eg, 1010000 = Overflow calculator.
Roundoff errors• Occurs when a value cannot be represented precisely.
Eg, 1/3 may be stored in the computer as 0.33333, a value that is close to, but not exactly equal to 1/3.
Errors• Testing
– Validating program correctness – Very important; discussed often in this text
• Debugging (remove bugs)– Finding the source of an error – A debugger is a handy tool
• Defensive Programming– Crafting programs to limit, minimize, localize errors
in one place if they do occur and the programs do not trigger an extremely bad response.
Common Error (syntax error)Don’t omit Semicolon:• Compiler ignores newlines• Uses semicolons to separate statements/instructions• Compiler sees this:
cout << "Hello, World!\n"return 0;as a single statement:cout << "Hello, World!\n" return 0;
• Make sure all your statements end in a semicolon– Even the last statement before a closing brace
Common Error (syntax or logic error)
Misspelling Words:• Misspelled words aren't obvious, make error
messages ambiguous. Eg: main()-> Main() • The compiler will compile your Main function
but the linker will complain about the “missing main function” and refuse to link the program.
• C++ is case-sensitive– All keywords and most library functions are lower-
case
1.10 The Compilation Process
Integrated desktop environments (IDEs) like CodeBlocks, Notepad++ shield user from compilation details:•Enter code in a window•Click a button to "compile" and "run".
So what is actually going on? See next slide…
The Compilation Process
• The compiler translates your C++ source into object code (*.o files)
• The linker takes your object files and code from various libraries, outputs an executable file
• Libraries contain (already translated/compiled) code, such as iostream
Figure 9: From Source Code to Executable Program
The Compilation Process
The process:• Compile• Errors? Edit file. Compile• Run• Errors? Edit file. Compile• Test• Errors? Edit file. Compile
Figure 10: Edit-Compile-Debug loop
46
1.11 Algorithms?
• Algorithm– A sequence of precise instructions for solving a
problem or carrying out a procedure that will terminate at some point.
ProblemSolving
Algorithms
Goals Checklist
• To understand the activity of programming• To learn about the architecture of computers• To learn about machine languages and higher-
level programming languages• To become familiar with your compiler• To compile and run your first C++ program• To recognize syntax and logic errors• To understand the notion of an algorithm to
solve problem