SAS Employee

## Trabb Pardo Knuth Algorithm - The more complete 'Hello World'

Trabb Pardo–Knuth algorithm

http://en.wikipedia.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm

```The Trabb Pardo–Knuth algorithm is a program introduced by Donald Knuth and Luis Trabb Pardo to illustrate the evolution of computer programming languages.
In their 1977 work "The Early Development of Programming Languages", Trabb Pardo and Knuth introduced a trivial program which involved arrays, indexing, mathematical functions, subroutines, I/O, conditionals and iteration. They then wrote implementations of the algorithm in several early programming languages to show how such concepts were expressed.
[. . .]
The algorithm reads eleven numbers from an input device, stores them in an array, and then processes them in reverse order, applying a user-defined function to each value and reporting either the value of the function or a message to the effect that the value has exceeded some threshold.
```

```ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
call a function to do an operation
if result overflows
else
print result
```

Below is my version for SAS using a datastep, highlight to see so it doesn't spoil your own working through it:

%let input=5 500 300 14 26 1000 3 4 7 400 24;

data _null_;

length x 4;

array i[11] _temporary_ (&input);

do _n_=hbound(i) to 1 by -1;

if i[_n_] > ((constant('exactint',vlength(x))**(1/3))/5) then do;

put 'Overflow';

end;

else do;

x=5*i[_n_]**3;

put x=;

end;

end;

run;

2 REPLIES 2
Opal | Level 21

## Re: Trabb Pardo Knuth Algorithm - The more complete 'Hello World'

Using SAS language sophisticated :smileygrin: user interaction capabilities to get the numbers :

data new;

array number{11};

do i = 1 to dim(number);

window start

#2  "Number (" i 2.0 protect=yes "):" number{i} attr=underline;

display start;

end;

do i = dim(number) to 1 by -1;

if number{i} > CONSTANT('LOGBIG', 10) then put "Can't represent 10**" number{i};

else do;

bignumber = 10**number{i};

put " 10**" number{i} "=" bignumber;

end;

end;

stop;

run;

PG

PG
Opal | Level 21

## Re: Trabb Pardo Knuth Algorithm - The more complete 'Hello World'

Or, to show SAS's error catching abilities :

data new;

array number{11};

do i = 1 to dim(number);

window start

#2  "Number (" i 2.0 protect=yes "):" number{i} attr=underline;

display start;

end;

do i = dim(number) to 1 by -1;

bignumber = 10**number{i};

if _error_ ne 0 then put "NOTE: Can't represent 10**" number{i};

else put " 10**" number{i} "=" bignumber;

_error_ = 0;

end;

stop;

run;

PG

PG
Discussion stats
• 2 replies
• 686 views
• 0 likes
• 2 in conversation