30
Programming Languages Programming Languages Tucker and Noonan Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural Abstraction 12.3 Expressions and Assignment 12.4 Library Support for Data Structures 12.5 C 12.6 Ada 12.7 Perl

CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

  • View
    241

  • Download
    1

Embed Size (px)

Citation preview

Page 1: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

Programming LanguagesProgramming LanguagesTucker and NoonanTucker and Noonan

Chapter 12: Imperative Programming

12.1 What Makes a Language Imperative?12.2 Procedural Abstraction12.3 Expressions and Assignment12.4 Library Support for Data Structures12.5 C12.6 Ada12.7 Perl

Page 2: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

Imperative ProgrammingImperative Programming

• Oldest and most well-developed paradigm

• Mirrors computer architecture

• Typical Languages– Fortran, Pascal– C, Clite– Ada 83– Perl

Page 3: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

What Makes Languages Imperative?What Makes Languages Imperative?

• In a von Neumann machine memory holds:– Instructions– Data– Intellectual heart: assignment statement– Others:

• Conditional branching• Unconditional branch (goto)

Page 4: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

FlowchartFlowchart

Page 5: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

Procedural AbstractionProcedural 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)

Page 6: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

Expressions and AssignmentExpressions 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.

Page 7: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

• There exist vast libraries of functions for most imperative languages.

• Partially accounts for the longevity of languages like Fortran, Cobol, and C.

• Typical libraries for data structures– Iterators– Vectors– Lists– Stacks, queues, deques, priority queues– Sets and bags– Maps

Library Procedures/FunctionsLibrary Procedures/Functions

Page 8: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

SupportsSupports• Turing Completeness

– Assignment– Sequence– Conditional statement: If– Loop statement:

• Goto• Structured programming revolution of 1970s replace the

goto with while loops.

• Other supports– Integer variables, values, operations– Input/output, error/exception handling, library support

Page 9: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

CC• “C was originally designed for and implemented on the

UNIX• Operating system on the DEC PDP-11, by Dennis Ritchie.• The operating system, the C compiler, and essentially all• UNIX applications programs (including all of the software• Used to prepare this book) 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.”

Page 10: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

InfluencesInfluences

• 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.

Page 11: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

General CharacteristicsGeneral Characteristics

• Relatively low level language

• Macro facility

• Conditional compilation

• Lacks: iterators, generics, exception handling, overloading

• Assignments are expression– ex: strcpy

Page 12: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

Dynamic AllocationDynamic 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 */

Page 13: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

Ex: GrepEx: Grep• Grep is a Unix utility to search for strings in a

text file• #include libraries• Two functions

– main processes command line arguments– find

• Forward reference– First signature/prototype, second definition

• Procedure– reads file– search each line – write line if match– fgets

Page 14: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

Ex: AverageEx: Average

• Compute min, max, average of a set of numbers

• Formatting: scanf, printf

• Conditional assignment

• 2nd argument to scanf must be an address– caught by some compilers– segment violation at run time

Page 15: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

Average C CodeAverage C Code#include <stdio.h>Int main(int argc, char *argv[]) {

int ct, number, min, max, sum;sum = ct = 0;printf(“Enter number: “);while (scanf(“%d”, &number) != EOF) {

if (ct=0) min = max = number;ct++;sum += number;min = number < min? number : min;max = number > max? number : max;printf(“Enter number: “);

}printf(“%d numbers read\n”, ct);if (ct>0)

printf(“Average: \t%d\n”, sum / ct);printf(“Maximum:\t%d\n”, max);printf(“Minimum: \t%d\n”, min);

}}

Page 16: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

AdaAda• Developed in late 1970’s by DoD• DoD spending billions of dollars on software• Over 450 languages in use• Solution: standardize on one language• Higher Order Language Working Group• Ada 83

– problem: size of language/compiler– no subsets rule

• Hard times during 1990s– use of COTS

• Renewed interest– COTS proved problematic– development of Spark Ada– NYU GNAT (Ada) compiler

Page 17: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

General CharacteristicsGeneral Characteristics

• Influences: Algol, Pascal

• Large language; case insensitive

• Unlike C, array indexing errors trapped

• Type safe

• Union

• Generics

• Exception handling -- strictly control

Page 18: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

type union(b: boolean) is =record

case b iswhen true =>

i : integer;when false =>

r : float;end case

