CS3101-2 Programming Languages - PowerPoint PPT Presentation

1 / 72
About This Presentation
Title:

CS3101-2 Programming Languages

Description:

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 ... – PowerPoint PPT presentation

Number of Views:89
Avg rating:3.0/5.0
Slides: 73
Provided by: pagesSte
Category:

less

Transcript and Presenter's Notes

Title: CS3101-2 Programming Languages


1
CS3101-2Programming Languages CLecture 1
  • Matthew P. Johnson
  • Columbia University
  • Fall 2003

2
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

3
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
  • Youre 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

4
Contact Info
  • Class page http//www.columbia.edu/mpj9/3101-2
  • PPTs
  • In-class examples
  • Link to CourseWorks, other lecture notes, etc.
  • Me mpj9_at_columbia.edu
  • OHs Saturdays, 1-3, in 251 Mudd lab
  • Check classpage for updates
  • TA Jacob Porway
  • jmp204_at_columbia.edu
  • OHs see web
  • Check http//ta.cs.columbia.edu for updates
  • Feedback is good!
  • Prepend CS3101-C to subject lines!

5
Textbook
  • For the C course, I like
  • The C Programming Language (KR)
  • Classic text
  • By creators of C
  • Short, pretty cheap, and rigorous

6
Textbook
  • This class is C
  • Exists the book
  • The C Programming Language
  • By creator of C
  • Rigorous, but difficult, expensive, and long
    (1000 pages)

7
Textbook
  • So well use
  • Practical C Programming
  • OReilly
  • Available Labyrinth, Papyrus, Amazon and BN
    (links on class page)
  • Not too difficult, not too long (500 pages)
  • Lectures will sometimes follow text, sometimes not

8
IMPORTANT
  • Ill repeat your questions before answering them,
    for CVN
  • If I forget, remind me!
  • Before Ive answered
  • Get participation XC

9
Rest of this class
  • Description History of C/C
  • Intro to Unix
  • 0th Homework
  • C Tutorial

