Chapter 8
SCOPE, LIFETIME, AND MORE ON FUNCTIONS
Programming Warm-Up Exercises
1. In this rewrite of the program without globals, the name of the
#include <iostream.h>
void MashGlobals( int&, int&, int );
int main()
{
int a;
int b;
int c;
cin >> a >> b >> c;
MashGlobals(a, b, c);
cout << "a = " << a << ' ' << "b = " << b << ' '
<< "c = " << c << endl;
return 0;
}
void MashGlobals( /* inout */ int& a,
/* inout */ int& b,
/* in */ int c )
{
int temp = a + b;
a = b + c;
b = temp;
}
2.
float Epsilon( /* in */ float high,/* in */ float low )
4. Below are two versions of the function body, the first being more direct.
#include <math.h> // For fabs()
.
.
Boolean NearlyEqual( /* in */ float num1,
/* in */ float num2,
/* in */ float difference )
{
return (fabs(num1 - num2) < difference);
}
or
{
if (fabs(num1 - num2) < difference)
return TRUE;
else
return FALSE;
}
6. For portability, the function below uses the precondition that
float FracPart( /* in */ float x )
// Precondition:
// x >= 0.0
// Postcondition:
// Function value == fractional part of x
{
return x - float(int(x));
}
7.
float Circumf( /* in */ float radius )// Precondition:
// radius is assigned (in principle, radius >= 0.0)
// Postcondition:
// Function value == 2.0 * pi * radius
{
const float PI = 3.14159;
return 2.0 * PI * radius;
}
9. The
float FifthPow( /* in */ float x )
// Precondition:
// x is assigned
// Postcondition:
// Function value == x to the power 5
{
return x * x * x * x * x;
}
10. Below are two versions of the function body.
int Min( /* in */ int int1,
/* in */ int int2,
/* in */ int int3 )
// Precondition:
// int1, int2, and int3 are assigned
// Postcondition:
// Function value == smallest of int1, int2, and int3
{
int smallest = int1;
if (int2 < smallest)
smallest = int2;
if (int3 < smallest)
smallest = int3;
return smallest;
}
or
{
int smallest;
if (int1 < int2)
if (int1 < int3)
smallest = int1;
else
smallest = int3;
else
if (int2 < int3)
smallest = int2;
else
smallest = int3;
return smallest;
}
11.a.
if (isdigit(inChar))DoSomething();
b.
if (isalpha(inChar))DoSomething();
c.
if (isupper(inChar) || isdigit(inChar))DoSomething();
or
if (isalnum(inChar) && !islower(inChar))
DoSomething();
d.
if ( !islower(inChar) )DoSomething();
12.
#include <math.h> // For sqrt()
.
Boolean IsPrime( /* in */ int n )
// Precondition:
// n is assigned
// Postcondition:
// Function value == TRUE, if n is a prime number
// == FALSE, otherwise
{
int trialDivisor; // A trial divisor to test
int limit; // Greatest divisor to test
if (n < 2) // If n < 2, it's not prime
return FALSE;
limit = int(sqrt(float(n))); // Only need to check up to sqrt(n)
trialDivisor = 2;
// Test divisors starting with 2. If we exceed limit, n is prime
while (trialDivisor <= limit && n % trialDivisor != 0)
trialDivisor++;
return (trialDivisor > limit);
}
ANSWERS TO QUESTIONS
True/False
Multiple Choice
Fill-In
44. scope 48. static
45. scope 49. side effect
46. lifetime 50. stub
47. automatic 51. driver