CPS 506 Comparative Programming Languages Imperative Programming Language Paradigm.

Slides:



Advertisements
Similar presentations
Chapter 25 Perl and CGI (Common Gateway Interface)
Advertisements

Overview of programming in C C is a fast, efficient, flexible programming language Paradigm: C is procedural (like Fortran, Pascal), not object oriented.
Intermediate Code Generation
Programming Languages and Paradigms
Fortran Jordan Martin Steven Devine. Background Developed by IBM in the 1950s Designed for use in scientific and engineering fields Originally written.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 12 Imperative Programming I really hate this.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 5 Types Types are the leaven of computer programming;
CS 898N – Advanced World Wide Web Technologies Lecture 8: PERL Chin-Chih Chang
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Scripting Languages Chapter 6 I/O Basics. Input from STDIN We’ve been doing so with $line = chomp($line); Same as chomp($line= ); line input op gives.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 12 Imperative Programming I really hate this.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 12 Imperative Programming I really hate this.
G. Levine Chapter 6 Chapter 6 Encapsulation –Why do we want encapsulation? Programmer friendliness- programmer need not know about these details –Easier.
1 Key Concepts:  Why C?  Life Cycle Of a C program,  What is a computer program?  A program statement?  Basic parts of a C program,  Printf() function?
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 5 Types Types are the leaven of computer programming;
Programming Languages Tucker and Noonan
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 12 Imperative Programming I really hate this.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 25 – Perl and CGI (Common Gateway Interface) Outline 25.1 Introduction 25.2 Perl 25.3 String Processing.
Shell Scripting Awk (part1) Awk Programming Language standard unix language that is geared for text processing and creating formatted reports but it.
Chapter 12.  Programs written in imperative programming languages consist of ◦ A program state ◦ Instructions that change the program state  Program.
1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010.
Imperative Programming
Practical Extraction & Report Language PERL Joseph Beltran.
CIS Computer Programming Logic
Lists in Python.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Lecture 2 Object Oriented Programming Basics of Java Language MBY.
C Programming Language Bill Jensen CS 354 May, 3 rd 2007.
History of C 1950 – FORTRAN (Formula Translator) 1959 – COBOL (Common Business Oriented Language) 1971 – Pascal Between Ada.
Computer Science 101 Introduction to Programming.
Chapter 8 High-Level Programming Languages. 8-2 Chapter Goals Describe the translation process and distinguish between assembly, compilation, interpretation,
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Introduction to PHP A user navigates in her browser to a page that ends with a.php extension The request is sent to a web server, which directs the request.
PLLab, NTHU,Cs2403 Programming Languages Expression and control structure Kun-Yuan Hsieh Programming Language Lab., NTHU.
Class 2Intro to Databases Goals of this class Include & Require in PHP Generating Random Numbers in PHP Arrays – Numerically Indexed and Associative Program.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Introduction to Perl Yupu Liang cbio at MSKCC
Perl Language Yize Chen CS354. History Perl was designed by Larry Wall in 1987 as a text processing language Perl has revised several times and becomes.
Perl: Lecture 1 The language. What Perl is Merger of Unix tools – Very popular under UNIX – shell, sed, awk Programming language – C syntax Scripting.
Ch. 5 Ch. 51 jcmt CSE 3302 Programming Languages CSE3302 Programming Languages (more notes) Dr. Carter Tiernan.
Types(1). Lecture 52 Type(1)  A type is a collection of values and operations on those values. Integer type  values..., -2, -1, 0, 1, 2,...  operations.
5 1 Data Files CGI/Perl Programming By Diane Zak.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Programming in C++ Dale/Weems/Headington Chapter 1 Overview of Programming and Problem Solving.
Department of Electrical and Computer Engineering Introduction to Perl By Hector M Lugo-Cordero August 26, 2008.
Ch. 5 Ch. 51 jcmt Summer 2003Programming Languages CSE3302 Programming Languages (more notes) Summer 2003 Dr. Carter Tiernan.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
Just a Little PHP Programming PHP on the Server. Common Programming Language Features Comments Data Types Variable Declarations Expressions Flow of Control.
Perl Variables: Array Web Programming1. Review: Perl Variables Scalar ► e.g. $var1 = “Mary”; $var2= 1; ► holds number, character, string Array ► e.g.
By Mr. Muhammad Pervez Akhtar
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Week Four Agenda Link of the week Review week three lab assignment This week’s expected outcomes Next lab assignment Break-out problems Upcoming deadlines.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
 History  Ease of use  Portability  Standard  Security & Privacy  User support  Application &Popularity Today  Ten Most Popular Programming Languages.
