Answers to Selected Exercises - SJSU

嚜燕rogramming Languages - Principles and Practice

2nd Edition

by Kenneth C. Louden

Thomson Brooks/Cole 2002

Answers to Selected Exercises

? Copyright Kenneth C. Louden 2002

Chapter 1

1.2.

(a)

function numdigits(x: integer): integer;

var t,n: integer;

begin

n := 1; t := x;

while t >= 10 do begin

n := n + 1;

t := t div 10;

end;

numdigits := n;

end;

(c)

numdigits x = if x < 10 then 1 else numdigits(x / 10) + 1

(e)

function numdigits(x: Integer) return Integer is

t: Integer := x;

n: Integer := 1;

begin

while t >= 10 loop

n := n + 1;

t := t / 10;

end loop;

return n;

end numdigits;

(g)

class NumDigits

{ public static int numdigits(int x)

{ int t = x, n = 1;

while (t >= 10)

{ n++;

t = t / 10;

}

return n;

}

}

Kenneth C. Louden

Programming Languages 每 Principles and Practice 2nd Ed.

Answers - 2

1.5. (a) The remainder function, which we shall write here as % (some languages use rem or remainder), is

defined by the integer equation a = (a / b) * b + a % b. The modulo function, which we shall

write here as mod (some languages use modulo) is defined by the properties

1. a mod b is an integer between b and 0 not equal to b, and

2. there exists an integer n such that a = n * b + a mod b.

When both a and b are non-negative, it can be shown that a % b = a mod b. But when either (or both) of

a and b are negative these definitions can produce different results. For example, 每10 % 3 = 每1, since 每

10 / 3 = 每3 and 每3 * 3 每 1 = 每10. However, -1 is not between 0 and 3, and indeed 每10 mod 3 = 2,

since 每10 = 每4 * 3 + 2. Some languages (C, Java) have only a remainder operation, some languages

(Pascal, Modula-2) have only a modulo operation, and some languages (Ada, Scheme, Haskell) have both.

(b) Indeed, the above differences can cause the results of the gcd to differ by a sign. For example, the Ada

implementation produces 5 as the gcd of 每15 and 10, while the C implementation produces 每5. For this

reason (and because the sign of the gcd makes little sense), most languages with a built in gcd operation

(like Scheme and Haskell) apply the absolute value to the operands before computing the gcd. Then it

doesn't matter whether remainder or modulo is used.

1.10. Two possible things can happen when overflow occurs: either an interrupt or exception occurs, halting

execution (if not handled), or the value "wraps", usually to a negative number (using two's complement

format), and the factorial function appears to work but produces an erroneous value. The ANSI C Standard

(see Kernighan and Ritchie [1988], p. 200) does not specify any particular behavior on overflow, but in C,

the constant INT_MAX defined in the limits.h standard library header file can be used to perform a

check:

int fact (int n)

{ if (n ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download