900 likes | 1.03k Views
Textbook. CS 140 Introduction to Computing I. Instructor: Bill White Engineering Building 3041 (618)650-3483 wwhite@siue.edu. Office Hours: MW 8:00-9:30AM & 2:00-3:00PM TR 8:00-10:00AM & 12:30-2:00PM and by appointment.
E N D
Textbook CS 140Introduction to Computing I Instructor: Bill White Engineering Building 3041 (618)650-3483 wwhite@siue.edu Office Hours:MW 8:00-9:30AM & 2:00-3:00PMTR 8:00-10:00AM & 12:30-2:00PMand by appointment
Tentative Syllabus AND THEN… A COMPREHENSIVE FINAL EXAM!!! WEEK 1 Intro to Hardware, Software, & C++ WEEK 2 Variables, Data Types, & I/O WEEK 3 If-Else, Looping, & Program Style WEEK 4 Nested Ifs & Switches WEEK 5 For-Loops, Nested Loops, & Infinite Loops EXAM #1 WEEK 6 Top-Down Design & Predefined Functions WEEK 7 Function Definitions & Black Boxes WEEK 8 Local Variables & Void Functions WEEK 9 Call-by-Reference & More Black Boxes WEEK 10 Function Design, Testing, & Debugging EXAM #2 WEEK 11 Files & Stream I/O WEEK 12 Character I/O & Intro to Arrays WEEK 13 Arrays in One or More Dimensions WEEK 14 Character Strings WEEK 15 Standard String Class EXAM #3 CS 140
Grading 100 points - Laboratory Grade 400 points - Programming Assignments Grading Scale 900-1000 points A 800-899 points B 700-799 points C 600-699 points D 0-599 points F 100 points - Quizzes 400 points - Exams 1000 points total! CS 140
Late Policy andAcademic Misconduct THE LATE CS 140 STUDENT Only the student and the instructor may see the student’s actual code!!! Assignments will be accepted late only for documented medical reasons!!! CS 140
Chapter 1Introduction to Computers and C++ Programming Goals: • To introduce the fundamental hardware and software components of a computer system • To describe the role of compilers in high-level programming • To examine the use of algorithms in program design • To define the software life cycle • To introduce the C++ programming language
Computer Hardware: PC Output The monitor is the principal device for providing computer output to a user. Cathode Ray Tube Display: Uses electron guns aimed at hundreds of thousands of RGB phosphor pixels to render images Menu Button Left & Right Arrow Buttons: For moving between on-screen display options Select Button: For selecting on-screen options Power Light-Emitting Diode Power Button CS 140
Computer Hardware: PC Input Mouse: For simple interactive control input Keyboard: For textual, numerical, and complex control input Input devices are employed to provide the user with a means for supplying the computer with information. CS 140
Computer Hardware: PC Tower Front 5.25” Drive Bay Door: For memory expansion CD/DVD Drive: For optical memory CD/DVD Eject Button 3.5” Drive Bay Door: For memory expansion IEEE 1394 Port: For plugging in 4-pin devices Diskette Drive Diskette Eject Button Power Button USB Ports: For plugging in USB (Universal Serial Bus) devices, such as a digital camera CS 140
Computer Hardware: PC Tower Back Power Connector Cable Lock Slot Voltage Switch Case Cover Shipping Screw Mouse Port Microsoft Certificate of Authenticity: Contains Windows product key Keyboard Port USB Ports Serial Port (e.g., camera) Parallel Port (e.g., printer) Monitor Port USB Ports Ethernet/DSL/Cable Modem Jack Microphone Jack Headphones/Speaker Jack Audio Input Jack Add-In Card Retention Screw Telephone Jack Modem Jack CS 140
Computer Hardware: Memory Cache Memory Very fast (and very expensive) circuitry to speed up access to stored data. L2 is about twice the speed of RAM, while L1 is about 7 times faster. Central Processing Unit Register Memory cells built right into the CPU, holding data that the processor needs immediately. Virtual Memory An operating system technique for “pretending” that RAM is larger than it really is by making room for new data by moving data that hasn’t been accessed lately to the hard drive. Physical Random-Access Memory Integrated circuitry that provides fast access to stored information, but that perpetually requires refreshing. Read-Only Memory Integrated circuitry that contains non-volatile, unchangeable data. Hard Drive Permanently installed magnetic platters, with larger capacity and faster speed than removable drives. Basic Input/Output System Software stored on ROM, which serves as an interface between the hardware and the operating system. Network Storage Remote memory on other machines, with retrieval and update capabilities provided. Removable Drives Portable devices that facilitate sharing and securing data. Types include magnetic (e.g., floppy disks and Zip disks), optical (e.g., CDs and DVDs), and solid-state (e.g., flash-memory cards). CS 140
Computer Hardware: Processor Instruction Unit Prefetches & decodes instructions CPU The Central Processing Unit Branch Predictor “Guesses” next instruction to be executed Code Cache Fast storage for instructions Integer ALU Handles integer arithmetic Registers Stores data & instructions Execution Unit Manages instruction traffic 32-Bit Buses Simultaneously pipelines 2 data streams Floating-Point ALU Handles non-integer arithmetic 64-Bit Bus Conduit through which CPU/RAM traffic travels Data Cache Fast storage for data Primary Cache Fast memory for data & instructions that are anticipated to be needed Bus Interface Separates and forwards incoming data & instructions; collates outgoing data & instructions CS 140
Computer Software Application Software that performs high level operations (computation, graphics, etc.) Specify resulting response “Hey, App! key ‘P’!” Operating System Software that relays messages between application and hardware Contact appropriate hardware “Hey, OS! key ‘P’!” Hardware Direct access to circuitry, disks, mouse, keyboard, monitor, etc. For a game, send explosion sound to speaker and new pixel values to monitor Key ‘P’ struck Note that for a word processor application, the result would have been the same, except the final step would have involved inserting a ‘P’ character in memory and updating the screen display. CS 140
Low-Level Programming Languages A computer processor is not smart! Its vocabulary is limited to a simple “machine language” consisting of a small number of simple commands. Move this number over there! Move that number over here! Add this number to that number! Check to see if this number is zero! CS 140
Programming To get the computer to perform sophisticated operations, the programmer writes programs that tell the processor the sequence of primitive steps to take to get a result. 001001010110101010101010101010100001111110011100101111000001101010010010111010100010100100001101011001010100110101100101010010101001010010101011010010101000100101010101010101010101001010101001 Programming in machine language is a binary pain, so higher level languages have been developed to make the job of the programmer more efficient and more effective! CS 140
Compiling a High-Level Program A program caller a “compiler” is used to translate your “source program” (in a language like C++) into an “object program” (in your system’s machine language). LEXICAL ANALYSIS Split the source program into words like “void”, “x”, “>”, and “;”. PARSING Analyze the grammatical syntax of the source program (e.g., “if (x > y)” makes sense, but “if (x > ) y” doesn’t). CODE GENERATION Generate an equivalent program in machine language. #include <iostream> using namespace std; void main() { int x, y; cout << “Enter two integers: ”; cin >> x >> y; if (x > y) cout << x << “ is the largest!”; else cout << y << “ is the largest!”; return; } 110101000101100011000010010110110100010101011110010101011100000010011100101011001110101010111001010100101010101000000110110111011101010100111110101010101001001001010000010101010101000000101111100101100001011101010101010100010101111110010100100100101000 Source Program Object Program COMPILATION CS 140
Compiled Library Programs Linking and Loading After being compiled, the object program must be “linked” (i.e., connected to other compiled code from libraries, like math functions or input/output operators) and then “loaded” into main memory for execution. Source Program Object Program Linked Program COMPILE Executable Code LINK LOAD CS 140
47 28 56 30 61 19 Algorithms After defining a problem that the programmer wants the computer to solve, the programmer must first design an algorithm, a sequence of precise instructions that lead to a solution. Problem: Find the largest value in a list of numbers. 47 47 Algorithm: ? 1) Retrieve the list of numbers. ? 56 56 2) Consider the first number the largest value so far. ? 3) Starting at the second number in the list, compare the number in the list to the largest value so far; if it’s larger, then make it the largest value so far. ? LARGEST! 61 61 ? 4) After examining all of the numbers, announce the largest value so far - it’s the largest in the list!. CS 140
Another Algorithm Problem: Find the phone number of a specific person in an alphabetized phonebook. Algorithm: 1) Get the phonebook. 2) Crack what’s left of the phonebook open to the middle page. 3) Check to see if the name you’re seeking is on that page. If so, announce the phone number and you’re done!. Otherwise, throw away the “impossible” half of the phonebook, and repeat the process, starting at step #2. 4) If the entire phonebook is ever thrown out, then the person is unlisted! CS 140
The Software Life Cycle Specification Clearly state the purpose of the software, including full details of the problem being solved. Maintenance Respond to “bugs” and “sugs”, and determine when the software has become obsolete. Design Develop a solution to the problem, modularizing it and determining specific pre- and post-conditions. DOCUMENTATION!!! Testing Design test scenarios for individual modules, interaction between modules, and the entire program. Coding Program the modules using a bottom-up approach (with dummy drivers) or a top-down approach (with stubs). CS 140
Introduction to C++ Ancient Languages Fortran - Great for scientific computations COBOL - Great for business file processing Very special purpose, not good in general Old Languages C - General purpose language for UNIX systems Pascal - General purpose language for PCs Emphasis upon procedures instead of data Modern Languages C++ - Object-oriented version of C Java - Object-orientation with networking emphasis Emphasis upon the objects being manipulated CS 140
#include <iostream> // This library facilitates input & output. #include <math.h> // This library enables math functions, like sqrt. using namespace std; // Use the standard C++ naming conventions void main() // Every C++ program must have a "main" function. { // Opening brace to contain main's statements. double nbr; // Declare variable "nbr" to be an integer. double root; // Declare variable "root" to be a long real number. nbr = 2.0; // Set value of nbr to be 2. root = sqrt(nbr); // Calculate square root of nbr. cout << "The square root of "// Output a message to the memory file << nbr << " is " << root // associated with the monitor (i.e., cout), << endl << endl; // including nbr, root, and a skipped line. cout << "Enter a number: "; // Ask the user for a value for nbr. cin >> nbr; // Input from file associated with keyboard (cin). root = sqrt(nbr); // Calculate the square root of nbr's new value. cout << "The square root of "// Output a message to the cout file << nbr << " is " << root // concerning the values of nbr and root, << endl << endl << endl; // followed by two skipped lines. return; // Terminate the program's execution. } // Closing brace to indicate end of main function. A Sample C++ Program CS 140
Programming in Visual C++ .NET Our labs are set up with PCs that run Visual C++ .NET, Microsoft’s version of the language that contains many user interface features designed to facilitate writing, editing, compiling, building, and executing C++ programs. CS 140
Starting Visual C++ .NET CS 140
Creating a New C++ Project ProgramXYZ C:\temp CS 140
Creating a Program File ActualCode CS 140
Editing the Program // This program just says "Hi!" #include <iostream> // Permits input/output operations #include <cstring> // Permits string manipulation using namespace std; void main() { char yourName[30]; cout << "What's Your Name?" << endl; cin >> yourName; cout << endl << endl << "Hi, " << yourName << "!!!" << endl << endl; } Note that… Comments are Green C++ Keywords are Blue Regular Code is Black CS 140
Executing the Program At this point the programmer could edit the program further, copy it to a diskette, or submit it as a completed assignment via the student’s assigned dropbox. CS 140
Chapter 2C++ Basics Goals: • To introduce the concept of a variable and its assignment • To explore primitive input and output operations • To survey the primitive data types in C++ • To examine the use of arithmetic expressions • To define flow of control via conditionals and loops
Variables Variables are memory locations within RAM. Binary Address 00000000 RAM When a program variable is declared, adequate space in RAM is reserved for it. The variable is named with an identifier and can be given a value. That value is stored at its memory address, which is known as a pointer. RAM is divided into 8-bit segments called bytes. Each byte is numbered with a binary address. Variable of type char Variable of type int Binary Address 11111111 Variable of type double CS 140
Identifiers Variables names, or identifiers, must start with an underscore or an alphabetic symbol, and all of the remaining symbols must be alphanumeric or underscores. theValueThatIsUsedWhenIAmInAGoodMood x27 Cost_of_living _b4Value 8AMtemperature Largest Value amt_in_$ vice-president CS 140
Reserved C++ Keywords -Can’t Be Used As Identifiers! asm auto bool break case catch char class const const_cast continue default delete do double dynamic_cast else enum explicit extern false float for friend goto if inline int log long mutable namespace new operator private protected public register reinterpret_cast return short signed sizeof static static_cast struct switch template this throw true try typedef typeid typename union unsigned using virtual void volatile wchar_t while CS 140
Variable Declarations Variables must be declared before being used in a program. int count; float salaryPerWeek; char middleInitial; int nbr_of_rings, nbr_of_knocks; float MonPay, TuePay, WedPay, ThuPay, FriPay; double measurement1, measurement2; CS 140
Assignment Statements Variables may be “assigned” values via the assignment operator (=) in assignment statements. count = 0; salaryPerWeek = 40 * salaryPerHour; middleInitial = ‘W’; nbr_of_rings = 2 * nbr_of_knocks - 1; MonPay = TuePay = WedPay = 47.25F; ThuPay = FriPay = (float)62.75; measurement2 = measurement1 / count; CS 140
Initializing Variables Variables may be “initialized” in their declarations to possess specific values. int value = 0; float Radius = 16.00F; bool flag = false; double errorMargin = 0.00000003; char firstltr = ‘A’, lastltr = ‘Z’; int loserCount(0), winnerCount(0); float GPA(4.00F); CS 140
Output: Output: 1492 1997was great!I made a fortune! Output: Output: 1997 was great! I made a fortune! 97 Output: 97million dollars! Output to the Monitor via cout Values may be output to the monitor by means of output statements that use the output operator (<<) to stream to the output file cout. cout << 1492; int val = 97; cout << val; cout << 1997 << “was great!”; cout << “I made a fortune!”; cout << 1997 << “ was great!\n”; cout << “I made a fortune!”; cout << val << “million\n\ndollars!”; CS 140
// Example EscapeSequence #include <iostream> using namespace std; void main() { cout << "1Aa\azzz\aZZZ" << endl; cout << "2Bb\bzzz\bZZZ" << endl; cout << "3Cc\nzzz\nZZZ" << endl; cout << "4Dd\rzzz\rZZZ" << endl; cout << "5Ee\tzzz\tZZZ" << endl; cout << "6Ff\'zzz\'ZZZ" << endl; cout << "7Gg\"zzz\"ZZZ" << endl; cout << "8Hh\\zzz\\ZZZ" << endl; return; } Escape Sequences When a character value contains a character preceded by a backslash (\), then it represents a single symbol known as an escape sequence. \a Bell (alert) \b Backspace \n New line \r Carriage return \t Horizontal tab \' Single quotation mark \" Double quotation mark \\ Backslash CS 140
Formatting Real Number Output To ensure that real numbers are output with decimal points, an integer part, and a specific number of decimal places, the following lines should be included before outputting: Avoids Scientific Notation. cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(4); Shows Decimal Point & Trailing Zeros. Shows 4 Digits After Decimal Point. CS 140
//Example FormatFloats #include <iostream> using namespace std; void main() { cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(8); cout << 9876.543210 << endl; cout << 0.246813579 << endl; cout << 37.00000000 << endl << endl; cout.precision(4); cout << 9876.543210 << endl; cout << 0.246813579 << endl; cout << 37.00000000 << endl << endl; cout.precision(2); cout << 9876.543210 << endl; cout << 0.246813579 << endl; cout << 37.00000000 << endl << endl; return; } SampleReal Number Formatting Program CS 140
Input from the Keyboard via cin Values may be input from the keyboard by means of input statements that use the input operator (>>) to stream from the input file cin. //Example UserInput #include <iostream> using namespace std; void main() { int nbr; cin >> nbr; char init1, init2, init3; cin >> init1 >> init2 >> init3; float temp; cout << "Enter the temperature: "; cin >> temp; return; } CS 140
Data Types - Integers //Example IntegerTypes #include <iostream> #include <limits.h> // Defines integer limits. using namespace std; void main() { int NTjurA = 5, NTjurB = INT_MAX, NTjurC = INT_MIN; cout << "REGULAR INTEGERS:" << endl << NTjurA << endl << NTjurB << endl << NTjurC << endl << endl; long NNNNNTjurD = 5, NNNNNTjurE = LONG_MAX, NNNNNTjurF = LONG_MIN; cout << "LONG INTEGERS:" << endl << NNNNNTjurD << endl << NNNNNTjurE << endl << NNNNNTjurF << endl << endl; short nTjurG = 5, nTjurH = SHRT_MAX, nTjurI = SHRT_MIN; cout << "SHORT INTEGERS:" << endl << nTjurG << endl << nTjurH << endl << nTjurI << endl << endl; unsignedint UnNTjurJ = 5, UnNTjurK = UINT_MAX; cout << "UNSIGNED INTEGERS:" << endl << UnNTjurJ << endl << UnNTjurK << endl << endl << endl; return; } CS 140
Data Types - Floating-Point //Example FloatTypes #include <iostream> #include <float.h> // Defines float limits. using namespace std; void main() { float floA = 9.87654321F, floB = FLT_EPSILON, floC = FLT_MAX, floD = FLT_MIN; cout << "REGULAR FLOATS:" << endl << floA << endl << floB << endl << floC << endl << floD << endl << endl; double dubE = 9.87654321, dubF = DBL_EPSILON, dubG = DBL_MAX, dubH = DBL_MIN; cout << "DOUBLE FLOATS:" << endl << dubE << endl << dubF << endl << dubG << endl << dubH << endl << endl; longdouble ldI = 9.87654321, ldJ = LDBL_EPSILON, ldK = LDBL_MAX, ldL = LDBL_MIN; cout << "LONG DOUBLE FLOATS:" << endl << ldI << endl << ldJ << endl << ldK << endl << ldL << endl << endl << endl; return; } CS 140
Data Types - Characters and Booleans //Example CharacterTypes #include <iostream> using namespace std; void main() { char chA = 'T'; char chB = '\t'; char chC = '\\'; cout << chA << chB << chC << endl << chB << chC << chA << endl << chC << chA << chB << endl << endl; return; } //Example BooleanTypes #include <iostream> using namespace std; void main() { bool booX = true; bool booY = false; bool booZ = (532 > 738); cout << booX << endl << booY << endl << booZ << endl << endl; return; } CS 140
Type Incompatibilities //Example IncompatibleTypes #include <iostream> using namespace std; void main() { int NTjurA = 9.635F, NTjurB = 9.635, NTjurC = '&’, NTjurD = true; cout << NTjurA << '\t' << NTjurB << '\t' << NTjurC << '\t' << NTjurD << "\n\n"; float floE = 65, floF = 65.34, floG = 'Q’, floH = false; cout << floE << '\t' << floF << '\t' << floG << '\t' << floH << "\n\n"; double dubI = 14, dubJ = 14.92F, dubK = '?’, dubL = true; cout << dubI << '\t' << dubJ << '\t' << dubK << '\t' << dubL << "\n\n"; char chM = 3, chN = 3.1416F, chO = 3.1416, chP = true; cout << chM << '\t' << chN << '\t' << chO << '\t' << chP << "\n\n"; bool booQ = 467, booR = 467.927F, booS = 467.927, booT = 'w'; cout << booQ << '\t' << booR << '\t' << booS << '\t' << booT << "\n\n"; return; } //Example IncompatibleTypes #include <iostream> using namespace std; void main() { intNTjurA = 9.635F, NTjurB = 9.635, NTjurC = '&’, NTjurD = true; cout << NTjurA << '\t' << NTjurB << '\t' << NTjurC << '\t' << NTjurD << "\n\n"; float floE = 65, floF = 65.34, floG = 'Q’, floH = false; cout << floE << '\t' << floF << '\t' << floG << '\t' << floH << "\n\n"; double dubI = 14, dubJ = 14.92F, dubK = '?’, dubL = true; cout << dubI << '\t' << dubJ << '\t' << dubK << '\t' << dubL << "\n\n"; char chM = 3, chN = 3.1416F, chO = 3.1416, chP = true; cout << chM << '\t' << chN << '\t' << chO << '\t' << chP << "\n\n"; boolbooQ = 467, booR = 467.927F, booS = 467.927, booT = 'w'; cout << booQ << '\t' << booR << '\t' << booS << '\t' << booT << "\n\n"; return; } The compiler gives warning messages for each highlighted statement, but allows the program to run nevertheless. CS 140
//Example FloatArithmetic #include <iostream> using namespace std; void main() { double interestRate = 0.075; double balance = 278.93; double depositAmount = 309.14; double withdrawalAmount = 416.72; int daysUntilPayday = 19; double interestEarned; double dailyAllowance; balance = balance + depositAmount - withdrawalAmount; interestEarned = interestRate * balance; balance = balance + interestEarned; dailyAllowance = balance / daysUntilPayday; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "Until payday, you\'ll have to\nget by on $" << dailyAllowance << " per day!" << endl << endl; return; } Floating-PointArithmetic There are four arithmetic operators for floating-point numbers. + Add - Subtract * Multiply / Divide CS 140
//Example IntegerArithmetic #include <iostream> using namespace std; void main() { const int PiecesPerLargePizza = 8; const int PiecesPerSmallPizza = 4; int nbrOfLargePizzas; int nbrOfSmallPizzas; int nbrOfConsumers; int nbrOfPieces; int piecesPerConsumer; int nbrOfSparePieces; cout << "How many large pizzas? "; cin >> nbrOfLargePizzas; cout << "How many small pizzas? "; cin >> nbrOfSmallPizzas; cout << "How many consumers? "; cin >> nbrOfConsumers; nbrOfPieces = nbrOfLargePizzas * PiecesPerLargePizza + nbrOfSmallPizzas * PiecesPerSmallPizza; piecesPerConsumer = nbrOfPieces / nbrOfConsumers; nbrOfSparePieces = nbrOfPieces % nbrOfConsumers; cout << "\nOn the average, " << piecesPerConsumer << " pieces each.\n" << "(with " << nbrOfSparePieces << " pieces left over!)" << endl << endl; return; } IntegerArithmetic There are five arithmetic operators for integers. + Add - Subtract * Multiply / Integer Divide % Modulus CS 140
Arithmetic Precedence Rules When evaluating arithmetic expressions, C++ uses specific precedence rules to determine which operators should be executed in which order. • Parentheses take the highest precedence • Multiplication, division, and modulus come second. • Addition and subtraction take the lowest precedence. • Precedence ties are handled in left-to-right fashion. 100 - 5 * 4 + 75 = 100 - 20 + 75 = 80 + 75 = 155 (100 - 5) * 4 + 75 = 95 * 4 + 75 = 380 + 75 = 455 100 - 5 * (4 + 75) = 100 - 5 * 79 = 100 - 395 = -295 CS 140
Additional Assignment Operators Certain shorthand operators can be used when a variable’s value is being altered by performing a simple operation on it. value = value + otherValue; x = x - y * z; value += otherValue; x -= y * z; probability = probability / 100; probability /= 100; dayOfYear = dayOfYear % 365; salary = salary * 3.5; dayOfYear %= 365; salary *= 3.5; CS 140
Increment and Decrement Operators Incrementing or decrementing a numerical value by one can be done with an even simpler mechanism. number = number + 1; number++; ++number; ctdown = ctdown - 1; ctdown--; --ctdown; //Example IncrementDecrement #include <iostream> using namespace std; void main() { int nbr = 57; cout << nbr << endl; cout << nbr++ << endl; cout << nbr << endl; cout << ++nbr << endl; cout << nbr << endl << endl; return; } The order in which the increment or decrement operator is applied will determine whether the operation is applied before or after a value is returned. CS 140
Branching There may be circumstances in a program when the next step to perform depends on a particular condition. Did the hourly employee work over 40 hours? Is the chosen WoF letter anywhere in the puzzle? No No Yes Yes Pay 40 hours at regular rate & extra hours at time-and-a-half Pay total hours worked at regular rate Increment the player’s winnings by the dollar amount times the number of occurrences of the letter Proceed to the next player CS 140