Homework 3
CS 3411 - Programming Language Concepts - Fall '98
Due: 1:30pm Tuesday 17 November (Follow
handin instructions on the class Web page.)
Got Questions? Try office hours, email or the class
newsgroup.
-
Rewrite the following C code fragment without using goto
or break:
j = -3;
for ( i=0; i<3; i++ ) {
switch (j+2) {
case
3:
case
2: j--; break;
case
0: j+=2; break;
default:
j=0;
}
if (j>0) break;
j=3-i;
}
-
Devise a program in a language of your choice to determine at runtime
the relative precedence and associativity of the multiplication and
addition operators. Do the same thing for less-than and boolean or. Your
program should produce output something like this:
* has higher
precedence than +
* is left associative
+ is right associative
-
Consider the following Algol 60-style for statement:
for i := j+1 step i*j until 3*j
do j:= j+1
Assume the initial value of j is 1. List the sequence of values that i
assumes during execution of this loop assuming the following semantics:
a. All control expressions are evaluated once at loop
entry.
b. All control expressions are evaluated at the beginning
of each iteration.
c. step expression are evaluated once on loop
entry but until expressions are evaluated each time.
d. until expressions are evaluated once on loop
entry but step expressions are are evaluated each time.
-
The Bohm-Jacopini Result proves that gotos are unnecessary in the
sense that any program (flowcharts, actually) with gotos can be rewritten
using three constructs: 1) statement sequences, 2) if statements, 3) while
statements. Actually you don't even need if! Show how any if statement
can be rewritten using a while loop. In other words, show how:
if E then S
can always be transformed to an equivalent form:
while E' then S'
(You need to tell me what E' and S' look like in terms of E
and S.)
-
Ok. Get your Web browsers ready for this question! Find a reference or
tutorial for Fortran 90 somewhere on the Web and rewrite the following
code as a multiple selection (case, switch) statement in Fortran
90:
if (k=1) or (k=2) then j:=2*k-1
if (k=3) or (k=5) then j:=3*k+1
if (k=4) then j:=4*k-1
if (k=6) or (k=7) or (k=8) then j:=k-2
Assume that all variable are integer type.
-
PL/I has a wild feature that allows labels (goto targets) to be
assigned to variables and passed into procedures so you can do things like
this (this isn't precise PL/I syntax, just pseudo-code):
if ( A > B )
MY_LABEL = L100;
else
MY_LABEL = L200;
...
goto MY_LABEL;
Describe a situation where this might be useful and briefly
discuss its merits (advantages and disadvantages) as a language feature.
-
EXTRA CREDIT: Rewrite the following super-weird C code using
if-else statements. Feel free to experiment by running similar examples
or check C reference material.
int a, b, c, d, e;
a?b:c;
a?b:c?d:e;
a?b?c:d:e;
a?b:c?d:e;