Midterm Review Questions Solutions¶
Write a function called
isPositive(x)
that returnstrue
ifx
is greater than 0, andfalse
ifx
is 0 or less. For example:isPositive(0)
returnsfalse
isPositive(4.0)
returnstrue
isPositive(-5.3)
returnsfalse
Sample solution:
boolean isPositive(float x) { if (x > 0) { return true; } else { return false; } } // or ... boolean isPositive(float x) { return x > 0; }
Write a function called
sign(x)
that returns the sign ofx
, i.e. -1 ofx
is less than 0, 0 ifx
is equal to 0, and 1 ifx
is greater than 0. For example:sign(-4)
returns -1sign(-5.3)
returns -1sign(0)
returns 0sign(4)
returns 1sign(53.2)
returns 1Sample Solution:
int sign(float x) { if (x < 0) { return -1; } else if (x > 0) { return 1; } else { return 0; } }
Write a function called
min(x, y)
that returns the smaller ofx
andy
. For example:min(1, 2)
returns 1min(2, 1)
returns 1min(-85, 2)
returns 2min(3, 3)
returns 3Sample solution:
int min(int x, int y) { if (x < y) { return x; } else { return y; } }
Write a function called
dist(x, y)
that returns the positive difference betweenx
andy
.dist(1, 2)
returns 1dist(2, 1)
returns 1dist(-5, 2)
returns 7dist(3, 3)
returns 0Sample solution:
int dist(int x, int y) { float d = x – y; if (d < 0) { return -d; } else { return d; } } // or ... int dist(int x, int y) { return abs(x - y); }