Lecture slides 1
Computer Science 31 with Rohr at University of California - Los Angeles
About this note
By: Anonymous
Textbook:
Absolute C++ Value Package (includes MyCodemate Student Access Kit)
Created: 2009-01-24
File Size: 81 page(s)
Views: 23
Textbook:
Absolute C++ Value Package (includes MyCodemate Student Access Kit)Created: 2009-01-24
File Size: 81 page(s)
Views: 23
About StudyBlue
STUDYBLUE makes things that make you better at school.
Things like online flashcards with photos and audio.
Things like personalized quizzes and friendly reminders about when (and what) to study next.
Think of it as a digital backpack™: access to all of your study materials online and on your phone.
STUDYBLUE exists to make studying efficient and effective for every student, for free. Join us.
“Simply amazing. The flash cards are smooth, there are many different types of studying tools, and there is a great search engine. I praise you on the awesomeness.”
Dennis
Dennis
Sign up (free) to study this.
CS 31: Introduction to Computer Science I Topic 1 Introduction to Programming Introduction to Programming PROGRAMMING PROCESS EXAMPLE Driving a Car Introduction to Programming Programming Process Example Types of Contol Sequential: Step-by-step Selection: One of choices Repetition: Repeated step Program Control Flow Sequential One Step at a Time Begin End Compute Compute Compute Compute Program Control Flow Selection One of Choices Compute Compute Condition Begin End Program Control Flow Repetition Repeated Step Begin End Condition Initialize Compute Update Program Control Flow Composition Replace any Sequential Step with a Selection or a Repetition Program Control Flow Composition Example Guess a Number Between 0 and 100 Program Control Flow Example Guess a Number Between 0 and 100 Set G to 50 G = N? N Y Done: G is N G < N? N Y Add C to G Set C to 25 Subtract C from G Divide C by 2 Start G is the current guess C is the current change N is the chosen number Introduction to Programming Programming Steps Specification: Description of the Task Analysis: Understanding the Task Test Data: Complete Set of Tests Design: Data and Algorithms Implement: Write the Program Test and Debug: Make It Work Algorithm Design Tools Flow Charts Pseudocode Algorithm Design Flow Charts Graphical Symbols Easy to Visualize Flow Difficult to Draw in Comments Examples: Flow of Control Diagrams Algorithm Design Flow Chart Example Guess a Number Between 0 and 100 Set G to 50 G = N? N Y Done: G is N G < N? N Y Add C to G Set C to 25 Subtract C from G Divide C by 2 Start G is the current guess C is the current change N is the chosen number Algorithm Design Pseudocode Structured Natural Language Easy to Understand Easy to Use in Comments Example: Following Program Comments Algorithm Design Pseudocode Example Guess a Number Between 0 and 100 1. Set the guess to 50. 2. Set the change to 25. 3. If the guess is the number, DONE! 4. If the guess is less than the number, add the change to the guess. 5. If the guess is greater than the number, subtract the change from the guess 6. Divide the change by 2. 7. Go to Step 3. Algorithm Design Pseudocode Example // Get the input values // If the input values are not valid // Display an error message // Else // For each input value // Calculate the result // Display the results Programming Basics Programming Practices Design before implementing Use comments liberally Develop incrementally Reuse functions Start early Programming Basics Learning to Program Program Program Program Programming Language Levels Machine vs. Human Machine Language Assembly Language High-Level Language Natural Language Programming Language Levels Machine Language Language of the Computer Consists of 0?s and 1?s Machine Dependent Lowest Level No Limits Programming Language Levels Assembly Language Simplified Computer Language Consists of Symbols and Operations Machine Dependent Second Lowest Level No Limits: Same as Machine Language Programming Language Levels High-Level Language Mathematical Language Consists of Mathematical Statements Machine Independent (Mostly) Highest Level (Except Natural) Limited Capability: Not All Operations Programming Language Levels Uses Machine Language: Debugging Only Assembly Language: Critical Tasks High-Level Language: Most Common Natural Language: Not Yet Programming Language Levels Examples High-Level: Sum = First + Second; Assembly: LOAD First ADD Second STORE Sum Machine: 210A = 0010000100001010 410B = 0010000100001011 310C = 0011000100001100 Compilation Process High-Level ? Machine Enter high-level program Translate to Assembly Language Translate to Machine Language Combine with Library Functions Load into Computer Run Program Compilation Process Assembler Compiler Linker Loader Source Files C++ Files Library Files Object Files Obj/Asm Files Execute File Main Memory Asm Obj Compilation Process User Steps Enter high-level program with editor Compile the program Fix the errors Run the program Fix the errors Complete the documentation High-Level Languages Many Types FORTRAN: First, Mathematical COBOL: Early, English-Like LISP,SNOBOL: Special-Purpose ADA: DOD Standard C: Operating System Implementation C++: Object-Oriented Programming High-Level Languages C/C++ C: Invented to Program UNIX O. S. General Purpose C++: Enhancement of C Object-Oriented Programming Language for this Course Functions and Programs Function A single unit of computation Accomplishes one thing May use other functions May produce a result Sequence of statements Functions and Programs Program Implementation of a complete solution Solves a specified problem Includes input and output May use functions C++ Basics Keywords/Identifiers Letter or _ followed by letters, _, & digits Case sensitive Unlimited length: Compiler may use 32 Don?t begin with _: Used by compiler Multiple words: Capitalize or use _ Constants: Capitalize Requirements Conventions C++ Basics Keywords/Identifiers Identifiers: Names of data Keywords: Identifiers reserved for specific language use Examples: x, data1, myName, ab123c, big_variable, v1234 Invalid: 3z, XY 3, #a3 C++ Basics Data Types Integer: int Real: float ? Limited precision double ? Extended precision Character: char ? One character only Logical: bool ? True or False Hardware Software C++ Basics Integer Data Discrete values Counting numbers Positive, negative, or zero Values specified by decimal digits No decimal point Examples: 24, -80, 0, 16 C++ Basics Real Data Continuous values Positive, negative, or zero Values specified by decimal digits Optional decimal point Optional scientific notation Examples: 3.14, -25.8, 0, 123, -3.45e8 C++ Basics Boolean Data True or False only true and false are keywords in C++ No Boolean data type in C False represented by zero value True represented by any nonzero value True value of one generated by compiler C++ Basics Character Data Single items of a character set Machine-dependent: Based on hardware ASCII/ANSI EBCDIC Unicode Characters are enclosed in single quotes Examples: 'A', 'z', '3', '*', ' ', '~' C++ Basics String Data Zero or more items of a character set Can be empty (No characters) Can be one character Can be multiple characters Characters are enclosed in double quotes Examples: "A String", " ", "", "AbC!#21" C++ Basics Characters vs. Strings Characters: Built-in to C++ char data type Single character only Enclosed in single quotes Strings: Available using #include string string data type Zero or more characters Enclosed in double quotes C++ Basics Constants and Variables Elementary unit of information Single data item Name is an identifier Type is specified in declaration Constant cannot be changed Variable is set by computation C++ Basics Literals Constant unit of information Single data item Specific value Integer: Decimal number; No decimal point Float: Decimal number; With decimal point Character: One character of set C++ Basics Literal Examples Integer: 80 Float: 8.42F, 8.42f, 8.42E2F, 8.42e2f Double: 16.24, 1.624E1, 1.624e1 Long Dbl: 8.42L, 8.42l, 8.42E2L, 8.42e2l Character: '*' String: "String Literal" C++ Basics Escape Sequences Characters with special meaning Specified in C++ with preceding backslash Limited set \n Newline \' Single Quote \" Double Quote \\ Backslash \0 Character String (Null) Terminator C++ Basics Data Declaration Must be declared before use Give compiler information about the data Name Type Size (Not for elementary data types) C++ Basics Data Declaration Examples int i; int x1, x2, abc; float f1, volts, power; double weight, v3, inp; bool state; char ch, letter; C++ Basics Data Initialization Must be initialized before first use Two ways to initialize Declaration Assignment C++ Basics Data Initialization Examples int i = 0; int x1 = 3, x2 = -5, abc = 3 * 5 + 9; float f1 = 0, volts = 120.5, power = 0.1; double weight = 100, v3 = 0.03, inp = -2; bool state = false; char ch = '*', letter = 'X'; C++ Basics Arithmetic Operators Unary syntax operator Operand: -value Binary syntax Operand operator Operand: a + 5 Parentheses (number) C++ Basics Arithmetic Operators + Addition - Subtraction * Multiplication / Division % Modulus, Remainder C++ Basics Division Two integer operands ? Integer result Example: 12 / 5 = 2 Two real operands ? Real result Example: 12.0 / 5.0 = 2.4 Mixed operands ? Real result Example: 12.0 / 5 = 2.4 C++ Basics Data Hierarchy int/char float double long double C++ Basics Increment and Decrement ++ Preincrement/Postincrement Preincrement: Increment before use Postincrement: Increment after use -- Predecrement/Postdecrement Postdecrement: Decrement before use Postdecrement: Decrement after use C++ Basics Expressions Operands and operators Arithmetic calculations Type conversion where allowed Implicit: Automatic Explicit: Cast C++ Basics Expression Examples var1 item1 * 5 a * (b + c) 0.5 * base * height x * (p * q / (m ? n) + t) var = (num / div) * div C++ Basics Automatic Type Conversion Promotion: No loss of accuracy Example: Integer ? Float 10 ? Float variable becomes 10.0 Demotion: May lose accuracy Example: Float ? Integer 10.1 ? Integer variable becomes 10 C++ Basics C++ Statements Terminated by semicolon One action Assignment Input/Output Control C++ Basics Assignment Statement Set the value of a variable Variable name (identifier) on left side = operator Value expression on right Examples: value = 1.23; data = base + 5; C++ Basics Assignment Statement Order of evaluation not guaranteed a + b is the same as b + a Problem: n + (++n): Avoid this use Shorthand notation for some statements Variable value changed by +, -, *, /, or % Form is variable += expression; Same as variable = variable + expression; C++ Basics Assignment Examples ans = factor1 * factor2; q = v1 + v2 * (v3 + v4 / v5); d2 += 16; z *= size1 ? base; a *= PI * r; r %= d; C++ Basics Basic String Operations Declaration: string string1; string string2, string3; Initialization: string string4 = "A String"; Assignment: string1 = ""; string2 = "Another string"; string3 = string4; C++ Basics Console Input/Output Uses iostream library #include using namespace std; Input: cin stream extraction operator Output: cout stream insertion operator C++ Basics Console Input: cin Reads values from keyboard (stdin) Values separated by white space Space, tab, or newline Lines ended with newline () Examples cin >> myData; cin >> firstValue >> secondValue; C++ Basics Console Input: cin Input values can be on multiple lines Each input variable receives one item Examples Single line: 297 3.15 -12.574 Multiple lines: 297 3.15 -12.574 C++ Basics Console Input: cin.ignore() May need to advance to next line Must skip over newline at end of line cin.ignore provides the capability Skip up to 10000 character to newline Stop on first character of next line cin.ignore(10000, '\n'); C++ Basics Console Output: cout Displays values on the screen (stdout) Strings, values, and expressions Multiple items not separated End lines with \n or endl (preferred) Example: cout << "Example" << endl; C++ Basics Console Output: cout Number formatting is automatic Compiler decides what format to use Can be explicitly controlled: e.g. 123.45 cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); C++ Basics Console Output: cout Output lines ended explicitly No new line unless specified One statement: Multiple output lines cout << a << endl << b << endl; Multiple statements: One output line cout << a; cout << " "; cout << b << endl; C++ Basics Console Output: cout Use cout for text prompts cout << "Enter a value: "; cin >> myValue; End final output with end of line cout << endl; Puts subsequent output on next line C++ Basics Console Output: cerr Alternate output to screen (stderr) Works like cout Can be redirected to different file Example cerr << "Error message!" << endl; C++ Basics Console I/O Example cout << "Enter data value:"; cin >> value; cout << "The value is " << value << endl; C++ Basics More String Operations String length: string.length() or string.size() Single character extraction: string[0] Substring: string.substr(start) Substring: string.substr(start, count) String output: cout << string; String input: cin >> string; (1 Word) String input: getline(cin, string); (1 Line) C++ Basics String Operation Examples String st = "Data string"; st.length() or st.size() is 11 st[0] is 'D' st[6] is 't? st[11] does not exist st.substr(3) is "a string? st.substr(8,2) is "in? st.substr(9,3) is illegal C++ Basics String Input cin >> string; Reads one word: Up to white space Stops on white space character getline(cin, string); Reads one complete line Stops on first character of next line C++ Basics String Input Examples Input line: This is some text string st1, st2, st3; getline(cin, st1) puts "This is some text" in st1 and stops at the start of the next line cin >> st2; cin >> st3; puts "This" in st2 and "is" in st3 and stops at the space after "is" C++ Basics Libraries Provide built-in capabilities Included by preprocessor Made available with #include statement Examples #include Stream input/output #include Strings #include exit, rand, and other C++ Basics Namespaces Provide "last names" for identifiers Resolve name conflicts with libraries Standard libraries use std Namespace name specified with using Example: using namespace std; C++ Basics Comments Two types can be intermixed Single line comments (preferred) Begin with // End at end of line Multiple line comments (alternate) Begin with /* End with */ C++ Basics Comment Examples // This is a single-line comment x = 1; // This is a partial-line comment /* This is a mulitple-line comment There can be many lines This is the last line of the comment */ C++ Basics Programming Style Write understandable code Use meaningful data names Use names for constants Use comments liberally Protect against user errors UPDATES Constant & Variable Examples More Example Programs
Back
Next
About this note
By: Anonymous
Textbook:
Absolute C++ Value Package (includes MyCodemate Student Access Kit)
Created: 2009-01-24
File Size: 81 page(s)
Views: 23
Textbook:
Absolute C++ Value Package (includes MyCodemate Student Access Kit)Created: 2009-01-24
File Size: 81 page(s)
Views: 23
About StudyBlue
STUDYBLUE makes things that make you better at school.
Things like online flashcards with photos and audio.
Things like personalized quizzes and friendly reminders about when (and what) to study next.
Think of it as a digital backpack™: access to all of your study materials online and on your phone.
STUDYBLUE exists to make studying efficient and effective for every student, for free. Join us.
“Simply amazing. The flash cards are smooth, there are many different types of studying tools, and there is a great search engine. I praise you on the awesomeness.”
Dennis
Dennis