PERL By C. Shing ITEC Dept Radford University. Objectives Understand the history Understand constants and variables Understand operators Understand control.
C Part 1 Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens A History Lesson Development of language by Dennis Ritchie at Bell.
The Scripting Programming Language
Introduction to Programming the WWW I CMSC Winter 2003 Lecture 17.
Chapter 1: Preliminaries Lecture # 2. Chapter 1: Preliminaries Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation.
Information and Computer Sciences University of Hawaii, Manoa
Definition of the Programming Language CPRL
Chapter 6: Data Types Lectures # 10.
C Language VIVA Questions with Answers
College of Computer Science and Engineering
High Level Programming Languages
Programming Languages 2nd edition Tucker and Noonan
Lecture 7: Types (Revised based on the Tucker’s slides) 10/4/2019
Presentation transcript:

CPS 506 Comparative Programming Languages Imperative Programming Language Paradigm

Introduction Oldest and most well-developed paradigm Mirrors computer architecture Series of steps – Retrieve input – Calculate – Produce output Procedural Abstraction – Assignments – Loops – Sequences – Conditional Statements Examples – Cobol, Fortran, Ada, Pascal, C, Perl 2

What Makes a Language Imperative? In a von Neumann machine memory holds: – Instructions – Data Intellectual heart: assignment statement – Others: Conditional branching Unconditional branch (goto) 3

Flowchart 4

Procedural Abstraction Procedural abstraction allows the programmer to be concerned mainly with a function interface, ignoring the details of how it is computed. The process of stepwise refinement utilizes procedural abstraction to develop an algorithm starting with a general form and ending with an implementation. – Ex: sort(list, len) 5

Expressions and Assignment Assignment statement is fundamental: target = expression Copy semantics Expression is evaluated to a value, which is copied to the target; used by imperative languages Reference semantics Expression is evaluated to an object, whose pointer is copied to the target; used by object- oriented languages. 6

There exist vast libraries of functions for most imperative languages. Partially accounts for the longevity of languages like Fortran, Cobol, and C. 7

Turing Complete Integer variables, values, operations Assignment If Goto Structured programming revolution of 1970s replace the Goto with while loops. 8

C C was originally designed for and implemented on the UNIX operating system on the DEC PDP-11, by Dennis Ritchie. Its parent and grandparent are B and BCPL, respectively. The operating system, the C compiler, and essentially all UNIX applications programs are written in C. C is not tied to any particular hardware or system, however, and it is easy to write programs that will run without change on any machine that supports C. 9

Influences Multics, PL/I Application: typesetting documentation PDP-11: 16-bit minicomputer; 32 KB memory BCPL: typeless Portability: big-endian vs. little-endian machines Good code from a non-optimizing compiler Hardware support for: ++, --, +=, etc. 10

General Characteristics Relatively low level language Macro facility Conditional compilation Lacks: iterators, generics, exception handling, overloading Assignments are expression; ex: strcpy 11

Dynamic Allocation int *a;... a = malloc(sizeof(int) *size); /* ANSI C: a = (int *) malloc(sizeof(int) *size); C++: a = new int[size]; */ /* deallocation left to programmer */ 12

