Programming Languages Exam 2

0.0(0)
studied byStudied by 0 people
0.0(0)
full-widthCall with Kai
GameKnowt Play
New
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/113

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

114 Terms

1
New cards

Name four types of looping constructs.

1. for

2. foreach

3. while

4. do-while

2
New cards

Why do programming languages provide more than one type of loop?

Writability; it allows programmers to choose the best loop construct for the task at hand.

3
New cards

What is short-circuit evaluation?

It is when part of an expression is not evaluated since that part has become irrelevant.

4
New cards

Provide an example of a short-circuit evaluation using Perl.

$x = 3;

if ($x > 0 || $x < 10)

{

# do blah blah blah

}

# the test of $x < 10 is short-circuited since $x > 0 is true

5
New cards

What are overloaded operators?

It is when you define a common operator like + or << for a class in which that operator is not defined.

6
New cards

Explain using an example of when it would be necessary to overload operators.

Suppose you created a Fraction class. You could overload the + and << operators so that you could add or display Fraction objects.

7
New cards

What is a union type?

Like a C++ struct, except the data members do not all exist at the same time. They share one memory space so only one data member may be active at a given time.

8
New cards

Provide a C++ definition of a union that could be helpful in an application.

union payroll

{

int annualSalary;

double hourlyRate;

};

9
New cards

What is a tuple?

An ordered, immutable sequence of elements.

10
New cards

Give an example of a Python tuple.

player = ("Cade", "Cunningham", 25.4, 6.3, 9.4)

11
New cards

immutable

unable to be changed

12
New cards

Who created Perl, and what year was it created?

Larry Wall; 1987

13
New cards

Why was Perl created?

For scripting and string/text manipulation in UNIX-like environments.

- there are many built-in text-manipulation functions and operators that can process text in an easier way compared to traditional languages.

14
New cards

What does Perl stand for?

Practical Extraction and Report Language

15
New cards

T/F: Perl uses a compiler.

F; it uses an interpreter

16
New cards

What new features did Perl 2.0, released in 1988, provide?

- new regexp routines

- support for /(foo | bar)/

- support for /(foo)*/ and /(foo)+/

- \s for whitespace, \S for non-, \d for digit, \D for nondigit

- open pipe to forked off script

- wait, sort operators, file globbing

- foreach loop

17
New cards

What does Perl's original man page highlight?

- interpreted language

- used for scanning arbitrary text files, extracting info from those text files, and printing reports based on that info

- used for system management tasks

- practical (easy-to-use, efficient, complete) rather than beautiful (tiny, elegant, minimal)

- combines best features of C, sed, awk, and sh

- expression syntax similar to C

- translators to turn sed and awk scripts into Perl scripts

18
New cards

What are Perl's strengths?

- feature rich

- Perl community has been contributing and using the language for over 30 years

- there are over 25,000 extension modules

- CPAN - Comprehensive Perl Archive Network

- freely available - binaries or source

- not owned - maintained and ported to other platforms by Wall and other volunteer programmers

- easy access to system calls and interaction with other programs

- can create web applications with CGI (Common Gateway Interface) programming

19
New cards

What are some similar languages to Perl?

- before Perl: based on shell languages, awk, sed, C

- after Perl: Python, PHP

20
New cards

What are some drawbacks to Perl?

- good for writing quick-and-dirty programs, but it is not as practical for writing large software applications

- rich language with many features, so it can get complicated reading someone else's code

21
New cards

What is the status of Perl today?

- current version of Perl is 5.40.1

- popularity has declined over the last decade, losing ground to languages such as Python

- Perl6 is a new sister language that is not intended to replace Perl5 (Perl6 is compiled, object-oriented, functional, uses parallelism and definable grammars)

22
New cards

hash

also called an associative array, is used for data in which each item has a unique attribute, or key

23
New cards

How do you create a hash in Perl?

use the % symbol

24
New cards

example of a hash

