Programming Languages: Part 2. Robert M. Dondero, Ph.D. Princeton University

Similar documents
Programming Languages Part 2. Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University

Princeton University COS 333: Advanced Programming Techniques A Subset of C90

Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7

Princeton University COS 333: Advanced Programming Techniques A Subset of Java

Princeton University COS 333: Advanced Programming Techniques A Subset of PHP

SECTION II: LANGUAGE BASICS

Continued from previous lecture

The Design of C: A Rational Reconstruction: Part 2

JAC444 - Lecture 1. Introduction to Java Programming Language Segment 4. Jordan Anastasiade Java Programming Language Course

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Operators. Java operators are classified into three categories:

Informatics Ingeniería en Electrónica y Automática Industrial

Chapter 3: Operators, Expressions and Type Conversion

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B

CSC 1214: Object-Oriented Programming

Fundamental of Programming (C)

Princeton University Computer Science 217: Introduction to Programming Systems The Design of C

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Fundamentals of Programming

Introduction to Programming Using Java (98-388)

Expressions and Precedence. Last updated 12/10/18

Operators and Expressions

JAVA OPERATORS GENERAL

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Java Basic Programming Constructs

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

CS313D: ADVANCED PROGRAMMING LANGUAGE

Computers Programming Course 6. Iulian Năstac

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

Chapter 2. Elementary Programming

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

A flow chart is a graphical or symbolic representation of a process.

Writing Program in C Expressions and Control Structures (Selection Statements and Loops)

Part I Part 1 Expressions

Eng. Mohammed S. Abdualal

Reserved Words and Identifiers

3. Java - Language Constructs I

CSC Java Programming, Fall Java Data Types and Control Constructs

Information Science 1

Lecture 02 C FUNDAMENTALS

C Programming Language (Chapter 2 of K&R) Variables and Constants

Operators in java Operator operands.

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

COMP6700/2140 Operators, Expressions, Statements

Prof. Navrati Saxena TA: Rochak Sachan

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

Guide for The C Programming Language Chapter 1. Q1. Explain the structure of a C program Answer: Structure of the C program is shown below:

Operators and Expressions:

UNIT- 3 Introduction to C++

And Parallelism. Parallelism in Prolog. OR Parallelism

Lecture 3. More About C

Programming in C++ 5. Integral data types

2. C99 standard guarantees uniqueness of characters for internal names. A. 12 B. 26 C. 31 D. 48

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Chapter 2 Elementary Programming

CSI33 Data Structures

JAVA Programming Fundamentals

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Goals of C "" The Goals of C (cont.) "" Goals of this Lecture"" The Design of C: A Rational Reconstruction"

DM503 Programming B. Peter Schneider-Kamp.

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Computer System and programming in C

Quick Reference Guide

Introduction to Programming (Java) 2/12

TED Language Reference Manual

CT 229. Java Syntax 26/09/2006 CT229

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

File Handling in C. EECS 2031 Fall October 27, 2014

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Chapter 2 Primitive Data Types and Operations. Objectives

.Net Technologies. Components of.net Framework

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

STSCI Python Introduction. Class URL

Operators in C. Staff Incharge: S.Sasirekha

Primitive Data Types: Intro

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Quick Reference Guide

DM550 Introduction to Programming part 2. Jan Baumbach.

CS111: PROGRAMMING LANGUAGE II

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Computer Components. Software{ User Programs. Operating System. Hardware

Review for Test 1 (Chapter 1-5)

C - Basics, Bitwise Operator. Zhaoguo Wang

COMP Primitive and Class Types. Yi Hong May 14, 2015

Lecture Set 4: More About Methods and More About Operators

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Transcription:

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