720 likes | 907 Views
CS3101-2 Programming Languages – C++ Lecture 1. Matthew P. Johnson Columbia University Fall 2003. Welcome. CS3101-2 Programming Langs: C++ 1 credit, 1/3 semester same bang/buck as usual (3000-level) 6 weeks, in-class final exam 2-hour sessions First class: overview of Unix, C++
E N D
CS3101-2Programming Languages – C++Lecture 1 Matthew P. Johnson Columbia University Fall 2003 CS3101-2, Lecture 1
Welcome • CS3101-2 Programming Langs: C++ • 1 credit, 1/3 semester same bang/buck as usual (3000-level) • 6 weeks, in-class final exam • 2-hour sessions • First class: overview of Unix, C++ • Magical mystery tour • Others: one or two topics, in depth CS3101-2, Lecture 1
Course Requirements • Assumes previous programming experience • Probably Java or C for most • But neither is required • Will, though compare and contrast between C/C++/Java • O(5) homeworks – 70% • Programming & written • Final exam – 25% • Participation/quizzes/attendance – 5% • Class attendance is required • You’re responsible for all material from lecture • Class time is finite • Responsible for all assigned reading • NB: some material may be covered in lecture xor reading • Lectures may have non-PPT portions • PPTs will be online to complement lecture CS3101-2, Lecture 1
Contact Info • Class page: http://www.columbia.edu/~mpj9/3101-2 • PPTs • In-class examples • Link to CourseWorks, other lecture notes, etc. • Me: mpj9@columbia.edu • OHs: Saturdays, 1-3, in 251 Mudd lab • Check classpage for updates • TA: Jacob Porway • jmp204@columbia.edu • OHs: see web • Check http://ta.cs.columbia.edu for updates • Feedback is good! • Prepend “CS3101-C++” to subject lines! CS3101-2, Lecture 1
Textbook • For the C course, I like: • The C Programming Language (K&R) • Classic text • By creators of C • Short, pretty cheap, and rigorous CS3101-2, Lecture 1
Textbook • This class is C++ • Exists the book: • The C++ Programming Language • By creator of C++ • Rigorous, but difficult, expensive, and long (+1000 pages) CS3101-2, Lecture 1
Textbook • So we’ll use: • Practical C++ Programming • O’Reilly • Available Labyrinth, Papyrus, Amazon and B&N (links on class page) • Not too difficult, not too long (~500 pages) • Lectures will sometimes follow text, sometimes not CS3101-2, Lecture 1
IMPORTANT • I’ll repeat your questions before answering them, for CVN • If I forget, remind me! • Before I’ve answered • Get participation XC CS3101-2, Lecture 1
Rest of this class • Description & History of C/C++ • Intro to Unix • 0th Homework • C++ Tutorial CS3101-2, Lecture 1
(Pre)History of C++ • BCPL (Basic Combined Programming Language), Martin Richards, 1960s • B (typeless), replaces BCPL, Ken Thompson, 1970 • C (fairly strongly typed), successor to B, Dennis Ritchie, Bell Labs, early 1973 • C-With-Classes, Bjarne Stroustrup, 1979 • C++, Bjarne Stroustrup, Bell Labs, 1983 • ANSI C standardization (K&R, second edition), 1988 – … • Java, James Gosling, Sun, 1995 • C#, Microsoft, about 15 minutes ago • C++, Java, C# conserve (much) C syntax CS3101-2, Lecture 1
Description of C • General-purpose language • “Procedural”: functions/procedures (not functional!) • “Imperative”: list of imperatives (commands) • Mid-level • Tricky syntax, but quite small; short learning curve • C programs ~ Hemingway’s “tight, athletic prose” (Scribner blurb) • CU (and others) jumped from C to Java, skipping C++ • Cross-platform language, single-platform compilers (unlike Java) • Char-based CS3101-2, Lecture 1
Why C? • Prior to C, two broad types of languages: • Applications languages • High-level • COBOL, etc. • Portable but inefficient • Systems languages • Low-level • Assembly • Efficient but not portable • Goal of C: fast and portable • How: abstract above hardware arch, but not far! CS3101-2, Lecture 1
Why not C? • But: C is procedural (imperative) • Limited encapsulation • Programs = algorithms, data structures • Relationship between (/tying together of) algs and data they take is manual • Intelligence tends to be widely distributed/decentralized • 10th Amendment/States rights • Large programs hard to maintain/understand • Dynamic memory management is entirely manual • Need memory at run-time must request right number of bytes, interpret correctly • When finished, must remember to free that memory • Fast (in part) because there’s so little error-checking • ar[-2] or ar[100000] doesn’t throw an exception (doesn’t support exceptions!) • just gives you read/write access where that elm would be • C simpliciter is multi-platform-compilable but, e.g., graphics/GUI libraries tend to be platform-specific • No types for boolean (just ints), string (just char arrays), etc. • Not multi-threaded • Everything in same namespace ( naming collisions) • All arg-passing is pass-by-value; must simulate pass-by-reference with pointers CS3101-2, Lecture 1
Why Java? • Java is object-oriented • Has garbage-collection • Prevents making of many mistakes legal in C • Stricter typing so prevents many mistakes legal in C/C++ • J has much more error-checking • Primitive array replaced with (implicit) array object • J has exceptions • a[-2] throws exception • Is multi-platform-runnable (compile once; run anywhere) • Has types for boolean, string*, etc. • Is multithreaded • Has packages for organizing classes to prevent naming collisions • All objects automatically pass-by-reference; all primitives pass-by-value • Java is great • Very sexy for a long time, throughout boom • Lots of universities skipped from C to Java • Q: any reason to learn C++, then? CS3101-2, Lecture 1
Why C++? • A: Yes! • Java is very elegant, but it doesn’t compile to machine code • It’s very slow! • O(20) times slower than C/C++ • Compiled Java programs aren’t executables, they’re .class’s • They’re run not by OS but by JVM (java.exe) • Big idea: write JVM for web browser on every platform people use (i.e., all 3 of them) • any browser can run your applet • Notice: winword.exe, netscape.exe, etc., aren’t class files • Almost all “real” PC/Mac software, Windows itself, many JVMs were written in… • C++ • C++ has a steeper learning curve • so Java is the dept’s default lang, learned over a semester or two • Instead, we’ll learn C++ in 6 weeks CS3101-2, Lecture 1
What is C++/OOP? • C++ is the successor language to C • At a high level: C++ ~= C + OOP • Big idea of OOP: organize the world into intelligent objects • The objects aren’t good at trivia questions • They’re able to solve the problems relevant to themselves • Plato: “carve nature at its joints” • Concepts/sorts of things in world classes • Particular examples of those things objects • Each object has • its own data • Access to functions applicable that data • Big argument in favor of OOP over imperative languages: • An imper program is just an abstracted list of assembler commands, which is just an abstracted list of machine code commands written with the machine in mind • An OOP program is an abstraction of the concepts and problems you’re interested in written with your interests in mind CS3101-2, Lecture 1
OOP Concepts • Object legislates how its data may be accessed (encapsulation) • Some data may be accessible to others, some not • Data can only be modified in specified ways easier to ensure correctness • One class may be a special case of another (inheritance) • Rectangle is like a square, plus a second (possibly) distinct value • Colored-Rectangle is like a rectangle, plus the concept of color • Different classes in a hierarchy behave correctly (polymorphism) • shape.getArea() len*wid, if shape is a rectangle • shape.getArea() PI*r2, if shape is a circle • Most important of three: encapsulation CS3101-2, Lecture 1
Why C++? • C++ is OOP and procedural • No garbage collection, but dynamic memory simpler than in C • Both safer and not safer • Still has prim. array, but also has safer/slower array-like objects • Somewhat stricter typing than in C • New casting somewhat safer, but old casting still unsafe • Still only cross-platform-compilable, for most char-based programs • Standard Template Library includes many important data structs & algs • Like Java, has a boolean type and a string class • Still not multi-threaded • Has namespaces to prevent naming collisions • Can pass objects by reference • Also, can pass both objects and primitives by value, by reference, or by pointer • Supports function overloading (like Java) • Supports operator overloading (unlike Java) • Supports default function parameter values • Has multiple inheritance (only single inheritance in Java) • Has templates (“generics” in Java 1.5) • Many other changes we’ll see as we go along CS3101-2, Lecture 1
What is C++? • C++ is (almost exactly) a superset of C • C concepts are also C++ concepts • Although many have C++ replacements/analogs • (Almost) Every valid C program is a valid C++ program • The set of C++ programs contains the set of C programs • Exceptions: use of new C++ keywords as var names, e.g. • One strategy for learning C++: • Learn C • Learn (C++ - C) • For most part, we won’t follow this strategy in this class • If you took 3101-1, then you’re following this strategy this semester • In general, we introduce concepts as they appear • Comparing/contrasting with C, Java analogs as applicable • Will be some overlap at beginning – basic syntax, shared concepts • Overlap should diminish rapidly • NB: Many tasks can be done C-style or C++-style • In general, lose points for C-style if C++-style has been covered CS3101-2, Lecture 1
Unix • You don’t have to do your hw on newcunix • Can download for free Borland C++ from class page • But hw must be submitted with newcunix submit script; • hw must compile on Unix (with g++) to be graded • Can Sftp and recompile before submitting • Non-compiling hw will not be graded! • Editors on newcunix: Emacs, Pico, etc. CS3101-2, Lecture 1
Programming with Emacs/g++ CS3101-2, Lecture 1
g++ Tips • Compilers on newcunix: • CC (default compiler; not “cc”) • g++ 3.3 (GNU’s C++ compiler) • Ensure you use the right version • Add these lines to your .profile (in your ~) • export PATH=/opt/gcc-3.3/bin:$PATH • export LD_LIBRARY_PATH=/opt/gcc-3.3/lib:$PATH • Instructions will be online • Compile with warnings on –Wall • Fix the first error first • One typo can cause huge numbers of errors • Send lots of messages to screen if confused CS3101-2, Lecture 1
Unix Commands CS3101-2, Lecture 1
Submitting from newcunix • Instructions: • Put hw in its own directory • Re-compile with g++ • $ /opt/ACISsubmit/bin/submit cs3101-2 • Wait for email confirmation • Important: • Omits binary files, *~ (backups) • Submits all text files in and below current directory • Don’t submit from your ~ directory! • Hw submitted by email will not be graded! Important: • Q: Can I just email in first hw? • A: No! Learning how to compile & submit is the purpose of hw0 CS3101-2, Lecture 1
Where to code • On newcunix: Emacs, Pico, etc. • On Win: Fancy IDEs like VC++, C++Builder, etc. • I recommend Textpad (textpad.com) • FTP: use utility, or put sftp://newcunix.cc.columbia.edu in IE address bar, log in, drag&drop CS3101-2, Lecture 1
Homework 0 • Write, compile, and run a Hello, World program • Prints “Hello world, from <my name>.” • Hand in: • Source file (e.g., hello.cpp) • Trace file ($ hello > trace.txt) CS3101-2, Lecture 1
Collaboration Policy • All subsequent work • Must be done independently • Collaboration = cheating • See scary CU cheating policies • “Severest of conseqences” • deans, honor committees, not fun • This homework only • Collaboration is fine • Hw0 is “merely instrumental”: learn how to compile & submit CS3101-2, Lecture 1
C++ Tutorial • Quick & dirty intro to language • Learn to write by writing, learn to program by programming • First program: Hello, World • #include <iostream> main() { std::cout << “Hello, world.” << std::endl; } CS3101-2, Lecture 1
C++ Tutorial – Hello, World • In Java, a program is >= 1 class • In C, a program is >= 1 function • In C++, a program is >= 1 function + >=0 classes • In all three, main() is the entry point • Contains the instructions performed when program is run • The body of a ftn is demarcated by braces (“curly brackets”): { } • Inside, instructions to be performed when ftn is called • main() is called on program start-up CS3101-2, Lecture 1
C++ Tutorial - #include • Before main() function, we have • #include <iostream> • Tells compiler to include the iostream (no .h!) library • Operationally similar to Java’s import • # indicates command to C Preprocessor (CPP) • Preprocesses the source just before compilation • #include line replaced with contents of file • What’s included is the header/declaration for a library • The library’s public interface • Allows access to functions and objects in the library • System libraries in < >, one’s own in “ ” CS3101-2, Lecture 1
C++ Tutorial – cout • Our program contains one statement: a call to std::cout • std “standard” library namespace • cout “console output” stream • Similar to Java’s System.out.print() and C’s printf() • printf uses complicated pattern-matching for outputting computed expressionss • print() and cout use OO • each object/var knows how to be printed • Intuitive (for now) understanding of << op: • Param is being passed (left) to cout CS3101-2, Lecture 1
C++ Tutorial - Parameters • We passed “Hello, World.” and endl to std::cout as a parameter • Tells function what to do • In this case, what to print • endl is a stream manipulator • Not simply data to be printed • Tells cout to print ‘\n’ and flush the stream • ’\n’ is the new line escape character CS3101-2, Lecture 1
C++ Tutorial – Esc chars • Stores internally as a char (1-byte integer) • A char-based concept • Not corresponding to any actual/typable character CS3101-2, Lecture 1
C++ Tutorial - Temps • More complicated program – print table of Fahr. – Cels. temperatures: • Math? • C = 5/9 * (F-32) CS3101-2, Lecture 1
C++ Tutorial - Temps #include <iostream> // prints F-C table main() { int lwr = 0, upr = 300, step = 20; int fahr = lwr; while (fahr <= upr) { int cels = 5*(fahr-32)/9; std::cout << fahr << ‘ ‘ << cels << std::endl; fahr = fahr + step; } } CS3101-2, Lecture 1
C++ Tutorial – Temps – comments • Things to notice: • /* */ enclose comments – no effect on program • // for single line comments • /* */ //, mutually nest • Can also comment code using CPP: • #if 0 this stuff won’t be seen by the compiler la LA la la laaaaa #endif • Three kinds of commenting syntax (CPP/C/C++) • But avoid CPP unless necessary (like #include) CS3101-2, Lecture 1
C++ Tutorial – Temps – vars • Var declarations • Announce that fahr, etc, will be names of persistent pieces of data, of type int • Var types determine what sort of value a var can take on • Local vars can be declared anywhere in a block (like in J) • Not just at beginning of block (like in C) • Live until end of block defined in • Var names: letters, digits, _ (can’t begin with digits) • Case-sensitive (like all else) • Other var types: • long (large integers) • floats (rational numbers) • doubles (larger, higher precision floats) • chars (small integers, representing typographical symbols) • bools (not booles, in spite of his name) CS3101-2, Lecture 1
C++ Tutorial – primitive types • Many data type sizes are … • undefined, i.e., compiler/machine-dependent (as in C) • Restrictions (in bytes): • |char| == 1 < |short| <= |int| <= |long| • Often: • |short| == = 16 -32768…32767 • |int| == |long| = 32 -1038…1038 • Integer literals (e.g, 10) eval as ints • Char literals (e.g., ‘A’) eval as chars • Unlike in C; overloading • NB: Don’t include leading 0s unless you mean it: 011 • This is octal: 011 == 1 + 8 == 9 CS3101-2, Lecture 1
C++ Tutorial – Temps - assigns • Like in C/Java: value of RHS stored in LHS • lvalue == can appear on LHS of assignment (e.g, vars) • rvalue == merely passive value • Assignments are expressions • with side effects (i.e., rvalue assigned to lvalue) • x = 10 x == 10 • that eval to some val (the new val of the lvalue) • (i = static_cast<int>(3.5)) val of i == 3 • Statements terminated by ; • More generally: • Statement == expr + ; CS3101-2, Lecture 1
C++ Tutorial - Temps • Table lines all of same form: two numbers, with a certain relationship repetition print lines the same way • Here using while-loop • Repeated evals test condition; if passes test, execs while body • While body is a statement or block of statements CS3101-2, Lecture 1
C++ Tutorial - Temps • Celsius computation line: • cels = 5*(fahr-32)/9; • Why not this: • cels = 5/9*(fahr-32);? • val1 and val2 are of the same type the value of val1 op val2 will also be of that type 5 and 9 are ints 5/9 is an int 5/9 as an int is just 0 all Celsius temps become 0 CS3101-2, Lecture 1
C++ Tutorial - Temps • cout line: • std::cout << fahr << ‘ ‘ << cels << std::endl; • Similar to Java equiv: • System.out.println(fahr + ‘ ‘ + cels); • Much different from C equiv: • printf(“%d %d\n”, fahr, cels); • NB: in both C and C++, must specify end-of-line manually: endl or ‘\n’ CS3101-2, Lecture 1
C++ Tutorial – Temps’ • use floating-pts for greater precision • double f = 0, c = 0; while (f <= upr) { c = (5.0/9.0) * (f – 32.0); std::cout << fahr << ‘ ’ << cels << std::endl; } • No need to change output • cout knows how to handle doubles, too CS3101-2, Lecture 1
C++ Tutorial – Temps’ • More succinct with a for loop: • main() { for (int f = 0; f <= 300; f += 20) std::cout << fahr << ‘ ’ << (5.0/9)*(f–32) << std::endl; } • Notice: • Fewer vars • sent expr (not var) to cout • << has low precedence • Doesn’t use float in <= check • Used +=: a += b a = a + b • Can declare counter var in for-loop init CS3101-2, Lecture 1
C++ Tutorial – Temps’ • For loop pattern: • for (init; test; inc) {} • init; while (test) { /* body code */ inc; } • For loop var lives past for loop body, just as in while-loop analog • Infinite loops: • while(true) … • for (;;) … CS3101-2, Lecture 1
C++ Tutorial – Temps’’ • In general: hard-coded, frequently appearing literals (“magic numbers”) are bad • Soln 1: symbolic constants • Defined with preprocessor – no ; • Pattern: #define name replace-text • Replaces all occurrences except: • In “ ” • In part of other name • Soln 2: declare numbers as consts CS3101-2, Lecture 1
C++ Tutorial – Temps’’ const int LOWER = 0, UPPER = 300, STEP = 20; // … main() { for (int f = LOWER; f <= UPPER; f += STEP) std::cout << f << ‘ ’ << (5.0/9)*(f–32) << std::endl; } CS3101-2, Lecture 1
C++ Tutorial – Temps’’ output $ g++ temp1.cpp $ a.out 0 -17.7778 20 -6.66667 40 4.44444 60 15.5556 80 26.6667 100 37.7778 120 48.8889 140 60 160 71.1111 180 82.2222 200 93.3333 220 104.444 240 115.556 260 126.667 280 137.778 300 148.889 • Coding is now okay • But output is ugly • Uneven columns – based on number-width • Cels show too many dec. places • Improvement 1: replace ‘ ‘ with ‘\t’ CS3101-2, Lecture 1
C++ Tutorial – Temps(2) output $ g++ temp2.cpp $ a.out 0 -17.7778 20 -6.66667 40 4.44444 60 15.5556 80 26.6667 100 37.7778 120 48.8889 140 60 160 71.1111 180 82.2222 200 93.3333 220 104.444 240 115.556 260 126.667 280 137.778 300 148.889 $ • Output is better • Aligned left • But still ugly • Numbers should right-align • Cels show too many dec. places • Improvements 2. create columns with column-widths, not tabs; 3. right-align columns CS3101-2, Lecture 1
C++ Tutorial – Temps(3) #include <iostream> #include <iomanip> using namespace std; const int LOWER = 0, UPPER = 300, STEP = 20; main() { for (int f = LOWER; f <= UPPER; f += STEP) { cout.width(3); cout << f; cout << setw(7) << (5.0/9)*(f-32) << endl; } } CS3101-2, Lecture 1