10
(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 (KR, second edition),
    1988
  • Java, James Gosling, Sun, 1995
  • C, Microsoft, about 15 minutes ago
  • C, Java, C conserve (much) C syntax

11
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 Hemingways 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

12
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!

13
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 theres so little
    error-checking
  • ar-2 or ar100000 doesnt throw an exception
    (doesnt 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

14
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?

15
Why C?
  • A Yes!
  • Java is very elegant, but it doesnt compile to
    machine code
  • ? Its very slow!
  • O(20) times slower than C/C
  • Compiled Java programs arent executables,
    theyre .classs
  • Theyre 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., arent
    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 depts default lang, learned over
    a semester or two
  • Instead, well learn C in 6 weeks

16
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 arent good at trivia questions
  • Theyre 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 youre interested in ? written with
    your interests in mind

17
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() ? lenwid, if shape is a
    rectangle
  • shape.getArea() ? PIr2, if shape is a circle
  • Most important of three encapsulation

18
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 well see as we go along

19
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 wont follow this strategy in
    this class
  • If you took 3101-1, then youre 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

20
Unix
  • You dont 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.

21
Programming with Emacs/g
Create source file in Emacs emacs myprog.cpp
Save file, exit Ctrl-X, Ctrl-S, Y
Compile g myprog.cpp ? a.out
Compile with executable name g myprog.cpp ? a.out
Compile with with all warnings on g myprog.cpp Wall
Run executable a.out, a.out lt from.txt gt to.txt
22
g Tips
  • Compilers on newcunix
  • CC (default compiler not cc)
  • g 3.3 (GNUs C compiler)
  • Ensure you use the right version
  • Add these lines to your .profile (in your )
  • export PATH/opt/gcc-3.3/binPATH
  • export LD_LIBRARY_PATH/opt/gcc-3.3/libPATH
  • 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

23
Unix Commands
Unix Windows
ls dir
cp copy
mv move
rm del
mkdir mk
cd cd
more type
24
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
  • Dont 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

25
Where to code
  • On newcunix Emacs, Pico, etc.
  • On Win Fancy IDEs like VC, CBuilder, etc.
  • I recommend Textpad (textpad.com)
  • FTP use utility, or put sftp//newcunix.cc.columb
    ia.edu in IE address bar, log in, dragdrop

26
Homework 0
  • Write, compile, and run a Hello, World program
  • Prints Hello world, from ltmy namegt.
  • Hand in
  • Source file (e.g., hello.cpp)
  • Trace file ( hello gt trace.txt)

27
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

28
C Tutorial
  • Quick dirty intro to language
  • Learn to write by writing, learn to program by
    programming
  • First program Hello, World
  • include ltiostreamgt
  • main()
  • stdcout ltlt Hello, world. ltlt stdendl

29
C Tutorial Hello, World
  • In Java, a program is gt 1 class
  • In C, a program is gt 1 function
  • In C, a program is gt 1 function gt0 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

30
C Tutorial - include
  • Before main() function, we have
  • include ltiostreamgt
  • Tells compiler to include the iostream (no .h!)
    library
  • Operationally similar to Javas import
  • indicates command to C Preprocessor (CPP)
  • Preprocesses the source just before compilation
  • include line replaced with contents of file
  • Whats included is the header/declaration for a
    library
  • The librarys public interface
  • Allows access to functions and objects in the
    library
  • System libraries in lt gt, ones own in

31
C Tutorial cout
  • Our program contains one statement a call to
    stdcout
  • std ? standard library namespace
  • cout ? console output stream
  • Similar to Javas System.out.print() and Cs
    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 ltlt op
  • Param is being passed (left) to cout

32
C Tutorial - Parameters
  • We passed Hello, World. and endl to stdcout
    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

33
C Tutorial Esc chars
\t Tab
\r Carriage return
\a Alarm bell
\
\
\\ \
  • Stores internally as a char (1-byte integer)
  • A char-based concept
  • Not corresponding to any actual/typable character

34
C Tutorial - Temps
  • More complicated program print table of Fahr.
    Cels. temperatures
  • Math?
  • C 5/9 (F-32)

0 lt0-in-Celsiusgt
20 lt20-in-Celsiusgt

300 lt300-in-Celsiusgt
35
C Tutorial - Temps
  • include ltiostreamgt
  • // prints F-C table
  • main()
  • int lwr 0, upr 300, step 20
  • int fahr lwr
  • while (fahr lt upr)
  • int cels 5(fahr-32)/9
  • stdcout ltlt fahr ltlt ltlt cels ltlt
    stdendl
  • fahr fahr step

36
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 wont 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)

37
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, _ (cant 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)

38
C Tutorial primitive types
  • Many data type sizes are
  • undefined, i.e., compiler/machine-dependent (as
    in C)
  • Restrictions (in bytes)
  • char 1 lt short lt int lt long
  • Often
  • short 16 ? -3276832767
  • int long 32 ? -10381038
  • Integer literals (e.g, 10) eval as ints
  • Char literals (e.g., A) eval as chars
  • Unlike in C overloading
  • NB Dont include leading 0s unless you mean it
    011
  • This is octal 011 1 8 9

39
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_castltintgt(3.5)) ? val of i 3
  • Statements terminated by
  • More generally
  • Statement expr

40
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

41
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

42
C Tutorial - Temps
  • cout line
  • stdcout ltlt fahr ltlt ltlt cels ltlt stdendl
  • 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

43
C Tutorial Temps
  • ? use floating-pts for greater precision
  • double f 0, c 0
  • while (f lt upr)
  • c (5.0/9.0) (f 32.0)
  • stdcout ltlt fahr ltlt ltlt cels ltlt
    stdendl
  • No need to change output
  • cout knows how to handle doubles, too

44
C Tutorial Temps
  • More succinct with a for loop
  • main()
  • for (int f 0 f lt 300 f 20)
  • stdcout ltlt fahr ltlt ltlt (5.0/9)(f32)
    ltlt stdendl
  • Notice
  • Fewer vars
  • sent expr (not var) to cout
  • ltlt has low precedence
  • Doesnt use float in lt check
  • Used a b ? a a b
  • Can declare counter var in for-loop init

45
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 ()

46
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

47
C Tutorial Temps
  • const int LOWER 0,
  • UPPER 300,
  • STEP 20 //
  • main()
  • for (int f LOWER f lt UPPER f STEP)
  • stdcout ltlt f ltlt ltlt (5.0/9)(f32) ltlt
    stdendl

48
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

49
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

50
C Tutorial Temps(3)
  • include ltiostreamgt
  • include ltiomanipgt
  • using namespace std
  • const int LOWER 0, UPPER 300, STEP 20
  • main()
  • for (int f LOWER f lt UPPER f STEP)
  • cout.width(3)
  • cout ltlt f
  • cout ltlt setw(7) ltlt (5.0/9)(f-32) ltlt endl

