Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!seismo!brl-adm!caip!topaz!think!mit-eddie!genrad!decvax!mcnc!duke!ear From: ear@duke.UUCP (Eric A. Raymond) Newsgroups: net.lang.c,net.lang.pascal Subject: Re: Pascal vs C, again (was: Pascals Origins) Message-ID: <8069@duke.duke.UUCP> Date: Mon, 21-Jul-86 03:36:43 EDT Article-I.D.: duke.8069 Posted: Mon Jul 21 03:36:43 1986 Date-Received: Tue, 22-Jul-86 01:10:36 EDT References: <2222@brl-smoke.ARPA> <7014@boring.mcvax.UUCP> <3130@utcsri.UUCP> Reply-To: ear@duke.UUCP (Eric A. Raymond) Organization: Duke University, Durham NC Lines: 59 Summary: Naah, NAh, na, naah, naah Xref: mnetor net.lang.c:5388 net.lang.pascal:334 In article <3130@utcsri.UUCP> greg@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