main() functions. Write the simplest
main() needed to get the job done. The point here
is not to write complete programs, but to exercise your
problem-solving skills. In this context, main() is
merely a tool.
int max(int a[], unsigned int length)
{
// assume the first number is the largest
int largest = a[0];
// compare each number against the current guess
for (unsigned int i = 0; i < length; ++i)
{
// if we found a larger number, update largest
if (a[i] > largest)
{ largest = a[i]; }
}
return largest;
}
float f(float x)
{
return (x / 2.0 + 1.0 / x);
}
c. [3 points] Next, write a small C++ program with
a main function in such a way that it asks the user for a
non-zero starting number x0 and for a maximum number of
iterations, maxIters, then repeatedly applies f()
to the result obtained from the previous application of
f(), printing the result every time, and doing it
maxIters times. In other words, your main function will be
computing and printing x1 = f(x0), x2 = f(x1), x3 = f(x2), etc,
maxIters times.
#include <iostream>
float f(float x)
{
return (x / 2.0 + 1.0 / x);
}
int main()
{
std::cout << "Computing the square root of 2..."
<< std::endl << std::endl;
// the while loop here is used to make sure that the
// user enters valid information, namely, a non-zero x0
float x0 = 0.0;
while (x0 == 0.0)
{
std::cout << "Please enter a non-zero starting number"
<< std::endl;
std::cin >> x0;
}
// the while loop here is used to make sure that the
// user enters valid information, namely, a number of
// iterations that is at least 1
unsigned int max_iters = 0;
while (max_iters < 1)
{
std::cout << "Please enter the number of iterations to perform"
<< std::endl;
std::cin >> max_iters;
}
// let's print 10 digits, shall we?
std::cout.precision(10);
// let's be nice and print the user's initial value
float x = x0;
std::cout << "x0 = " << x0 << std::endl;
// now compute and print each subsequent approximation
for (unsigned int i = 0; i < max_iters; ++i)
{
x = f(x);
std::cout << "x" << (i+1) << " = " << x << std::endl;
}
return 0;
}
Here's a printout of an actual run of this program:
Computing the square root of 2... Please enter a non-zero starting number 15 Please enter the number of iterations to perform 20 x0 = 15 x1 = 7.566666603 x2 = 3.915491819 x3 = 2.21314168 x4 = 1.558417201 x5 = 1.420885324 x6 = 1.414229274 x7 = 1.414213538 x8 = 1.414213538 x9 = 1.414213538 x10 = 1.414213538 x11 = 1.414213538 x12 = 1.414213538 x13 = 1.414213538 x14 = 1.414213538 x15 = 1.414213538 x16 = 1.414213538 x17 = 1.414213538 x18 = 1.414213538 x19 = 1.414213538 x20 = 1.414213538Now, if you observe carefully, you'll notice that the results here do not agree with those we calculated earlier (1.414213538 instead of 1.41421356). How come?
Computing the square root of 2... Please enter a non-zero starting number 15 Please enter the number of iterations to perform 20 x0 = 15 x1 = 7.566666667 x2 = 3.915491924 x3 = 2.213141713 x4 = 1.558417204 x5 = 1.420885296 x6 = 1.414229226 x7 = 1.414213562 x8 = 1.414213562 x9 = 1.414213562 x10 = 1.414213562 x11 = 1.414213562 x12 = 1.414213562 x13 = 1.414213562 x14 = 1.414213562 x15 = 1.414213562 x16 = 1.414213562 x17 = 1.414213562 x18 = 1.414213562 x19 = 1.414213562 x20 = 1.414213562And now we get the expected answer. What happened here is that floats don't have enough precision to hold a result accurate to 10 decimal digits or more. For that, we need doubles.
F(0) = 1 F(1) = 1 F(n) = F(n-1) + F(n-2), for n > 1How many function calls of the form F(something) are made when computing F(5)? How many times are F(1) and F(0) called for? In your solution, show a trace of the execution of this function call. Here's an example of tracing the execution of F(3): (Notice the indentation pattern; it will help you understand what's happening.)
F(3) calls F(2)
F(2) calls F(1)
F(1) returns 1
F(2) calls F(0)
F(0) returns 1
F(2) returns (1+1) = 2
F(3) calls F(1)
F(1) returns 1
F(3) returns (2+1) = 3
So, the call to F(3) generates 1 call to F(2), 2 calls to
F(1), and 1 call to F(0), for a total of 4 additional F calls
(besides the call to F(3) that originated the rest).
#F(n) = 2 + #F(n-1) + #F(n-2), n > 1which is another recursive relation. The base cases are:
#F(0) = 0 #F(1) = 0since F(0) and F(1) do not generate F-calls at all (they're the base cases of the Fibonacci sequence). You can try it yourself and you'll find out, from the recursion above, that #F(5) = 14, as the trace below demonstrates.
F(5) calls F(4)
F(4) calls F(3)
F(3) calls F(2)
F(2) calls F(1)
F(1) returns 1
F(2) calls F(0)
F(0) returns 1
F(2) returns (1+1) = 2
F(3) calls F(1)
F(1) returns 1
F(3) returns (2+1) = 3
F(4) calls F(2)
F(2) calls F(1)
F(1) returns 1
F(2) calls F(0)
F(0) returns 1
F(2) returns (1+1) = 2
F(4) returns (3+2) = 5
F(5) calls F(3)
F(3) calls F(2)
F(2) calls F(1)
F(1) returns 1
F(2) calls F(0)
F(0) returns 1
F(2) returns (1+1) = 2
F(3) calls F(1)
F(1) returns 1
F(3) returns (2+1) = 3
F(5) returns (5+3) = 8
int pow(int x, int n)
{
return x * pow(x, n-1);
}
Solution: The reasons are: (1) there is no base case, meaning that this function would try to recurse infinitely many times (of course, a stack overflow would prevent an actual infinite number of recursive calls, though your program would crash), (2) you won't be able to get results bigger than 2 to the 31st power, since that's the largest integer you can have. To get larger results, you need to use double instead of int for the result. Here's the correct implementation:
double pow(double x, int n)
{
if (n == 0) // base case
return 1.0;
else
return x * pow(x, n-1);
}
recMin on (73, -21, -22, 48, 0, 724, 214, -93, 1721, 4)
calls recMin on (73, -21, -22, 48, 0)
calls recMin on (73, -21, -22)
calls recMin on (73)
returns 73
calls recMin on (-21, -22)
calls recMin on (-21)
returns -21
calls recMin on (-22)
returns -22
returns min(-21, -22) = -22
returns min(73, -22) = -22
calls recMin on (48, 0)
calls recMin on (48)
returns 48
calls recMin on (0)
returns 0
returns min(48, 0) = 0
returns min(-22, 0) = -22
calls recMin on (724, 214, -93, 1721, 4)
calls recMin on (724, 214, -93)
calls recMin on (724)
returns 724
calls recMin on (214, -93)
calls recMin on (214)
returns 214
calls recMin on (-93)
returns -93
returns min(214, -93) = -93
returns min(724, -93) = -93
calls recMin on (1721, 4)
calls recMin on (1721)
returns 1721
calls recMin on (4)
returns 4
returns min(1721, 4) = 4
returns min(-93, 4) = -93
returns min(-22, -93) = -93
Write a recursive function int recMin(int a[],
unsigned int begin, unsigned int end) which returns the
smallest element of the integer array a using the idea
described above. Also write a main function to test your
recursive function.
#include <iostream>
int recMin(int a[], unsigned int begin, unsigned int end)
{
// base case: sub-array of size 1
if (begin == end)
return a[begin];
// notice that this is integer division
int middle = (begin + end) / 2;
// get the minimum value in each sub-array
int left_min = recMin(a, begin, middle);
int right_min = recMin(a, middle + 1, end);
// return the min of each sub-array's min
if (left_min < right_min)
return left_min;
else
return right_min;
}
int main()
{
std::cout << "Testing recMin()..."
<< std::endl << std::endl;
// the while loop here is used to make sure that the
// user enters valid information, namely, a positive
// number for the size of the array
unsigned int length = 0;
while (length == 0)
{
std::cout << "Please enter the size of the array"
<< std::endl;
std::cin >> length;
}
std::cout << std::endl;
// gather array elements from the user
int * a = new int[length];
for (unsigned int i = 0; i < length; ++i)
{
std::cout << "Please enter the value for element"
<< " a[" << i << "]" << std::endl;
std::cin >> a[i];
}
std::cout << std::endl;
// let's print the array back to the user
// so he can see what he entered
std::cout << "You entered the following array:"
<< std::endl;
std::cout << "[" << a[0];
for (unsigned int i = 1; i < length; ++i)
{
std::cout << ", " << a[i];
}
std::cout << "]" << std::endl << std::endl;
// now find and print the minimum array element
std::cout << "The minimum element is:" << std::endl;
std::cout << recMin(a, 0, length-1) << std::endl;
return 0;
}
Here's the output of an actual run:
Testing recMin()...
Please enter the size of the array
8
Please enter the value for element a[0]
5001
Please enter the value for element a[1]
33
Please enter the value for element a[2]
-1023
Please enter the value for element a[3]
59
Please enter the value for element a[4]
121
Please enter the value for element a[5]
-199
Please enter the value for element a[6]
1
Please enter the value for element a[7]
13
You entered the following array:
[5001, 33, -1023, 59, 121, -199, 1, 13]
The minimum element is:
-1023
// having the int's be unsigned guarantees that
// they are not negative integers
void setDate(unsigned int d, unsigned int m)
{
if (m == 0 || m > 12)
{
// throw an error: m must be in the range [1, 12]
}
if (d == 0)
{
// throw an error: d must not be zero
}
switch (m)
{
case 2: // February
if (d > 29)
{
// throw an error: February may have
// only up to 29 days
// if we also had a member variable
// to store the year, we'd then also
// test for leap years
}
break;
case 1: // January
case 3: // March
case 5: // May
case 7: // July
case 8: // August
case 10: // October
case 12: // December
if (d > 31)
{
// throw an error: these months may have
// only up to 31 days
}
break;
default: // all other months
if (d > 30)
{
// throw an error: these months may have
// only up to 30 days
}
break;
}
// now we know that d and m are valid day and
// month values so all that's left is to set our
// private member variables accordingly
day = d;
month = m;
}
============================================================
Book
============================================================
- string title
- string ISBN // not an int b/c ISBN numbers may have an X
- string author_list[]
- string publisher
- int num_of_pages
- float price
============================================================
+ Book() // constructor... needs some parameters!
+ string getTitle() const
+ string getISBN() const
+ string getAuthor(unsigned int index) const
+ string * getAuthorArray() const
+ string getPublisher() const
+ int getNumberOfPages() const
+ float getPrice() const
+ void setPrice(float cost)
============================================================
The press() function should flip the button's
on/off state, then print the button's label and whether the
button is now on or off. Answer the following questions:
isOn ?
#include <iostream>
#include <string>
using namespace std;
class ToggleButton
{
private:
string label;
bool isOn;
public:
ToggleButton(string lbl, bool on);
ToggleButton(string lbl);
string getLabel() const;
void press();
};
// this is the general constructor
ToggleButton::ToggleButton(string lbl, bool on)
{
label = lbl;
isOn = on;
}
// this constructor creates a ToggleButton that
// starts in the OFF position
ToggleButton::ToggleButton(string lbl)
{
label = lbl;
isOn = false;
}
string ToggleButton::getLabel() const
{
return label;
}
void ToggleButton::press()
{
// this is a quick way of inverting the
// value of a boolean variable
isOn = !(isOn);
// here's the long way of doing the same thing:
/*
if (isOn == true)
isOn = false;
else
isOn = true;
*/
cout << "Button '" << label
<< "' is now in the ";
if (isOn)
cout << "ON";
else
cout << "OFF";
cout << " state." << endl;
}
int main ()
{
ToggleButton playBtn = ToggleButton("Play");
playBtn.press();
playBtn.press();
playBtn.press();
return 0;
}
Here's the output:
isOn ?
© 2003 UC Riverside Department of Computer Science & Engineering. All rights reserved.