51
C Tutorial Temps(3)
  • Changes
  • Width set for each col
  • cout.width(3) member ftn in cout
  • cout ltlt setw(7) manipulator
  • Requires include of iomanip
  • Applies only to next output
  • Precision is set
  • cout.precision(2) member ftn
  • cout ltlt setprecision(2) manip
  • Applies from now on
  • Namespace std is now used
  • Prevents having to prefix std members with std
  • Many I/O settings can be controlled
  • with either member ftns of the stream used or
  • with manipulators passed to the stream

52
C Tutorial Temps(3) output
g temp3.cpp a.out 0 -18 20 -6.7 40
4.4 60 16 80 27 100 38 120
49 140 60 160 71 180 82 200
93 220 1e02 2401.2e02 2601.3e02 2801.4e02 300
1.5e02
  • Problems precision isnt what we meant
  • Total number of sig digs
  • Veers into sci. not.
  • Want number of places past dec. pt.
  • Soln set the fixed flag
  • cout.setf(iosfixed)

53
C Tutorial Temps(3) output
  • At last

include ltiostreamgt include ltiomanipgt using
namespace std const int LOWER 0, UPPER 300,
STEP 20 main() cout.setf(iosfixed)
cout ltlt setprecision(2) ltlt setw(6) for (int
f LOWER f lt UPPER f STEP)
cout.width(3) cout ltlt f cout ltlt
setw(7) ltlt (5.0/9)(f-32) ltlt endl
g temp4.cpp a.out 0 -17.78 20 -6.67 40
4.44 60 15.56 80 26.67 100 37.78 120
48.89 140 60.00 160 71.11 180 82.22 200
93.33 220 104.44 240 115.56 260 126.67 280
137.78 300 148.89
54
C operators
Addition x y z
Subtraction x y z
Multiplication x y z
Division x y / z
Boolean AND x 1 y lt 2
Boolean OR x 1 y lt 2
Boolean NOT x !y
Bitwise AND 2 3 2
Bitwise OR 2 3 3
Bitwise NOT/ Complement x !x 0
Bitwise XOR x x 0
Shift left x ltlt 1
Shift right x gtgt 2
  • Operators are similar to those in C/Java, some
    already used
  • Usual comparsion operators , lt, gt, lt, gt

55
Shortcut operators
  • In general, for every binary operator has a
    shortcut assignment analog
  • Also, there are shortcut increment/decrement (by
    1) ops /--
  • Prefix/postfix notation indicates whether to
    modify before or after expression eval
  • int x 10, y
  • y x // x evals to 10, thyen x set to 11 y
    1
  • y --x // x set to 10, then x evals to 10 y
    10
  • y y // ?
  • Contract for postfix side effect occurs after
    eval
  • Q How long after?
  • A Compiler-dependent in g, yy ? y is
    incremented
  • Like assign ops, side effects and evals are
    independent

Addition x x y x y
Subtraction x x y X - y
Shift left x x ltlt 2 X ltlt 2
Etc.
56
Type conversion
  • Can be widening
  • Smaller range type ? larger range
  • Or narrowing
  • Large range ? smaller range
  • Generally, only narrowing loses info
  • Conversion occurs automatically between
    assignment of distinct types
  • Narrowing assignment is legal, but may give
    warning
  • int x 1025 char ch float f 3.5
  • ch x // ch 1
  • x f // x 3
  • f x // f 3.0
  • Q What printed by cout ltlt ch 1089?
  • A char value of 1029 65 as char A

57
Static Casting
  • Used 5.0 to force use of doubles
  • What if 5, 9 had been vars or consts?
  • Can force conversion (in expression!) by casting
  • static_castltnew-typegt(expr)
  • int x 1
  • double half x/2 // half 0
  • half static_castltdoublegt(x)/2 // half 0.5
  • NB x (lvalue) is not changed by cast
  • static_castltdoublegt(x) simply evals differently
  • ? correct value lands in half
  • C has several other types of casting later
  • Replace old C-style casts (double)x
  • Prevents precedence errors
  • Casting is more recognizable
  • Safer

58
More I/O compute ages
  • Idea compute ones age in arbitrary year
  • include ltiostreamgt
  • using namespace std
  • int main()
  • int curr_year, curr_age, another_year,
    another_age
  • cout ltlt "Enter the current year "
  • cin gtgt curr_year
  • cout ltlt "Enter your current age in years "
  • cin gtgt curr_age
  • cout ltlt "Enter another year "
  • cin gtgt another_year
  • another_age another_year - (curr_year -
    curr_age)
  • if (another_age 0)
  • cout ltlt This was the year you were born ltlt
    endl

