Programming Languages: Part 2 Robert M. Dondero, Ph.D. Princeton University 1
Objectives You will learn/review: In C, Java, and Python... Terminal input/output Data types, operators, statements Multi-file programs 2
"Circle" Programs Illustrate: Primitive data types Operators Terminal I/O 3
"Circle" in C See circle.c Data types: int, double Operators: =, *, +, cast Terminal input via scanf() Lack of exception handling Generalizing Must check function return value instead Data types, operators, and terminal I/O... 4
C Primitive Data Types Data Type Size Example Literals char 1 byte (char)-128, (char)127, 'a', '\n', '\t', '\0' unsigned char 1 byte (unsigned char) 0, (unsigned char)256 short 2 bytes? (short)-32768, (short)32767 unsigned short 2 bytes? (short)0, (short)65535 int 4 bytes? -2147483648, 2147483647 unsigned int 4 bytes? 0U, 4294967295U, 0123, 0x123 long 4 bytes? -2147483648L, 2147483647L unsigned long 4 bytes? 0UL, 4294967295UL, 0123L, 0x123L float 4 bytes? 123.456F double 8 bytes? 123.456 long double 12 bytes? 123.456L 5
C Operators Operator fun(params) a[i] s.f ps->f (type) *p, &x i++, ++i, i--, --i +x, -x (Precedence) Meaning (1) Function call (1) Array element selector (1) Structure field selector (1) Structure dereference and field selector (2) Typecast (2) Dereference, address of (2) Increment, decrement (2) Unary positive, unary negative ~i (2) Bitwise NOT!i (2) Logical NOT sizeof(type) (2) sizeof 6
C Operators Operator x*y, x/y, i%j x+y, x-y i<<j, i>>j x,y, x>y, x<=y, x>=y x==y, x!=y i&j i^j i j i&&j i j i?x:y (Precedence) Meaning (3) Multiplication, division, remainder (4) Addition, subtraction (5) Left-shift, right-shift (6) Relational (7) Relational (8) Bitwise AND (9) Bitwise EXCLUSIVE OR (10) Bitwise OR (11) Logical AND (12) Logical OR (13) Conditional expression 7
C Operators Operator x=y x+=y, x-=y, x*=y, x/=y i&=j, i^=j, i =j i<<=j, i>>=j x,y (Precedence) Meaning (14) Assignment (14) Assignment (14) Assignment (14) Assignment (15) Sequence 8
C Terminal I/O Reading from stdin: ivaluesread = scanf("%d", &i); ivaluesread = scanf("%lf", &d); s = fgets(s, size, stdin) 9
C Terminal I/O Writing to stdout: printf("%d", i); printf("%f", d); fputs(s, stdout); Writing to stderr: fprintf(stderr, "%d", i); fprintf(stderr, "%f", d); fputs(s, stderr); 10
"Circle" in Java See Circle.java Data types: int, double Operators: =, *, +, cast Terminal input via Scanner class Exception handling via try...catch statement Generalizing Data types, operators, and terminal I/O... 11
Java Primitive Data Types Data Type Size Example Literals boolean 1 bit false, true char 2 bytes '\u0000', 'uffff', 'a', '\n', '\t', '\0' byte 1 byte (byte)-128, (byte)127 short 2 bytes (short)-32768, (short)32767 int 4 bytes -2147483648, 2147483647 long 8 bytes -9223372036854775808L, 9223372036854775807L float 4 bytes 123.456F double 8 bytes 123.456 12
Java Operators Operators method(params) a[i] obj.field, obj.method() class.field, class.method() i++, ++i, i--, --i +x, -x ~i,!b new Class() (type) x*y, x/y, i%j (Precedence) Meaning (1) Method call (1) Array element selector (1) Object member selector (1) Class member selector (2) Increment, decrement (2) Unary plus, unary minus (2) Bitwise NOT, logical NOT (3) Object creation (3) Typecast (4) Multiplication, division, remainder 13
Java Operators Operators x+y, x-y i<<j, i>>j, i>>>j x<y, x>y, x<=y, x>=y obj instanceof Class x==y, x!=y i&j i^j i j b1&&b2 b1 b2 (Precedence) Meaning (5) Addition, subtraction (6) Left shift, right shift, right shift zero fill (7) Relational (7) instanceof (8) relational (9) Bitwise AND (10) Bitwise exclusive OR (11) Bitwise OR (12) Logical AND (13) Logical OR 14
Java Operators Operators b?x:y x=y x+=y, x-=y, x*=y, x/=y, x%=y i&=j, i^=j, i =j i<<=j, i>>=j, i>>>=j (Precedence) Meaning (14) Conditional expression (15) Assignment (15) Assignment (15) Assignment (15) Assignment 15
Java Terminal I/O Reading from stdin: import java.util.scanner; Scanner scanner = new Scanner(System.in); int i = scanner.nextint(); double d = scanner.nextdouble(); String s = scanner.nextline(); 16
Java Terminal I/O Writing to stdout: System.out.print(i); System.out.println(d); System.out.println(s); Writing to stderr: System.err.print(i); System.err.println(d); System.err.println(s); 17
"Circle" in Python See circle.py Data types: number Type conversions via int() and float() functions String literals: ' ' or " " Operators: * (multiplication), % (string formatting) Terminal input via raw_input() Exception handling via try...except statement 18
"Circle" in Python Generalizing Conversion functions: int(obj), float(obj), str(obj), bool(obj) String formatting: conversion specifications are as in C Data types, operators, and terminal I/O... 19
Python Primitive Data Types Data Type Example Literals Integer numbers (plain or long) 1, 23, 3493, 01, 027, 06645, 0x1, 0x17, 0cDA5, 1L, 23L, 99999333493L, 01L, 027L, 01351033136165L, 0x1L, 0x17L, 0x17486CBC75L (no theoretical size limit) Floating-point numbers 0., 0.0,.0, 1.0, 1e0, 1.0e0 (correspond to C doubles) Boolean False, True Null object None 20
Python Operators Operators (Priority) Meaning {key:expr,...} (1) Dictionary creation [expr,...] (2) List creation (expr,...) (3) Tuple creation, or just parentheses f(expr,...) (4) Function call x[startindex:stopindex] (5) Slicing (for sequences) x[index] (6) Indexing (for containers) x.attr (7) Attribute reference x**y (8) Exponentiation ~x (9) Bitwise NOT +x, -x (10) Unary plus, unary minus x*y, x/y, x//y, x%y (11) Mult, div, truncating div, remainder x+y, x-y (12) Addition, subtraction 21
Python Operators Operator x<<i, x>>i x&y x^y x y x<y, x<=y, x>y, x>=y x==y, x!=y x is y, x is not y x in y, x not in y not x x and y x or y (Priority) Meaning (13) Left-shift, right-shift (14) Bitwise AND (15) Bitwise XOR (16) Bitwise OR (17) Relational (17) Relational (18) Identity tests (19) Membership tests (20) Logical NOT (21) Logical AND (22) Logical OR 22
Python Terminal I/O Reading from stdin: str = raw_input() str = raw_input(promptstr) from sys import stdin str = stdin.readline() 23
Python Terminal I/O Writing to stdout: print str print str, Writing to stderr: print >>stderr, str print >>stderr, str, 24
"Euclid" Programs Illustrate: Control flow statements 25
"Euclid" in C See euclid.c Control flow statements: if, while, return Generalizing Statements... 26
C Statements Expression statement expr; Declaration statement modifiers datatype var [= expr] [, var [= expr]]...; Common modifiers: const, static Compound statement { statement; statement;...} 27
C Statements If statement if (intorptrexpr) statement [else statement] 0 or NULL pointer => false; anything else => true Switch statement switch (intexpr) { case (intvalue1): statement;...; break; case (intvalue2): statement;...; break;... default: statement;...; } 28
C Statements While statement while (intorptrexpr) statement; Do...while statement do statement while (intorptrexpr); For statement for (initexpr; intorptrexpr; increxpr) statement; 29
C Statements Break statement break; Continue statement continue; Return statement: return; return expr; 30
"Euclid" in Java See Euclid.java Control flow statements: if, while, return Generalizing Statements... 31
Java Statements Expression statement expr; Declaration statement modifiers datatype var [= expr] [, var [= expr]]...; Common modifiers: const, static Compound statement { statement; statement;...} 32
Java Statements If statement if (booleanexpr) statement else statement; Switch statement switch (intexpr) { case (intvalue1): statement;...; break; case (intvalue2): statement;...; break;... default: statement;...; } 33
Java Statements While statement while (booleanexpr)statement; Do...while statement do statement while (booleanexpr); For statement for (initexpr; booleanexpr; increxpr) statement; Foreach statement for (type var : IterableOrArrayObject) statement; 34
Java Statements Break statement break; Continue statement continue; Return statement return; return expr; 35
Java Statements Try...catch statement try { statement; statement; ; } catch (ExceptionType e) { statement; statement; ; } Throw statement throw object; 36
"Euclid" in Python See euclid.py Integer division operator Control flow statements: if, while, return, raise Weak typing Generalizing Statements... No type checks at compile-time, so... Must do type checks at run-time, or... Suffer the consequences!!! 37
Python Statements Assignment statements var = expr var += expr var -= expr var *= expr var /= expr var //= expr var %= expr var **= expr var &= expr var = expr var ^= expr var >>= expr var <<= expr 38
Python Statements Unpacking assignment statement var1,var2,... = iterable No-op statement pass Assert statement assert expr, message 39
Python Statements Print statement print expr,... print expr,..., hack Function call statement f(expr, name=expr,...) Return statement return return expr 40
Python Statements If statement if expr: statement(s) elif expr: statement(s) else: statement(s) False, 0, None, '', "", [], (), and {} indicate logical FALSE Any other value indicates logical TRUE 41
Python Statements While statement while expr: statement(s) False, 0, None, '', "", [], (), and {} indicate logical FALSE Any other value indicates logical TRUE 42
Python Statements For statements for var in range(startint, stopint): statements for var in range(stopint): statements for var in iterable: statements for key,value in mapping.iteritems(): statements Break statement break Continue statement continue 43
Python Statements Try...except statement try: statement(s) except [ExceptionType[, var]]: statement(s) Raise statement raise ExceptionType(str) 44
"IntMath" Modules Illustrate: Multi-file programs... Design to facilitate reuse of functions in multiple programs Module interfaces and implementations Building and running multi-file programs 45
"IntMath" in C See intmath.h, intmath.c, testintmath.c intmath.h is IntMath module interface Protection against multiple inclusion Function names begin with module name intmath.c is IntMath module implementation #includes intmath.h so compiler can enforce consistency testintmath.c is IntMath module client #includes intmath.h so compiler can check calls of IntMath_gcd() and IntMath_lcm() 46
"IntMath" in C Building: $ gcc -Wall -ansi -pedantic intmath.c testintmath.c -o testintmath Running: $ testintmath 47
"IntMath" in Java See IntMath.java, TestIntMath.java Module interface is not distinct from implementation IntMath.java is module interface and implementation Interface: public method headings & fields Implementation: all method headings & fields TestIntMath.java is IntMath module client 48
"IntMath" in Java Building and running $ javac TestIntMath.java Automatically builds IntMath.java Directory containing IntMath.java must be in CLASSPATH env var "." is in CLASSPATH by default $ java TestIntMath 49
"IntMath" in Python See intmath.py, testintmath.py Module interface is not distinct from implementation intmath.py is IntMath module interface and implementation testintmath.py is IntMath module client testintmath.py must import from intmath.py 50
"IntMath" in Python Building and running $ testintmath.py Automatically builds intmath.py Directory containing intmath.py must be in PYTHONPATH env var "." is in PYTHONPATH by default 51
"ReadNum" Modules The job: Prompt for and read an int/double from stdin Re-prompt and re-read if user enters bad data Illustrate Multi-file programs (as previous example) Unit testing 52
"ReadNum" in C See readnum.h, readnum.c, circle2.c Consumes entire line Otherwise bad characters would affect subsequent reads Calls strtol() and strtod() to convert string to int/double Contains lots of code for error handling 53
"ReadNum" in C Conditionally includes main() function in readnum module To build normally: Common technique for unit testing gcc -Wall -ansi -pedantic circle2.c readnum.c To build for unit testing: gcc -Wall -ansi -pedantic -D TEST_READNUM readnum.c
"ReadNum" in Java See ReadNum.java, Circle2.java Consumes entire line Otherwise bad characters would affect subsequent reads Calls Integer.parseInt() and Double.parseDouble() to convert String to int/double Uses exceptions to handle errors Defines main() method in ReadNum.java Common technique for unit testing 55
"ReadNum" in Python See readnum.py, circle2.py Consumes entire line Otherwise bad characters would affect subsequent reads Calls int() and float() to convert string to int/double Uses exceptions to handle errors Defines conditionally-executed test code in readnum.py Common technique for unit testing 56
Summary We have covered: In C, Java, and Python... Terminal input/output Data types, operators, statements Multi-file programs 57