end record;tagged : union;begin tagged := (b => false, r => 3.375);

put(tagged.i); -- errorcase tagged(b) is

when true =>put(tagged.i);

when false =>put(tagged.r);

end case

Tagged UnionTagged Union

Page 19: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

• Generic sort

– Sort various data set of different types• Code

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;

GenericsGenerics

Page 20: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

package body sort_pck isprocedure sort (in out a : list) isbegin

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;

end loopend loop;

end sort;end sort_pck;

Page 21: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

Ada: AverageAda: Average

• Comparable to C

• Infinite loop; exit on end of file via exception

• Inner loop to catch errors caused by non-numeric data

• Exception handling

• Wordy than C

Page 22: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

Ada: Average CodeAda: Average Codewith Ada.Text_IO: with Ada.Integer_Text_IO;Procedure Average is sum := 0; Ct := 0; Ada.Text_IO.Put(“Enter number: “); loop

begin Ada.Integer_Text_IO.Get(Number);

if Ct = 0 thenMin := Number;Max := Number;

end ifCount := Count + 1;if Number < Min then

Min := Number;elsif Number > Max then

Max := Number;end if

exception when Constraint_Error =>

Ada.Text_IO.Put(“Value out of range.”);

when Ada.Text_IO.Data_Error =>Ada.Text_IO.Put(“Value not an

integer.“); when Ada.Text_IO.End_Error =>

exit;end

Ada.Text_IO.Put(“Enter number: “); end loop

Ada.Integer_Text_IO.Put(Ct, 5); Ada.Text_IO.Put(“ numbers read”); Ada.Text.IO.New_Line; if Ct > 0 then Ada.Text_IO.Put(“Average: “);

Ada.Integer_Text_IO.Put(Sum/ Ct);Ada.Text.IO.New_Line;Ada.Text_IO.Put(“Masimum: “);Ada.Integer_Text_IO.Put(Max);Ada.Text.IO.New_Line;Ada.Text_IO.Put(“Minimum: “);Ada.Integer_Text_IO.Put(Min);Ada.Text.IO.New_Line;

end ifEnd Average;

Page 23: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

• Widely used• A scripting language (originally for Unix)• Dynamically typed• Encourages a variety of styles• Supports regular expression pattern matching• 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

PerlPerl

Page 24: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

Scripting LanguagesScripting 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

Page 25: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

• Indexed Arrays– @a = (2, 3, 5, 7); # size is 4– ...– $a[7] = 17; # size is 8; – # $a[4:6] are undef

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

ArraysArrays

Page 26: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

1. #! /usr/bin/perl2. die "Usage mygrep string \n" if @ARGV < 1;3. use strict;4. my $string = shift;5. my $ct = 0;6. while (<>) {7. $ct++;8. print "$ct:\t$_" if /$string/;9. }10. exit;

Perl: GrepPerl: Grep

Page 27: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

• Scalar variables start with a $• Indexed arrays with an @• Hash arrays with %• Otherwise: bare word syntax error• use strict forces declaration of

variables– local : dynamic scoping– my : static scoping– NB: only 1 $_

Comments on GrepComments on Grep

Page 28: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

StringsStrings• Double quotes: special characters interpreted

– ex: “$a \n”– forms: “ “, qq{ }, qq/ /

• Single quotes: special characters uninterpreted– forms: ‘ ‘, q{ }, q/ /

• Comparison– 10 < 2 # false - numeric– 10 < "2" # false– "10" lt "2" # true - string– 10 lt "2" # true

Page 29: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

• while (<>) { ... }is same as:

while ($_ = <STDIN>) { ... }where <> is read a line

• returns undef at end of file; undef interpreted as false

• no subject: $_• if $_ =~ m/pattern/ # implied subject,

operator

Loops and PatternsLoops and Patterns

Page 30: CSC321: Programming Languages Programming Languages Tucker and Noonan Chapter 12: Imperative Programming 12.1 What Makes a Language Imperative? 12.2 Procedural

1. #! /usr/bin/perl

2. if (@ARGV < 1) { die "Usage mygrep string \n" ; }

3. use strict;

4. my $string = shift(@ARGV);

5. my $ct = 0;

6. my $line;

7. while ($line = <STDIN>) {

8. $ct++;

9. if ($line =~ m/$string/) {

10. print STDOUT $ct, ":\t", $line;

11. }

12. }

13. exit;

Alternative CodeAlternative Code