#include #include "node.h" struct node *mknodebin(char op1, struct node *left,struct node * right) { struct node *result; result = (struct node*) malloc(sizeof(struct node)); result->kind = binary; result->op = op1; result->term1 = left; result->term2 = right; return result; } 13

struct node *diff(char x, struct node *root){ struct node *result; switch (root->kind) { case value: result = mknodeval(0); break; case var: result = mknodeval( root->id == x?1:0); break; 14

case binary: switch (root->op) { case '+': result = mknodebin( Plus, diff(x, root->term1), diff(x, root->term2)); break;... return result; } 15

Ada developed in late 1970’s by US Department of Defense (DoD) DoD spending billions of dollars on software over 450 languages in use solution: standardize on one language Higher Order Language Working Group 16

General Characteristics influencs: Algol, Pascal large language; case insensitive unlike C, array indexing errors trapped type safe generics exception handling -- strictly control 17

type union = record case b : boolean of true : (i : integer); false : (r : real); end; var tagged : union; begin tagged := (b => false, r => 3.375); put(tagged.i); -- error 18

generic type element is private; type list is array(natural range <>) of element; with function ">"(a, b : element) return boolean; package sort_pck is procedure sort (in out a : list); end sort_pck; 19

package sort_pck is procedure sort (in out a : list) is begin for i in a'first.. a'last - 1 loop for j in i+1.. a'last loop if a(i) > a(j) then declare t : element; begin t := a(i); a(i) := a(j); a(j) := t; end; end if; 20

type Matrix is array (Positive range <> of Float, Positive range <> of Float); function "*" (A, B: Matrix) return Matrix is C: Matrix (A'Range(1), B'Range(2)); Sum: Float; begin if A'First(2) /= B'First(1) or A'Last(2) /= B'Last(1) then raise Bounds_Error; end if; 21

for i in C'Range(1) loop for j in C'Range(2) loop Sum := 0.0; for k in A'Range(2) loop Sum := Sum + A(i,k) * B(k,j); end loop; Result(i,j) := Sum; end loop; return C; end "*"; 22

Perl is: widely used a scripting language (originally for Unix) dynamically typed encourages a variety of styles supports regular expression pattern matching 23

Scripting Languages “glue” take output from one application and reformat into desired input format for a different application. most time is spent in the underlying applications. also used for Web applications 24

General Characteristics dynamically typed default conversion from one type to another (vs. Python) result is distinct operators; ex:. for string concatenation types: numbers, strings, regular expressions dynamic arrays: indexed and associative 25

String vs. numeric comparisons: 10 < 2 # false - numeric 10 < "2" # false "10" lt "2" # true - string 10 lt "2" # true 26

Indexed = (2, 3, 5, 7); # size is 4... $a[7] = 17; # size is 8; # $a[4:6] are = (1, 2, = qw/This is an = qw/Mon Tue Wed Thu Fri Sat Sun/; print = (1.. 10); print # Prints number starting from 1 to 10 27

Indexed = (1,2,3); print = (1,2,3); $array[50] = 4; print "Size: print "Max Index: ", $#array,"\n"; This will return Size: 51 Max Index: 50 28

Associative Arrays %d = (“bob” => “3465”, “allen” => “3131”, “rebecca” => “2912”); print $d{“bob”};# prints

Many different ways of saying the same thing Much of the syntax is optional; Perl 5 added support for classes and objects Great strengths: support for regular expressions Scalar variables start with a $ Indexed arrays with Hash arrays with % 30

Strings Double quotes: special characters interpreted – ex: “$a \n” – forms: “ “, qq{ }, qq/ / Single quotes: special characters uninterpreted – forms: ‘ ‘, q{ }, q/ / 31

while (<>) {... } is same as: while ($_ = ) {... } where: <> is read a line returns undef at end of file; undef interpreted as false no subject: $_ if $_ =~ m/pattern/ # implied subject, operator 32

%hash = ('name' => 'Tom', 'age' => 19); print %hash; nameTomage19 sub display_hash { my (%hash) foreach (%hash) { print "$_ => $hash{$_}\n"; } 33

#! /usr/bin/perl if < 1) { die "Usage mygrep string \n" ; } use strict; my $string = my $ct = 0; my $line; while ($line = ) { $ct++; if ($line =~ m/$string/) { print STDOUT $ct, ":\t", $line; } exit; 34

Ex: Mailing Grades typical glue program student grades kept in a spreadsheet after each project/test, mail each student her grades include averages export data in comma-separated value format (CSV) CSV format varies by spreadsheet 35

::Proj1:Test1:::::Total:Average ::50:100::::::150: : : Average::88:91:::::135:90 36

Main program - part 1 retrieves class designation from command line opens CSV file for input or die is a common idiom declares some useful constants (some should be command line options) 37

#! /usr/bin/perl use strict; my $class = shift; my $suf = ".csv"; open(IN, "<$class$suf") || die "Cannot read: ". "$class$suf\n"; my $sep = ":"; my $tab = 8; 38

Main program - part 2 reads grade column names reads maximum points for each column adds 100% array 39

# read header lines: titles, max grades = &readSplit(); = &readSplit(); '100%'); 40

Main program - part 3 loop reads 1 student per iteration (line) chomp() idiom; irregular tr deletes “, ' tokenizer for Perl last line pops averages from student array and splits values into columns (printed with each student) 41

# read students while ( ) { chomp; tr /"'//d; $_); } = split(/$sep/, 42

Main - part 4 for loop generates mail, 1 student per iteration student grades split into columns subroutine call; & optional mails averages to script invoker prints number of student s generated 43

# gen mail for each student my $ct = 0; foreach { = split(/$sep/); $ct += } $ave[1] = $ENV{"USER"}; print " s sent: $ct\n"; exit; 44

sub readSplit reads a line; note $_ is global chomp idiom tr deletes quotes splits line and returns array of columns 45

sub readSplit { $_ = ; chomp; tr /"'//d; = split(/$sep/); } 46

sub sendMail no formal parameters shift -- call by array reference -- call by reference return if student has no address open pseudo file or die MAIL is a pipe to Berkeley mail command s option is subject $ is mail address 47

sub sendMail { my $name = shift; my $ = shift; return 0 unless $ ; open(MAIL, "| mail -s '$name Grades' $ ") || die "Cannot fork mail: $!\n"; print MAIL "GRADE\t\tYOUR\tMAX\tCLASS\n", "NAME\t\tSCORE\tSCORE\tAVE\n\n"; 48

sub sendMail -- for loop for each column skip column if empty header -- not a grade otherwise print header if column value starts with a digit, round value to an integer; otherwise print value print maximum points print average (rounded) 49

my $ct = 1; foreach { $ct++; next unless $hdr[$ct]; print MAIL "$hdr[$ct]\t"; print MAIL "\t" if length($hdr[$ct]) < $tab; if (/^\d/) { print MAIL int($_ + 0.5); } else { print MAIL $_; } 50

print MAIL "\t$max[$ct]\t"; if ($ave[$ct] =~ /^\d/) { print MAIL int($ave[$ct] + 0.5); } else { print MAIL $ave[$ct];} print MAIL "\n"; } # foreach return 1; } # sub sendMail 51

$_ : implied object/subject $ARG : default input $. : input line number $/ : input record separator : default \n – undef $/; $_ = ; # reads entire file $, : output field separator in print $\ : output record separator $" : list separator : default space $[ : starting array index : default zero 52

Regular Expressions Operators m// -- match, m optional s/// -- substitute split -- array returning function 53

Modifiers i -- case insensitive m -- treat string as multiple lines s -- treat string as a single line x -- extend with whitespace and comments 54