Skip to content

Instantly share code, notes, and snippets.

@nathanhleung
Last active December 16, 2015 14:19
Show Gist options
  • Save nathanhleung/e7bb2819bfff39c55d0f to your computer and use it in GitHub Desktop.
Save nathanhleung/e7bb2819bfff39c55d0f to your computer and use it in GitHub Desktop.
Returning Values Questions

Returning Values

Questions

  1. What is the value of cubeByVolume(9)?
  2. 729.
  3. What is the value of cubeByVolume(cubeByVolume(2))?
  4. cubeByVolume(8) = 512.
  5. Using the pow() function, write an alternate implementation of the cubeByVolume function.
double cubeByVolume(double sideLength) {
  return pow(sideLength, 3.0);
}
  1. Define a function called squareArea that computes the area of a square of a given sideLength.
double squareArea(double sideLength) {
  return pow(sideLength, 2.0);
}
  1. Consider this function:
int mystery( int x, int y) {
  double result = (x + y ) / ( y - x);
  return result;
}

What is the result of mystery(2,3) and mystery(3,5).

  1. 5 and 4.
  2. Implement a function that returns the minimum of three values.
// Prototype
int findTheSmallest(int, int, int);
// Implementation
int findTheSmallest(int x, int y, int z) {
  if (x < y && x < z) {
    return x;
  } else if (y < x && y < z) {
    return y;
  }
  return z;
}
// Function call
findTheSmallest(1,2,3);
// => 1

Attached Code

#include <iostream>
#include <cmath>

using namespace std;

double steinbergPow( double, double);

int main()
{
	double result1;
	double result2;
	
	result1 = pow( 2.0, 4.0 );
	result2 = steinbergPow( 2.0, 4.0 );
	
	cout << "pow: " << result1 << endl;
	cout << "steinbergPow:  " << result2 << endl;

	cout << endl;
	system("pause");
	return EXIT_SUCCESS;
}

/**
Raises base to the power
@param base is the base
@param power is the exponent
*/
double steinbergPow( double base, double power )
{
	double sum = 1;
	for( int i = 0; i < power ; i++ )
	{
		sum = sum * base;
	}
	return sum;
}

/*
Computes the volume of a cube.
@param sideLength the side length of a cube
@return the volume
*/
double cubeByVolume( double sideLength )
{
	double volume = sideLength * sideLength * sideLength;
	return volume;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment