Day 2: Language hierarchyHistory of C++Major pieces of softwareOur first programsHello world programDay 3CommentsHeader commentHeader fileint main()int main()Another programVariablesI/OAnother programRules for C++ identifiersC++ identifiersDay 4: Choice of variable namesAssignmentVariablesPrimitive typesArithmetic operatorsPrecedenceDay 5: DebuggingThoughts about HW1FundamentalsIntegersfloatdoublecharboolOutput settingsDay 6: example programBranchingif-else exampleAnother if-else exampleSyntaxSyntax of if-elseExamplesAnother example programBoolean expressionDay 7Dangling else problemShorthand if-elsewhileMore shorthandSyntax/semantics of whileAnother exampleHW2 discussiondo whileSyntax/semantics of do-whileDay 8: Subtleties of Boolean expressionsforsyntax of forMore about for loopsfactorialDay 9: Examples using forSolution of HW1Built-in functionsType castingType casting (cont.)Day 10: User-defined functionsArguments and parametersReasons for writing a functionReasons (cont.)TerminologyDay 2: Language hierarchyMachine languageAssembly languageProgramming languagez Object-oriented: C++, Java, …z Functional: Lisp, …z Logic: Prolog, …HTML is not a programming language, it is a markup languageDesigning rather than using softwareHistory of C++C: language in which to implement the operating system Unix (Dennis Ritchie)C++: object-oriented extension; Bjarne StroustrupJava: OO language designed for the webz Sacrifice execution speed for development speedMajor pieces of softwareOperating system (Unix, Linux, NT)Compiler (gcc, Visual C++)Text editor (emacs, Word)Hardware:z keyboard/cpu/screen/memorySoftwarez input/program/output/variablesOur first programsSimplest C++ programCompiling C++z New: C++ sourcez Compile, build, executez Build = link = TV dinnerz Save on floppy (or C:temp)Hello-world programHello world program#include <iostream.h>int main(){cout << “Hello, world.\n”;return 0;}Day 3Lab assignment: 145 or 430 CampbellHandout of hello-world program, with header commentCommentsA comment is ignored by the compiler.Multi-line comment: anything in between /* and *//* This is a comment. It can straddle two lines.*/Single-line comment: everything on line after // is ignored// This is a single line comment./*****************************This is a good way to highlight and separate a comment.********************************/Header commentImportant to explain the program in comments, for yourself and for othersYou will forget what code means: add a comment to describe nontrivial codeAlso important to document creation of program and its purposeE.g., easier to debug if you know when something was changedHeader file#include <iostream.h> adds the file ‘iostream.h’ at this positioniostream: input/output streamWhenever you want to use I/O, must include this file‘introduces’ I/O library so that compiler will understand I/O commands when they are encountered<> : system file“” : user-supplied fileint main()int main(): main functionEvery program must contain a main function, called ‘main’The program starts here.int main()int: return type is integerEvery function must return somethingNote ‘return 0’ at the endAnother programConsider computing the area of a rectangle.Need input of length and width.Need to store length and width.Variablesint length;length = 5;A place to record a value for future referencean abstraction of data z similar to a variable in mathAlso, a location in memoryz not similar to a variable in mathMust declare before usingI/Ocoutz cout << “output string”z cout stands for screencinz cin >> variableThatStoresInputz cin stands for keyboardPrompt user before receiving input.Another programCompute area of a rectangleRules for C++ identifiersContain only letters, digits or _z No !,+,&,^…Start with letter (or _)Not a reserved keywordz Not int, float, main, return, …z highlighted in Visual C++ and emacsC++ identifiersCase-sensitivez N and n are different variablesNo limit to length, in theory; very long limit, in practicez Make it short but meaningfulDay 4: Choice of variable namesCounters i,j,kNumber of things: n, nPtMulti-word namesz Spaces cannot be introducedz Capitalize each word except firstz centerOfCircle, goalPerGame, endTangentz I prefer this to center_of_circleUse abbreviations, intelligentlyAssignmentlength = 5;= is not equality (== is equality)z n = 2*n;n = 2*n;z l-value vs. r-valuez l-value: interpreted as addressz r-value: interpreted as contents of addressa = b; is not at all the same as b = a;i = i+1; (incrementing) is given shorthand i++;VariablesVariables must be z Declared before they are used in any way, ANDz Initialized before they are referencedz C++ does not initialize for you!z Assumes you are smartz Has unpredictable garbage value until initialized2 standard initializations:z By inputz By assignment statementCan initialize as you declare: int length=5;Primitive typesType checking is important in C++.Every variable must have a type.int, float, char, … are called primitive types.Arithmetic operators+,-,*,/,% (no exponentiation operator)%: remainder from quotient of two integersDon’t forget to use *z (x+2y)(3x-4y): wrongz (x+2*y)*(3*x-4*y): rightInteger division truncates: int a; a = 5/3;PrecedenceInterpretation of 1+2*3Precedence as magnet strengthHighest: unary – and unary +2ndhighest: * , /, %3rdhighest: + and -Use parentheses () to override preference2+3*4+5Day 5: DebuggingAdmiral Grace Hopper (Cobol) and Eniac bug3 types of errorSyntaxLogicz One that creates wrong result immediatelyz One that hides and only begins evident later, or changes unpredictablyCompile-time vs. run-time errorFinding an error in Visual C++Output statements to trace program for debuggingThoughts about HW1Don’t repeat yourselfStore all values in variables before outputtingdebuggingFundamentalsIntroduce yourselfz E.g., variables declared before used; iostream.hAvoid repeating code:z E.g., need sum both in sum and average in HW1z Rather than calculating a value twice, calculate it once and store in a variable (so that 2ndtime you can read variable rather than recalculating)z For larger calculations, encapsulate in a function and call function several times (rather than repeating code over and over)z Use a library if the task is standardIntegersintz Memory allocation; bits/bytes; binary rep; powers of 2; largest integer stored; sign bitz Typically 2 bytes z Range for 2 bytes: +- 2^15z short vs long [ use int ]floatfloat radius; radius =
View Full Document