%vehicles = ('ABC123', 'John Doe', 'XYZ777', 'Betty Smith', DSNY14', 'Donald Duck', ...);

%vehicles = ( ); (empty)

25
New cards

How do you reference a specific hash?

similar to an array index, specify it by its key, using curly braces instead of brackets

ex. $vehicles{12UNIX} = 'Dennis Ritchie';

if (exists $vehicles{$key})

{

print "Vehicle w/ plate $key exists";

}

26
New cards

Perl hashes example using arrays

@plates = keys % vehicles;

@names = values % vehicles;

foreach $plate (sort keys %vehicles)

{

print "owner: $vehicles{$plate} ";

print "license: $plate\n";

}

How this works:

- It maps license plate numbers (keys) to owner names (values).

- keys % vehicles returns a list of all the license plate numbers

- values % vehicles returns a list of all the owners

- the lists are stored in @plates and @names

- sort allows license plate numbers to be sorted in ascending order

- Since the keys are the plate numbers, the owner is printed out when using $vehicles{$plates} in the foreach loop.

- the license plate number is printed out here since we stored the keys into the plates array.

27
New cards

How do you call a subroutine in Perl?

use the &, but you can call without & if the function is defined before the call

28
New cards

What does @_ return in reference to subroutines?

the number of parameters

ex. $num_params = @_;

29
New cards

What does @_ contain in reference to subroutines?

the actual parameters

ex. $_[0], $_[1], ...

30
New cards

T/F: A function can return a value with the return statement.

T; if no return statement is executed, the subroutine will return the value of the final statement that was performed

31
New cards

example of a Perl subroutine

#!/usr/bin/perl

my ($len, $wid, $price) =

(75, 80, 3.25);

$cost=

&fenceCost($len, $wid, $price);

print "The total cost is $cost\n";

sub fenceCost

{

my ($l,$w,$p) = @_;

my $perimeter = 2 $l + 2 $w;

my $total = $perimeter * $p;

return $total;

}

32
New cards

global scope

refers to a variable that is available to all parts of a script and exists as long as the script is running

33
New cards

local scope

refers to a variable that has limited scope and might pop in and out of existence depending on what part of the script is currently executing

34
New cards

T/F: Global variables are easy to create and easy to use in Perl.

T; in fact, any variable not explicitly declared with local or my is automatically a global variable

35
New cards

Why are global variables not good?

- large scripts are more difficult to debug when only globals are used

- questions could arise like: Where did that variable come from? When does it get updated? What is it doing?

- variable names may accidentally be used multiple times

- creating reusable Perl libraries is a nightmare

36
New cards

local keyword in Perl

specifies that variables will be local to the currently executing block , loop, or subroutine. The variable is also available to all nested subroutines.

37
New cards

my keyword in Perl

specifies that those variables are local to the current block, loop, or subroutine. It is not available to nested subroutines.

38
New cards

using my and local with more than one variable

must be placed within parenthesis

ex. local ($x, $y);

39
New cards

Example: Local vs. My

study this example and trace through the code in PerlSubroutines powerpoint

40
New cards

reference parameters

the argument list that you get inside your subroutine via @_ are implicit references to the values that were passed in from outside

41
New cards

Do variables passed as parameters have their values modified if you modify the contents of the @_ array itself inside the body of the subroutine?

yes

42
New cards

example of using reference parameters

#!/usr/bin/perl

@prices = (24.95, 35.75, 55.69, 88.59);

print "Prices before the sale\n";

&show(@prices);

&sale(@prices);

print "Prices after the sale\n";

&show(@prices);

sub show {

for (my $i=0; $i < @_; $i++) {

printf("\$%4.2f\n", $_[$i]);

}

}

sub sale {

for (my $i=0; $i < @_; $i++) {

$_[$i] *= 0.95;

}

}

43
New cards

example of recursion with Perl

#!/usr/bin/perl

sub factorial {

my $num = $_[0];

return (1) if ($num <=1);

return ($num * factorial($num-1));

}

print factorial(8);

44
New cards

data type

defines a collection of data values and a set of predefined operations on those values

45
New cards

Which language introduced user-defined data types?

ALGOL 68

46
New cards

user-defined data types

- data structure that is designed for a specific need

- improved readability through the use of meaningful names for types

- allow type checking of the variables of a special category of use

- aids modifiability; programmers can change the type of category of variables in a program by changing a type definition statement only

47
New cards

abstract data types

interface of a type, which is visible to the user, is separated from the representation and set of operations on values of that type, which are hidden from the user; all types provided by high-level programming languages are of this kind

48
New cards

descriptor

collection of the attributes of a variable

49
New cards

object

values of a variable and the space it occupies; more clear definition: instances of user-defined and language-defined abstract data types

50
New cards

primitive data types

data types that are not defined in terms of other types

51
New cards

What types of integers does Java have?

byte, short, int, and long

52
New cards

twos complement

way computers store negative numbers; formed by taking the logical complement of the positive version of the number and adding 1

53
New cards

When were Boolean types introduced?

came with the creation of ALGOL 60

54
New cards

slices

references to substrings of a given string

55
New cards

library functions for character strings in C and C++

- strcpy (moves strings)

- strcat (catenates one given string onto another)

- strcmp (lexigraphically compares two given strings)

- strlen (returns the number of characters, not counting the null character, in the given string)

56
New cards

enumeration type

one in which all the possible values, which are named constants, are provided, or enumerated, in the definition

ex in C++:

enum colors {red, blue, green};

colors myColor = blue, yourColor = red;

myColor++ assigns green to myColor since next in value order

57
New cards

What's another term for an array?

finite mappings

58
New cards

using negative subscripts in Perl

- subscript value is an offset from the end of the array

- ex. if a list had 5 elements, $list[-2] references the element with subscript 3 (subscript range is 0..4)

59
New cards

static array

one in which subscript ranges are statically bound and storage allocation is static (done before run time)

60
New cards

fixed stack-dynamic array

one in which the subscript ranges are statically bound, but allocation is done at declaration elaboration time during execution

61
New cards

fixed heap-dynamic array

similar to fixed stack-dynamic array, in that the subscript ranges and the storage bindings are both fixed after storage is allocated; difference is storage is allocated from the heap, rather than the stack

62
New cards

heap-dynamic array

one in which binding of subscript ranges and storage allocation is dynamic and can change any number of times during the array's lifetime

63
New cards

examples of array types in C and C++

- arrays with static keyword are static

- regular arrays without keyword are fixed stack-dynamic arrays

- for dynamic arrays, new and delete are used to manage heap storage

64
New cards

rectangular array

multidimensional array in which all of the rows have the same number of elements and all of the columns have the same number of elements

65
New cards

jagged array

array where lengths of rows don't have to be the same

66
New cards

What is the equivalent of associative arrays in Python and Perl?

Python: dictionaries

Perl: hashes

67
New cards

How is a tuple different from a record?

elements are not named; don't have a particular type

68
New cards

dangling pointer/dangling reference

pointer that contains the address of a heap-dynamic variable that has been deallocated; worst case could cause store merger to fail in storage management system

ex in C++:

int * arrayPtr1;

int * arrayPtr2 = new int[100]; arrayPtr1 = arrayPtr2;

delete [] arrayPtr2;

// Now, arrayPtr1 is dangling, because the heap storage to which it was pointing has been deallocated.

69
New cards

lost heap-dynamic variable/memory leakage

allocated heap-dynamic variable that is no longer accessible to the user program; garbage

- usually caused by having a pointer point to a newly created heap-dynamic variable, and then the pointer is changed to point to another newly created dynamic variable without deallocating or moving previous variable

70
New cards

reference type

similar to a pointer, but pointers refer to address in memory while this refers to an object or a value in memory

71
New cards

T/F: A programming language is strongly typed if type errors are always detected.

T

72
New cards

data type vs. type system

data type: defines a set of values and a collection of operations on those values

type system: set of types and the rules that govern their use in programs

73
New cards

referential transparency

where any two expressions in the program that have the same value can be substituted for one another anywhere in the program, without affecting the action of the program

74
New cards

pass-by-value

the value of the actual parameter is used to initialize the corresponding formal parameter, which then acts as a local variable in the subprogram, thus implementing in-mode semantics

75
New cards

pass-by-result

implementation model for out-mode parameters; no value is transmitted to the subprogram. The corresponding formal parameter acts as a local variable, but just before control is transferred back to the caller, its value is transmitted back to the caller's actual parameter, which obviously must be a variable.

- has issue of order mattering in calling function parameters

76
New cards

pass-by-value-result (pass-by-copy)

implementation model for inout-mode parameters in which actual values are copied

- combo of pass-by-value and pass-by-result

- value of actual parameter is used to initialize the formal parameter, which then acts as a local variable

- at subprogram termination, the value of the formal parameter is transmitted back to the actual parameter

77
New cards

pass-by-reference

second implementation model for inout-mode parameters

- rather than copying data values back and forth, it transmits an access path, usually just an address, to the called subprogram

- the called subprogram is allowed to access the actual parameter in the calling program unit; the actual parameter is shared with the called subprogram

- efficient in both time and space

78
New cards

pass-by-name

inout-mode parameter transmission method that does not correspond to a single implementation model; the actual parameter is, in effect, textually substituted for the corresponding formal parameter in all its occurrences in the subprogram

- complex and inefficient, so isn't used very often

79
New cards

What does chomp( ) do?

removes whitespace from variable

80
New cards

How does Perl compare strings?

uses eq; to compare numerical values, uses ==

81
New cards

What is a dynamic webpage?

a webpage that changes

82
New cards

CGI

defines how web server and program communicate

83
New cards

T/F: Some query strings should be hidden.

T; things like passwords must be secure

84
New cards

How do you change file permissions?

use change mod (chmod)

- read - 4

- write - 2

- execute - 1

- first field is my permissions, second is group permissions, and third is outside group permissions

- add together permissions to specify how you want the file to be visible

- ex. chmod 755 allows r, w, and e for me, r and e for group and outside group (doesn't allow editing to anyone but me)

85
New cards

command line switches vs. arguments

arguments are required, whereas switches are optional

ex. of argument: cd dirname

ex. of switch: ls -l

86
New cards

methodology

process you use to answer your research question

87
New cards

$x = 8.9;

printf("x is %7.2f\n", $x);

output: x is 8.90

- 7.2f specifies that there can be 7 total characters (including characters before, decimal point, and characters after), and 2 characters after the decimal point

- example above has 4 total characters (but could have up to 7)

88
New cards

file processing modes in Perl

3 file modes: read, write, append

- to specify write, use >file.txt

- to specify append, use >>file.txt

89
New cards

write vs. append

- write: overwrites file

- append: adds to end of file, keeping existing contents

90
New cards

opening/closing a Perl file

open(FP, "file.txt") || die("bye");

- makes sure if file doesn't open, program terminates

close(FP);

91
New cards

reading data from a file into an array/list line-by-line

@data = ;

92
New cards

How do you calculate the time it takes to complete a task?

you take into account the total number of items to operate on and the number of processes available

- ex. Suppose it takes 1 ms to add 2 matrices. How long would it take to add 8 matrices?

sum = a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7

Time(n = 8, p = 1) = 7 ms (must add a0 + a1, then each one incrementally, resulting in 7 times)

Time(n = 8, p = 4) = 3 ms (must add a0 + a1, a2 + a3, a4 + a5, a6 + a7, then sum1 + sum2, sum3 + sum4, then sum + sum)

- more processors, less time

93
New cards

How do you calculate speedup?

divide the time it takes with one processor by the time it takes with multiple processors

ex. T(n = 8, p = 1)/T(n = 8, p = 4) = 7 ms / 3 ms = 2.3

94
New cards

How do you calculate efficiency?

Divide speedup by the given multiple processors.

ex. S(n = 8, p = 4) / p = 4 => (7/3) / 4 => 7/12 => about 58%

95
New cards

What are you assuming when calculating time, speedup, and efficiency?

1. Tcomm = 0

2. processes are homogenous

3. processes are not doing the work

96
New cards

process

active instance of a program

97
New cards

What are the different types of interprocess communication (IPC)?

1. file (one-way)

2. pipe (one-way or two-way; must be related, on same computer)

3. socket (one-way or two-way; must have IP address and port # since on separate computers)

4. RPC (remote procedure call); allows computer to run a function on another computer

5. RMI (remote method invocation); objects are passed rather than just data like with RPC

98
New cards

What does $result = 'finger'; do?

shows everyone using server

99
New cards

What does exec('ls'); do?

leaves program, then does ls command

100
New cards

What does grep do?

searches files