59
More I/O compute ages
  • First line
  • include ltiostreamgt
  • Links the iostream library with out program
  • Second line
  • using namespace std
  • Specifies that were using std (standard
    namespace)
  • Otherwise, must specify locations of stds
    members
  • stdcin ltlt
  • Similar to Javas import command
  • Q Why does include ltiostream.hgt work?
  • Old-style includes
  • A think of io.stream.h as including iostream and
    then using std

60
Equality testing
  • We wrote
  • if (another_age 0)
  • Q Would this have compiled
  • if (another_age 0)?
  • A Yes!
  • C has no boolean type!
  • ? bools are represented in C by ints
  • C does have a bool type
  • Comparison expressions eval to bools
  • But backward compatibility if (12) is legal
  • Q What happens in if (another_age 0)?
  • A 0 assigned to another_age, expr evals to 0 ?
    if-statement interpets as false ? we wrongly say
    user wasnt born

61
Booleans and integers
  • Conversions carry over from C
  • 0 ? false
  • !0 (anything but 0) ? true
  • Literally !1 0, x ! 0 ? !x 1
  • Conversely
  • true expression ? 1
  • false expression ? 0
  • Lesson Be careful with ,
  • Turn on Wall
  • g age.cpp -Wall
  • age.cpp In function int main()'
  • age.cpp19 warning suggest parentheses around
    assignment used as truth value

62
ASCII chars digits
  • Consider converting digit chars to corresponding
    ints
  • e.g., 2 ?2
  • What is relationship bet 2 2?
  • 2 2?
  • No
  • 2 some int corresponding to the char 2
  • 3 some int the char 3
  • 2 1
  • 1 1 1
  • 0 1 1 1
  • 0 3
  • ? 3 3 0
  • Also, Q 2 static_castltintgt(2)?
  • A No. static_castltintgt(2) is just a 32-bit rep
    of the number 2 the same number, with more
    leading 0s

63
Arrays
  • Simplest type of composite data structure
  • Ordered seq of vars (counting from 0)
  • Homogeneous vars of same type
  • Contiguous stored adjacently in mem
  • Lowest memory address to highest
  • Declare, access with s
  • int nums10
  • nums0 25
  • Indices begin at 0
  • What if index is a non-int val?
  • Compile error
  • What if index is an int too small or too big?
  • nums800 or nums-5
  • calcs where corresponding int would be ?
    reads/writes to that location ? probably crashes
  • be careful!

64
Functions
  • Group of instructions that can be called
    repeatedly
  • For now, declared outside of a class
  • Exist independently of any objects no
    construction to call
  • So far, seen only main function
  • New ftn C has no (pwr) op lets write a
    ftn

65
Functions
  • General form
  • return-type name (parm-list)
  • declars
  • stmts
  • optionally return val

66
power
  • include ltiostreamgt
  • int pwr (int b, int exp)
  • main()
  • int i
  • for (i 0 i lt 10 i)
  • stdcout ltlt i ltlt ltlt pwr(2,i) ltlt ltlt
  • pwr(-3,i) ltlt stdendl

67
power (cont.)
  • int pwr (int b, int exp)
  • int p 1
  • for (int i 1 i lt n i)
  • p b
  • return p

68
Functions notice
  • Ftn states its I/O params it takes, type of val
    (if any) it returns
  • Ftn must be defined or declared before use
  • By default, params are passed-by-val change to
    param in ftn is not seen by caller
  • Pre-Ansi C syntax was
  • power(base, n)
  • int base, n

69
power
  • Take advantage of pass-by-val
  • int power(int b, int exp)
  • for (int p 1 n gt 0 --n)
  • p b
  • return p
  • Removed one var
  • Passed-in b not effected
  • We can simulate pass-by-ref with pointers more
    later

70
Strings
  • No built-in type (tho will see class later)
  • Just arrays of chars no internal structure
  • char s Hi\n
  • ?
  • char s H, i, \n, \0
  • \0 is the null char
  • Indicates end of string
  • Evals to 0
  • ? n-char string really uses n1 bytes in memory

71
Strings/arrays as ftn args
  • Unless otherwise specified, all args passed to
    ftns by value
  • True of strings/arrays as well, but may seem not
  • What to know for now if array/string passed to
    ftn, the members/chars in orig. arg can be
    modified by ftn
  • Q Why?
  • A Find out next week!

72
Next time
  • Topics Pointers, References, Arrays, DMA
  • For next time
  • Get your book
  • Do reading assigned on web
  • hw0
Write a Comment
User Comments (0)
About PowerShow.com