Pascal vs C, again (was: Pascals Origins)
Eric A. Raymond
ear at duke.UUCP
Mon Jul 21 17:36:43 AEST 1986
In article <3130 at utcsri.UUCP> greg at utcsri.UUCP (Gregory Smith) writes:
>Challenge: given
>
>var x: array [1..1000] of integer;
>
>write a code fragment to find the location of the first 0 in x. The
>condition that no zeroes exist must be distinguished.
>
>Further rules:
> - Standard Jensen & Wirth Pascal ( no break from loop )
> - *** x[i] must not be evaluated for i<1 or i>1000 ***
> - The search loop must be terminated as soon as a zero is found.
> - 'a or b', 'a and b' always evaluate both a and b ( I think
> this is a rule in Jensen & Wirth )
>
>This is the best I can find:
> var i: integer;
> ...
> i :=1 ;
> while i<1000 and x[i] <> 0 do
> i := i+1;
> if x[i] = 0 then writeln('zero at location', i )
> else writeln('not found');
Well assuming that a OR b only evaluates b if a is false, how about:
var i: integer;
i := 0;
repeat
i := i + 1; {or use INC(i) if one exists}
until (i > 1000) OR (x[i] = 0);
if (i > 1000) then
writeln('No zero found')
else
writeln('Zero at location ',i);
Note that this takes an extra loop (1001 .vs. 1000) if there is no zero.
Also, the condition that x[i>1000] not be evaluated is dependent upon
the previous assumption of OR evaluation. Now if you didn't care whether
x[i>1000] was evaluated and if you don't mind x[i] being evaluated twice,
then you could use something like this ...
until (i = 1000) OR (x[i] =0);
if (x[i] = 0) then ... found
else ... not found
Your point (however understated it may be) that C's ability to include
assignment in conditional tests is well taken. An optimizing compiler
should be able to generate code similar to what C allows one to explicitly
encode. (This would not be so if x[i] were some (expensive) function.)
--
Eric A. Raymond UUCP: ...decvax!mcnc!duke!ear
More information about the Comp.lang.c
mailing list