100% found this document useful (21 votes)
624 views37 pages

Engineering Problem Solving With C++ 4th Edition Etter Solutions Manual Download

The document describes a textbook on engineering problem solving with C++ and provides sample exam problems testing concepts related to programming with C++. It includes multiple choice, true/false, and programming problems testing concepts like functions, file I/O, and simple simulations.

Uploaded by

John Durant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (21 votes)
624 views37 pages

Engineering Problem Solving With C++ 4th Edition Etter Solutions Manual Download

The document describes a textbook on engineering problem solving with C++ and provides sample exam problems testing concepts related to programming with C++. It includes multiple choice, true/false, and programming problems testing concepts like functions, file I/O, and simple simulations.

Uploaded by

John Durant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Engineering Problem Solving With C++ 4th

Edition by Etter Ingber ISBN 0134444299


9780134444291
Download solution manual at:
https://testbankpack.com/p/solution-manual-for-engineering-
problem-solving-with-c-4th-edition-by-etter-ingber-isbn-
0134444299-9780134444291/

Download full test bank at :


https://testbankpack.com/p/test-bank-for-engineering-problem-
solving-with-c-4th-edition-by-etter-ingber-isbn-0134444299-
9780134444291/

Exam Practice!
True/False Problems
1. T
2. F
3. T
4. T
5. F
6. T
7. T
Multiple Choice Problems
8. (b)
9. (a)
10. (d)
Program Analysis
11. 1
12. 0
13. 0
14. Results using negative integers may not be as expected.
Memory Snapshot Problems
15. v1-> [double x->1 double y->1 double orientation->3.1415]
v2-> [double x->1 double y->1 double orientation->3.1415]
16. v1-> [double x->0.0 double y->0.0 double orientation->0.0]
v2-> [double x->1 double y->1 double orientation->3.1415]
17. v1-> [double x->2.1 double y->3.0 double orientation->1.6]
v2-> [double x->2.1 double y->3.0 double orientation->1.6]
Programming Problems
/*--------------------------------------------------------------------*/
/* Problem chapter6_18 */
/* */
/* This program calls a function that detects and prints the first */

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


/* n prime integers, where n is an integer input to the function. */

#include <iostream>
using namespace std;

void primeGen(int n);

int main()
{
/* Declare and initialize variables. */
int input;

/* Prompt user for number of prime numbers. */


cout << "\nEnter number of primes you would like: ";
cin >> input;

/* Call the function. */


primeGen(input);

return 0;

}
/*--------------------------------------------------------------------*/
/* Function to calculate prime numbers. */
void primeGen(int n){

/* Declare variables. */
int i,j;
bool prime;

/* Print header information. */


cout << "Prime Numbers between 1 and " << n << endl;

for (i=1;i<=n;i++){
prime=true;
for (j=2;j<i;j++){
if (!(i%j)) {
prime=false;
}
}
/* Output number if it is prime. */
if (prime)
cout << i << endl;
}
return;
}
/*--------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/
/* Problem chapter6_19 */
/* */
/* This program calls a function that detects and prints the first */
/* n prime integers, where n is an integer input to the function. */
/* The values are printed to a designated output file. */

#include <iostream>
#include <fstream>

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


#include <string>

using namespace std;

void primeGen(int n, ofstream& file);

int main()
{
/* Declare and initialize variables */
int input;
ofstream outfile;
string filename;

/* Prompt user for number of prime numbers. */


cout << "\nEnter number of primes you would like: ";
cin >> input;

/* Prompt user for the name of the output file. */


cout << "\nEnter output file name: ";
cin >> filename;

outfile.open(filename.c_str());
if (outfile.fail()) {
cerr << "The output file " << filename << " failed to open.\n";
exit(1);
}

/* Call the function. */


primeGen(input, outfile);

outfile.close();

return 0;

}
/*--------------------------------------------------------------------*/
/* Function to calculate prime numbers. */
void primeGen(int n, ofstream& out){

/* Declare variables. */
int i,j;
bool prime;

/* Print header information. */


out << "Prime Numbers between 1 and " << n << endl;

for (i=1;i<=n;i++){
prime=true;
for (j=2;j<i;j++){
if (!(i%j)) {
prime=false;
}
}
/* Output number if it is prime. */
if (prime)
out << i << endl;
}

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


return;
}
/*--------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/
/* Problem chapter6_20 */
/* */
/* This program calls a function that counts the integers in a file */
/* until a non-integer value is found. An error message is printed */
/* if non-integer values are found. */

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int countInts(ifstream& file);

int main()
{
/* Declare and initialize variables */
ifstream infile;
string filename;
int numInts;

/* Prompt user for the name of the input file. */


cout << "\nEnter input file name: ";
cin >> filename;

infile.open(filename.c_str());
if (infile.fail()) {
cerr << "The input file " << filename << " failed to open.\n";
exit(1);
}

/* Call the function. */


numInts = countInts(infile);

/* Print the number of integers. */


cout << numInts << " integers are in the file " << filename << endl;

infile.close();

return 0;

}
/*--------------------------------------------------------------------*/
/* Function to count integers. */
int countInts(ifstream& in){

/* Declare and initialize variables. */


int count(0), num;

in >> num;
while (!in.eof()) {
if (!in) {

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


cerr << "Encountered a non-integer value." << endl;
break;
} else {
count++;
}
in >> num;
}

return count;
}
/*--------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/
/* Problem chapter6_21 */
/* */
/* This program calls a function that prints the values of the state */
/* flags of a file stream, which is passed to the function as an */
/* argument. */

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void printFlags(ifstream& file);

int main()
{
/* Declare and initialize variables */
ifstream infile;
string filename;

/* Prompt user for the name of the input file. */


cout << "\nEnter input file name: ";
cin >> filename;

infile.open(filename.c_str());
if (infile.fail()) {
cerr << "The input file " << filename << " failed to open.\n";
exit(1);
}

/* Call the function. */


printFlags(infile);

infile.close();

return 0;

}
/*--------------------------------------------------------------------*/
/* Function to count integers. */
void printFlags(ifstream& in){

cout << "Badbit: " << in.bad() << endl;

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


cout << "Failbit: " << in.fail() << endl;

cout << "Eofbit: " << in.eof() << endl;

cout << "Goodbit: " << in.good() << endl;

return;
}
/*--------------------------------------------------------------------*/
Simple Simulations
/*--------------------------------------------------------------------*/
/* Problem chapter6_22 */
/* */
/* This program simulates tossing a "fair" coin. */
/* The user enters the number of tosses. */

#include <iostream>
#include <cstdlib>

using namespace std;

int rand_int(int a, int b);

const int HEADS = 1;


const int TAILS = 0;

int main()
{
/* Declare and initialize variables */
/* and declare function prototypes. */
int tosses=0, heads=0, required=0;

/* Prompt user for number of tosses. */


cout << "\n\nEnter number of fair coin tosses: ";
cin >> required;
while (required <= 0)
{
cout << "Tosses must be an integer number, greater than zero.\n\n";
cout << "Enter number of fair coin tosses: ";
cin >> required;
}

/* Toss coin the required number of times, and keep track of */


/* the number of heads. Use rand_int for the "toss" and */
/* and consider a positive number to be "heads." */
while (tosses < required)
{
tosses++;
if (rand_int(TAILS,HEADS) == HEADS)
heads++;
}

/* Print results. */
cout << "\n\nNumber of tosses: " << tosses << endl;
cout << "Number of heads: "<< heads << endl;
cout << "Number of tails: " << tosses-heads << endl;
cout << "Percentage of heads: " << 100.0 * heads/tosses << endl;

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


cout << "Percentage of tails: " << 100.0 * (tosses-heads)/tosses << endl;

/* Exit program. */
return 0;
}
/*--------------------------------------------------------------------*/
/* (rand_int function from page 257) */
/*--------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/
/* Problem chapter6_23 */
/* */
/* This program simulates tossing an "unfair" coin. */
/* The user enters the number of tosses. */

#include <iostream>
#include <cstdlib>

using namespace std;

const int HEADS = 10;


const int TAILS = 1;
const int WEIGHT = 6;

int main()
{
/* Declare variables and function prototypes. */
int tosses=0, heads=0, required=0;
int rand_int(int a, int b);

/* Prompt user for number of tosses. */


cout << "\n\nEnter number of unfair coin tosses: ";
cin >> required;

/* Toss coin the required number of times, and */


/* keep track of the number of heads. */
while (tosses < required)
{
tosses++;
if (rand_int(TAILS,HEADS) <= WEIGHT)
heads++;
}

/* Print results. */
cout << "\n\nNumber of tosses: " << tosses << endl;
cout << "Number of heads: " << heads << endl;
cout << "Number of tails: " << tosses-heads << endl;
cout << "Percentage of heads: " << 100.0 * heads/tosses << endl;
cout << "Percentage of tails: " << 100.0 * (tosses-heads)/tosses <<
endl;

/* Exit program. */
return 0;
}
/*------------------------------------------------------------------*/
/* (rand_int function from page 257) */
/*------------------------------------------------------------------*/

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


/*--------------------------------------------------------------------*/
/* Problem chapter6_24 */
/* */
/* This program simulates tossing a "fair" coin using Coin class. */
/* The user enters the number of tosses. */

#include <iostream>
#include <cstdlib>
#include "Coin.h"
using namespace std;

int main()
{
/* Declare and initialize variables */
/* and declare function prototypes. */
int tosses=0, heads=0, required=0;
int seed;
/* Prompt user for number of tosses. */
cout << "\n\nEnter number of fair coin tosses: ";
cin >> required;
while (required <= 0)
{
cout << "Tosses must be an integer number, greater than zero.\n\n";
cout << "Enter number of fair coin tosses: ";
cin >> required;
}

/* Toss coin the required number of times, and keep track of */


/* the number of heads. Use rand_int for the "toss" and */
/* and consider a positive number to be "heads." */
cout << "enter a seed..";
cin >> seed;
srand(seed);
while (tosses < required)
{
tosses++;
Coin c1;
if (c1.getFaceValue() == Coin::HEADS)
heads++;
}

/* Print results. */
cout << "\n\nNumber of tosses: " << tosses << endl;
cout << "Number of heads: "<< heads << endl;
cout << "Number of tails: " << tosses-heads << endl;
cout << "Percentage of heads: " << 100.0 * heads/tosses << endl;
cout << "Percentage of tails: " << 100.0 * (tosses-heads)/tosses << endl;

/* Exit program. */
return 0;
}
/*--------------------------------------------------------------------*/

/*---------------------------------------------------*
/* Definition of a Coin class */
/* Coin.h
#include <iostream>

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


#include <cstdlib> //required for rand()
using namespace std;
int rand_int(int a, int b);
class Coin
{
private:
char faceValue;
public:
static const int HEADS = 'H';
static const int TAILS = 'T';

//Constructors
Coin() {int randomInt = rand_int(0,1);
if(randomInt == 1)
faceValue = HEADS;
else
faceValue = TAILS;}

//Accessors
char getFaceValue() const {return faceValue;}
//Mutators
//Coins are not mutable
};
/*----------------------------------------------------*/
/* This function generates a random integer */
/* between specified limits a and b (a<b). */
int rand_int(int a, int b)
{
return rand()%(b-a+1) + a;
}
/*----------------------------------------------------*/

/*------------------------------------------------------------------*/
/* Problem chapter6_25 */
/* */
/* This program simulates rolling a six-sided "fair" die. */
/* The user enter the number of rolls. */

#include <iostream>
#include <cstdlib>

using namespace std;

int rand_int(int a, int b);


const int MIN = 1;
const int MAX = 6;

int main()
{
/* Declare variables and function prototypes. */
int onedot=0, twodots=0, threedots=0, fourdots=0, fivedots=0,
sixdots=0, rolls=0, required=0;

/* Prompt user for number of rolls. */


cout << "\n\nEnter number of fair die rolls: ";
cin >> required;

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


/* Roll the die as many times as required */
while (rolls < required)
{
rolls++;
switch(rand_int(MIN,MAX))
{
case 1: onedot++;
break;
case 2: twodots++;
break;
case 3: threedots++;
break;
case 4: fourdots++;
break;
case 5: fivedots++;
break;
case 6: sixdots++;
break;
default:
cout << "\nDie roll result out of range!\n";
exit(1);
break;
}
}

/* Print the results. */


cout << "\nNumber of rolls: " << rolls << endl;
cout << "Number of ones: " << onedot << " percentage: "
<< 100.0*onedot/rolls << endl;
cout << "Number of twos: " << twodots << " percentage: "
<< 100.0*twodots/rolls << endl;
cout << "Number of threes: " << threedots << " percentage: "
<< 100.0*threedots/rolls << endl;
cout << "Number of fours: " << fourdots << " percentage: "
<< 100.0*fourdots/rolls << endl;
cout << "Number of fives: " << fivedots << " percentage: "
<< 100.0*fivedots/rolls << endl;
cout << "Number of sixes: " << sixdots << " percentage: "
<< 100.0*sixdots/rolls << endl;
/* Exit program. */
return 0;
}
/*------------------------------------------------------------------*/
/* (rand_int function from page 257) */
/*------------------------------------------------------------------*/

/*------------------------------------------------------------------*/
/* Problem chapter6_26 */
/* */
/* This program simulates an experiment rolling two six-sided */
/* "fair" dice. The user enters the number of rolls. */

#include <iostream>
#include <cstdlib>

using namespace std;

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


const int MAX = 6;
const int MIN = 1;
const int TOTAL = 8;

int rand_int(int a, int b);

int main()
{
/* Declare variables. */
int rolls=0, die1, die2, required=0, sum=0;

/* Prompt user for number of rolls. */


cout << "\n\nEnter number of fair dice rolls: ";
cin >> required;

/* Roll the die as many times as required. */


while (rolls < required)
{
rolls++;
die1=rand_int(MIN,MAX);
die2=rand_int(MIN,MAX);
if (die1+die2 == TOTAL)
sum++;
cout << "Results: " << die1 << " " << die2 << endl;
}

/* Print the results. */


cout << "\nNumber of rolls: " << rolls << endl;
cout << "Number of " << TOTAL << "s: " << sum << endl;
cout << "Percentage of " << TOTAL << "s: " << 100.0*sum/rolls << endl;

/* Exit program. */
return 0;
}
/*------------------------------------------------------------------*/
/* (rand_int function from text) */
/*------------------------------------------------------------------*/

/*------------------------------------------------------------------*/
/* Problem chapter6_27 */
/* */
/* This program simulates a lottery drawing that uses balls */
/* numbered from 1 to 10. */

#include <iostream>
#include <cstdlib>

using namespace std;

const int MIN = 1;


const int MAX = 10;
const int NUMBER = 7;
const int NUM_BALLS = 3;

int rand_int(int a, int b);


int main()
{

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


/* Define variables. */
unsigned int alleven = 0, num_in_sim = 0, onetwothree = 0, first,
second, third;
int lotteries = 0, required = 0;

/* Prompt user for the number of lotteries. */


cout << "\n\nEnter number of lotteries: ";
cin >> required;
while (required <= 0)
{
cout << "The number of lotteries must be an integer number, "
<< "greater than zero.\n\n";
cout << "Enter number of lotteries: ";
cin >> required;
}

/* Get three lottery balls, check for even or odd, and NUMBER. */
/* Also check for the 1-2-3 sequence and its permutations. */
while (lotteries < required)
{
lotteries++;

/* Draw three unique balls. */


first = rand_int(MIN,MAX);
do
second = rand_int(MIN,MAX);
while (second == first);
do
third = rand_int(MIN,MAX);
while ((second==third) || (first==third));

cout << "Lottery number is: " << first << "-" << second
<< "-" << third << endl;

/* Are they all even? */


if ((first % 2 == 0) && (second % 2 == 0) && (third %2 == 0))
alleven++;

/* Are any of them equal to NUMBER? */


if ((first == NUMBER) || (second==NUMBER) || (third == NUMBER))
num_in_sim++;

/* Are they 1-2-3 in any order? */


if ((first <= 3) && (second <= 3) && (third <= 3))
if ((first != second) && (first != third) && (second != third))
onetwothree++;
}

/* Print results. */
cout << "\nPercentage of time the result contains three even numbers:"
<< 100.0*alleven/lotteries << endl;
cout << "Percentage of time the number " << NUMBER << " occurs in the"
" three numbers: " << 100.0*num_in_sim/lotteries << endl;
cout << "Percentage of time the numbers 1,2,3 occur (not necessarily"
" in order): " << 100.0*onetwothree/lotteries << endl;

/* Exit program. */

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


return 0;

}
/*--------------------------------------------------------------------*/
/* (rand_int function from page 257) */
/*--------------------------------------------------------------------*/
Component Reliability
/*--------------------------------------------------------------------*/
/* Problem chapter6_28 */
/* */
/* This program simulates the design in Figure 6-17 using a */
/* component reliability of 0.8 for component 1, 0.85 for */
/* component 2 and 0.95 for component 3. The estimate of the */
/* reliability is computed using 5000 simulations. */
/* (The analytical reliability of this system is 0.794.) */

#include <iostream>
#include <cstdlib>

using namespace std;

const int SIMULATIONS = 5000;


const double REL1 = 0.8;
const double REL2 = 0.85;
const double REL3 = 0.95;
const int MIN_REL = 0;
const int MAX_REL = 1;

double rand_float(double a, double b);


int main()
{
/* Define variables. */
int num_sim=0, success=0;
double est1, est2, est3;

/* Run simulations. */
for (num_sim=0; num_sim<SIMULATIONS; num_sim++)
{
/* Get the random numbers */
est1 = rand_float(MIN_REL,MAX_REL);
est2 = rand_float(MIN_REL,MAX_REL);
est3 = rand_float(MIN_REL,MAX_REL);

/* Now test the configuration */


if ((est1<=REL1) && ((est2<=REL2) || (est3<=REL3)))
success++;
}

/* Print results. */
cout << "Simulation Reliability for " << num_sim << " trials: "
<< (double)success/num_sim << endl;

/* Exit program. */
return 0;
}
/*-------------------------------------------------------------------*/
/* (rand_float function from page 257) */

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


/*-------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/
/* Problem chapter6_29 */
/* */
/* This program simulates the design in Figure 6.18 using a */
/* component reliability of 0.8 for components 1 and 2, */
/* and 0.95 for components 3 and 4. Print the estimate of the */
/* reliability using 5000 simulations. */
/* (The analytical reliability of this system is 0.9649.) */

#include <iostream>
#include <cstdlib>
using namespace std;

const int SIMULATIONS = 5000;


const double REL12 = 0.8;
const double REL34 = 0.95;
const int MIN_REL = 0;
const int MAX_REL = 1;

double rand_float(double a, double b);

int main()
{
/* Define variables. */
int num_sim=0, success=0;
double est1, est2, est3, est4;

/* Run simulations. */
for (num_sim=0; num_sim<SIMULATIONS; num_sim++)
{
/* Get the random numbers. */
est1 = rand_float(MIN_REL,MAX_REL);
est2 = rand_float(MIN_REL,MAX_REL);
est3 = rand_float(MIN_REL,MAX_REL);
est4 = rand_float(MIN_REL,MAX_REL);

/* Now test the configuration. */


if (((est1<=REL12) && (est2<=REL12)) ||
((est3<=REL34) && (est4<=REL34)))
success++;
}

/* Print results. */
cout << "Simulation Reliability for " << num_sim << " trials: "
<< (double)success/num_sim << endl;

/* Exit program. */
return 0;
}
/*--------------------------------------------------------------------*/
/* (rand_float function from page 257) */
/*--------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


/* Problem chapter6_30 */
/* */
/* This program simulates the design in Figure 6.19 using a */
/* component reliability of 0.95 for all components. Print the */
/* estimate of the reliability using 5000 simulations. */
/* (The analytical reliability of this system is 0.99976.) */

#include <iostream>
#include <cstdlib>

using namespace std;

const int SIMULATIONS = 5000;


const double REL = 0.95;
const int MIN_REL = 0;
const int MAX_REL = 1;

double rand_float(double a, double b);

int main()
{
/* Define variables. */
int num_sim=0, success=0;
double est1, est2, est3, est4;

/* Run simulations. */
for (num_sim=0; num_sim<SIMULATIONS; num_sim++)
{
/* Get the random numbers. */
est1 = rand_float(MIN_REL,MAX_REL);
est2 = rand_float(MIN_REL,MAX_REL);
est3 = rand_float(MIN_REL,MAX_REL);
est4 = rand_float(MIN_REL,MAX_REL);

/* Now test the configuration. */


if (((est1<=REL) || (est2<=REL)) || ((est3<=REL) && (est4<=REL)))
success++;
}

/* Print results. */
cout << "Simulation Reliability for " << num_sim << " trials: "
<< (double)success/num_sim << endl;

/* Exit program. */
return 0;
}
/*--------------------------------------------------------------------*/
/* (rand_float function from page 257) */
/*--------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/
/* Problem chapter6_31 */
/* */
/* This program generates a data file named wind.dat that */
/* contains one hour of simulated wind speeds. */

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

using namespace std;

const int DELTA_TIME = 10;


const int START_TIME = 0;
const int STOP_TIME = 3600;
const string FILENAME = "wind.dat";

double rand_float(double a, double b);

int main()
{
/* Define variables. */
int timer=START_TIME;
double ave_wind=0.0, gust_min=0.0, gust_max=0.0, windspeed=0.0;
ofstream wind_data;

/* Open output file. */


wind_data.open(FILENAME.c_str());

/* Prompt user for input and verify. */


cout << "Enter average wind speed: ";
cin >> ave_wind;
cout << "Enter minimum gust: ";
cin >> gust_min;
cout << "Enter maximum gust (> minimum gust): ";
cin >> gust_max;

for (timer=START_TIME; timer<=STOP_TIME; timer+=DELTA_TIME)


{
windspeed = rand_float(ave_wind+gust_min,ave_wind+gust_max);
wind_data << timer << ' ' << windspeed << endl;
}

/* Close file and exit program. */


wind_data.close();
return 0;
}
/*--------------------------------------------------------------------*/
/* (rand_float function from page 257) */
/*--------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/
/* Problem chapter6_32 */
/* */
/* This program generates flight simulator wind data with a */
/* 0.5% possiblity of encountering a small storm at each time step. */
/* The average wind speed is increased by 10 mph for 5 minutes when */
/* a storm is encountered. */

#include <iostream>
#include <fstream>
#include <cstdlib>

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


#include <string>

using namespace std;

const int DELTA_TIME = 10;


const int START_TIME = 0;
const int STOP_TIME = 3600;
const string FILENAME = "wind.dat";
const int STORM_WIND = 10;
const int MIN_PROB = 0;
const int MAX_PROB = 1;
const double STORM_PROB = 0.005;
const int STORM = 1;
const int NO_STORM = 0;
const int MAX_DURATION = 300;

double rand_float(double a, double b);

int main()
{
/* Define variables. */
double ave_wind=0.0, gust_min=0.0, gust_max=0.0, windspeed = 0.0;
int timer=START_TIME, storm_duration=0, storm_flag=NO_STORM;
ofstream wind_data;

/* Open file for writing */


wind_data.open(FILENAME.c_str());

/* Prompt user for input and verify */


cout << "Enter average wind speed: ";
cin >> ave_wind;
cout << "Enter minimum gust: ";
cin >> gust_min;
cout << "Enter maximum gust (>minimum): ";
cin >> gust_max;

/* Compute wind speeds. */


for (timer=START_TIME; timer<=STOP_TIME; timer+=DELTA_TIME)
{
if (storm_flag == STORM)
/* There is a storm, is it time to stop? */
if (storm_duration < MAX_DURATION)
storm_duration += DELTA_TIME;
else
storm_flag = NO_STORM;
else
/* No storm raging, is it time for another? */
if (rand_float(MIN_PROB,MAX_PROB) <= STORM_PROB)
{
storm_flag = STORM;
storm_duration = 0;
}

windspeed = rand_float(ave_wind+gust_min,ave_wind+gust_max);

if (storm_flag == STORM)
windspeed += STORM_WIND;

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


wind_data << timer << ' ' << windspeed << endl;
}

/* Close file and exit program. */


wind_data.close();
return 0;
}
/*--------------------------------------------------------------------*/
/* (rand_float function from page 257) */
/*--------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/
/* Problem chapter6_33 */
/* */
/* This program generates flight simulator wind data with a */
/* 0.5% possiblity of encountering a small storm at each time step. */
/* The average wind speed is increased by 10 mph for 5 minutes when */
/* a storm is encountered. During a small storm, there is a 1% */
/* chance of encountering a microbust at each time step. The wind */
/* is increased by 50mph for 1 minute when a microburst occurs. */

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

using namespace std;

const int DELTA_TIME = 10;


const int START_TIME = 0;
const int STOP_TIME = 3600;
const string FILENAME = "wind.dat";
const int STORM_WIND = 10;
const int BURST_WIND = 50;
const int MIN_PROB = 0;
const int MAX_PROB = 1;
const double STORM_PROB = 0.005;
const int STORM_TIME = 300;
const double BURST_PROB = 0.01;
const int BURST_TIME = 60;

double rand_float(double a, double b);

int main()
{
/* Define variables. */
double ave_wind=0.0, gust_min=0.0, gust_max=0.0, windspeed = 0.0;
int timer=START_TIME, storm_duration=0, burst_duration=0;
bool storm=false, burst=false;
ofstream wind_data;

/* Open file for writing */


wind_data.open(FILENAME.c_str());

/* Prompt user for input and verify */


cout << "Enter average wind speed: ";

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


cin >> ave_wind;
cout << "Enter minimum gust: ";
cin >> gust_min;
cout << "Enter maximum gust (>minimum): ";
cin >> gust_max;

/* Compute wind speeds. */


for (timer=START_TIME; timer<=STOP_TIME; timer+=DELTA_TIME)
{
if (storm)
/* There is a storm, is it time to stop? */
if (storm_duration < STORM_TIME) {
storm_duration += DELTA_TIME;
/* Is there a burst? */
if (burst)
/* burst in progress */
if (burst_duration < BURST_TIME)
burst_duration +=DELTA_TIME;
else
burst=false;
else
/* no burst, but is it time for one? */
if (rand_float(MIN_PROB,MAX_PROB) <= BURST_PROB) {
/* Time for a burst! */
burst=true;
burst_duration=0;
}
} else {
storm=false;
burst=false;
}
else
/* No storm raging, is it time for another? */
if (rand_float(MIN_PROB,MAX_PROB) <= STORM_PROB)
{
storm = true;
storm_duration = 0;
if (rand_float(MIN_PROB,MAX_PROB) <= BURST_PROB) {
/* Time for a burst! */
burst=true;
burst_duration=0;
}

windspeed = rand_float(ave_wind+gust_min,ave_wind+gust_max);

if (storm){
windspeed += STORM_WIND;
if (burst)
windspeed += BURST_WIND;
}

wind_data << timer << ' ' << windspeed << endl;
}

/* Close file and exit program. */

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


wind_data.close();
return 0;
}
/*--------------------------------------------------------------------*/
/* (rand_float function from page 257) */
/*--------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/
/* Problem chapter6_34 */
/* */
/* This program generates flight simulator wind data with a */
/* user-entered possiblity of encountering a small storm at each */
/* time step. The average wind speed is increased by 10 mph for 5 */
/* minutes when a storm is encountered. */

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

using namespace std;

const int DELTA_TIME = 10;


const int START_TIME = 0;
const int STOP_TIME = 3600;
const string FILENAME = "wind.dat";
const int STORM_WIND = 10;
const int MIN_PROB = 0;
const int MAX_PROB = 1;
const int STORM = 1;
const int NO_STORM = 0;
const int MAX_DURATION = 300;

double rand_float(double a, double b);

int main()
{
/* Define variables. */
double ave_wind=0.0, gust_min=0.0, gust_max=0.0, windspeed = 0.0;
double storm_prob;
int timer=START_TIME, storm_duration=0, storm_flag=NO_STORM;
ofstream wind_data;

/* Open file for writing */


wind_data.open(FILENAME.c_str());

/* Prompt user for input and verify */


cout << "Enter average wind speed: ";
cin >> ave_wind;
cout << "Enter minimum gust: ";
cin >> gust_min;
cout << "Enter maximum gust (>minimum): ";
cin >> gust_max;
cout << "Enter the probability of a storm: ";
cin >> storm_prob;

/* Compute wind speeds. */

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


for (timer=START_TIME; timer<=STOP_TIME; timer+=DELTA_TIME)
{
if (storm_flag == STORM)
/* There is a storm, is it time to stop? */
if (storm_duration < MAX_DURATION)
storm_duration += DELTA_TIME;
else
storm_flag = NO_STORM;
else
/* No storm raging, is it time for another? */
if (rand_float(MIN_PROB,MAX_PROB) <= storm_prob)
{
storm_flag = STORM;
storm_duration = 0;
}

windspeed = rand_float(ave_wind+gust_min,ave_wind+gust_max);

if (storm_flag == STORM)
windspeed += STORM_WIND;

wind_data << timer << ' ' << windspeed << endl;
}

/* Close file and exit program. */


wind_data.close();
return 0;
}
/*--------------------------------------------------------------------*/
/* (rand_float function from page 257) */
/*--------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/
/* Problem chapter6_35 */
/* */
/* This program generates flight simulator wind data with a */
/* 0.5% possiblity of encountering a small storm at each time step. */
/* The average wind speed is increased by 10 mph for a user-entered */
/* duration when a storm is encountered. */

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

using namespace std;

const int DELTA_TIME = 10;


const int START_TIME = 0;
const int STOP_TIME = 3600;
const string FILENAME = "wind.dat";
const int STORM_WIND = 10;
const int MIN_PROB = 0;
const int MAX_PROB = 1;
const double STORM_PROB = 0.005;
const int STORM = 1;
const int NO_STORM = 0;

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


double rand_float(double a, double b);

int main()
{
/* Define variables. */
double ave_wind=0.0, gust_min=0.0, gust_max=0.0, windspeed = 0.0;
int max_storm_length = 300;
int timer=START_TIME, storm_duration=0, storm_flag=NO_STORM;
ofstream wind_data;

/* Open file for writing */


wind_data.open(FILENAME.c_str());

/* Prompt user for input and verify */


cout << "Enter average wind speed: ";
cin >> ave_wind;
cout << "Enter minimum gust: ";
cin >> gust_min;
cout << "Enter maximum gust (>minimum): ";
cin >> gust_max;
cout << "Enter the length of a storm: ";
cin >> max_storm_length;

/* Compute wind speeds. */


for (timer=START_TIME; timer<=STOP_TIME; timer+=DELTA_TIME)
{
if (storm_flag == STORM)
/* There is a storm, is it time to stop? */
if (storm_duration < max_storm_length)
storm_duration += DELTA_TIME;
else
storm_flag = NO_STORM;
else
/* No storm raging, is it time for another? */
if (rand_float(MIN_PROB,MAX_PROB) <= STORM_PROB)
{
storm_flag = STORM;
storm_duration = 0;
}

windspeed = rand_float(ave_wind+gust_min,ave_wind+gust_max);

if (storm_flag == STORM)
windspeed += STORM_WIND;

wind_data << timer << ' ' << windspeed << endl;
}

/* Close file and exit program. */


wind_data.close();
return 0;
}
/*--------------------------------------------------------------------*/
/* (rand_float function from page 257) */
/*--------------------------------------------------------------------*/

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


/*--------------------------------------------------------------------*/
/* Problem chapter6_36 */
/* */
/* This program generates flight simulator wind data with a */
/* 0.5% possiblity of encountering a small storm at each time step. */
/* The average wind speed is increased by 10 mph for a random */
/* duration between 3 and 5 minutes when a storm is encountered. */

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

using namespace std;

const int DELTA_TIME = 10;


const int START_TIME = 0;
const int STOP_TIME = 3600;
const string FILENAME = "wind.dat";
const int STORM_WIND = 10;
const int MIN_PROB = 0;
const int MAX_PROB = 1;
const double STORM_PROB = 0.005;
const int STORM = 1;
const int NO_STORM = 0;

double rand_float(double a, double b);


int rand_int(int a, int b);

int main()
{
/* Define variables. */
double ave_wind=0.0, gust_min=0.0, gust_max=0.0, windspeed = 0.0;
int max_storm_length;
int timer=START_TIME, storm_duration=0, storm_flag=NO_STORM;
ofstream wind_data;

/* Open file for writing */


wind_data.open(FILENAME.c_str());

/* Prompt user for input and verify */


cout << "Enter average wind speed: ";
cin >> ave_wind;
cout << "Enter minimum gust: ";
cin >> gust_min;
cout << "Enter maximum gust (>minimum): ";
cin >> gust_max;

/* Generate the length of the storm */


max_storm_length = rand_int(180,300);

/* Compute wind speeds. */


for (timer=START_TIME; timer<=STOP_TIME; timer+=DELTA_TIME)
{
if (storm_flag == STORM)
/* There is a storm, is it time to stop? */
if (storm_duration < max_storm_length)

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


storm_duration += DELTA_TIME;
else
storm_flag = NO_STORM;
else
/* No storm raging, is it time for another? */
if (rand_float(MIN_PROB,MAX_PROB) <= STORM_PROB)
{
storm_flag = STORM;
storm_duration = 0;
}

windspeed = rand_float(ave_wind+gust_min,ave_wind+gust_max);

if (storm_flag == STORM)
windspeed += STORM_WIND;

wind_data << timer << ' ' << windspeed << endl;
}

/* Close file and exit program. */


wind_data.close();
return 0;
}
/*--------------------------------------------------------------------*/
/* (rand_float function from page 259) */
/* (rand_int function from page 257) */
/*--------------------------------------------------------------------*/
Roots of Functions
/*--------------------------------------------------------------------*/
/* Problem chapter6_37 */
/* */
/* This program determines the real roots of a quadratic */
/* equation, assuming that the user enters the coefficients of */
/* the quadratic equation. */

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
/* Declare variables. */
double a, b, c, discriminant, root1,root2;

/* Prompt user for equation. */


cout << "Enter a,b,c for equation ax^2 + bx + c: ";
cin >> a >> b >> c;
cout << "Equation is: " << a << "x^2 + " << b << "x + "
<< c << " = y\n";

/* Are the roots complex? */


discriminant = b*b - 4*a*c;
if (discriminant < 0.0)
cout << "Complex roots!";
else
{

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


root1 = (-b + sqrt(discriminant)) / (2*a);
root2 = (-b - sqrt(discriminant)) / (2*a);
cout << "Roots are: x1=" << root1 << ", x2=" << root2 << endl;
}

/* Exit program. */
return 0;
}
/*--------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/
/* Problem chapter6_38 */
/* */
/* This program determines the roots of a quadratic equation. */

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
/* Declare variables. */
double a, b, c, discriminant, root1, root2;

/* Prompt user for equation. */


cout << "Enter a,b,c for equation ax^2 + bx + c: ";
cin >> a >> b >> c;
cout << "Equation is: " << a << "x^2 + " << b << "x + "
<< c << " = y\n";

/* Are the roots complex? */


discriminant = b*b - 4*a*c;
if (discriminant < 0.0)
{
root1 = -b/(2*a);
root2 = sqrt(abs(discriminant))/(2*a);
cout << "Roots are: x1= " << root1 << " + i" << root2 << ", x2 = "
<< root1 << " -i" << root2 << endl;
}
else
{
root1 = (-b + sqrt(discriminant)) / (2*a);
root2 = (-b - sqrt(discriminant)) / (2*a);
cout << "Roots are: x1=" << root1 << ", x2=" << root2 << endl;
}

/* Exit program. */
return 0;
}
/*--------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/
/* Problem chapter6_39 */
/* */
/* This program evaluates this mathematical function: */
/* f(x) = 0.1 x^2 - x ln x */

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


#include <iostream>
#include <cmath>

using namespace std;

void check_roots(double left, double right);


double f(double x);

int main()
{
/* Declare variables. */
int n, k;
double a, b, step, left, right;

/* Get user input. */


cout << "Enter interval limits a, b (a<b): \n";
cin >> a >> b;
cout << "Enter step size: \n";
cin >> step;

/* Check subintervals for roots. */


n = ceil((b - a)/step);
cout << "n is " << n << endl;
for (k=0; k<=n-1; k++)
{
left = a + k*step;
if (k == n-1)
right = b;
else
right = left + step;
check_roots(left,right);
}
check_roots(b,b);

/* Exit program. */
return 0;
}
/*--------------------------------------------------------------------*/
/* This function checks a subinterval for a root. */

void check_roots(double left, double right)


{
/* Declare variables and function prototypes. */
double f_left, f_right;
double f(double x);

/* Evaluate subinterval endpoints and test for roots. */


f_left = f(left);
f_right = f(right);
if (fabs(f_left) < 0.1e-04)
cout << "Root detected at " << left << endl;
else
if (!(fabs(f_right) < 0.1e-04))
if (f_left*f_right < 0)
cout << "Root detected at " << (left+right)/2 << endl;

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


/* Exit function. */
return;
}
/*--------------------------------------------------------------------*/
/* This functions evaluates a mathematical function given */
/* in problem 28. Be sure not to call with x < 0. */

double f(double x)
{
/* Return function value. */
return (0.1*x*x - x*log(x));
}
/*--------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/
/* Problem chapter6_40 */
/* */
/* This program finds the roots of this function in a */
/* user-specified interval: f(x) = sinc(x) */

#include <iostream>
#include <cmath>
using namespace std;

double sinc(double x);


void check_roots(double left, double right);

int main()
{
/* Declare variables. */
int n, k;
double a, b, step, left, right;

/* Get user input. */


cout << "Enter interval limits a, b (a<b): \n";
cin >> a >> b;
cout << "Enter step size: \n";
cin >> step;

/* Check subintervals for roots. */


n = ceil((b - a)/step);
for (k=0; k<=n-1; k++)
{
left = a + k*step;
if (k == n-1)
right = b;
else
right = left + step;
check_roots(left,right);
}
check_roots(b,b);

/* Exit program. */
return 0;
}
/*--------------------------------------------------------------------*/
/* This function checks a subinterval for a root. */

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


void check_roots(double left, double right)
{
/* Declare variables. */
double f_left, f_right;

/* Evaluate subinterval endpoints and */


/* test for roots. */
f_left = sinc(left);
f_right = sinc(right);
if (fabs(f_left) < 0.1e-04)
cout << "Root detected at " << left << endl;
else
if (!(fabs(f_right) < 0.1e-04))
if (f_left*f_right < 0)
cout << "Root detected at " << (left+right)/2 << endl;

/* Void return. */
return;
}
/*--------------------------------------------------------------------*/
/* This function evaluates a sinc function. */

double sinc(double x)
{
/* Return function value. */
if (x == 0)
return 1;
else
return sin(x)/x;
}
/*--------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/
/* Problem chapter6_41 */
/* */
/* This program estimates the roots of a subinterval using this */
/* approximation: c = (a*f(b) - b*f(b)) / (f(b) - f(a)) */

#include <iostream>
#include <cmath>
using namespace std;

void check_roots(double left, double right, double a0,


double a1, double a2, double a3);
double poly(double x, double a0, double a1,
double a2, double a3);

int main()
{

/* Declare variables. */
int n, k;
double a0, a1, a2, a3, a, b, step, left, right;

/* Get user input. */

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


cout << "Enter coefficients a0, a1, a2, a3: \n";
cin >> a0>> a1>> a2>> a3;
cout << "Enter interval limits a, b (a<b): \n";
cin >> a >> b;
cout << "Enter step size: \n";
cin >> step;

/* Check subintervals for roots. */


n = ceil((b - a)/step);
for (k=0; k<=n-1; k++)
{
left = a + k*step;
if (k == n-1)
right = b;
else
right = left + step;
check_roots(left,right,a0,a1,a2,a3);
}
check_roots(b,b,a0,a1,a2,a3);

/* Exit program. */
return 0;
}
/*--------------------------------------------------------------------*/
/* This function checks a subinterval for a root. */

void check_roots(double left, double right, double a0,


double a1, double a2, double a3)
{
/* Declare variables. */
double f_left, f_right,c;

/* Evaluate subinterval endpoints and test for roots. */


f_left = poly(left,a0,a1,a2,a3);
f_right = poly(right,a0,a1,a2,a3);

if (fabs(f_left) < 0.1e-04)


cout << "Root detected at " << left << endl;
else
if (!(fabs(f_right) < 0.1e-04))
if (f_left*f_right < 0) {
c = (left*f_right - right*f_left)/(f_right - f_left);
cout << "Root detected at " << c << endl;
}

/* Void return. */
return;
}
/*--------------------------------------------------------------------*/
/* (poly function from page 231) */
/*--------------------------------------------------------------------*/

/*-------------------------------------------------------------------------*/
/* Program chapter6_42 */
/* */
/* This program finds the real roots of a polynomial using the */
/* Newton-Raphson method using functions that evaluate the polynomial */

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


/* and its derivative. */

#include <iostream>
#include <cmath>
using namespace std;

double polynomial(double a, double b, double c, double d, double x);


double derivative(double a, double b, double c, double d, double x);

int main()
{
// Declare objects.
int iterations=0;
double a0, a1, a2, a3, x, p, dp, tol;

// Get user input.


cout << "Enter coefficients a0, a1, a2, a3\n";
cin >> a0 >> a1 >> a2 >> a3;
cout << "Enter initial guess for root\n";
cin >> x;

// Evaluate p at initial guess.


p = polynomial(a0, a1, a2, a3, x);

// Determine tolerance.
tol = abs(p);
while(tol > 0.001 && iterations < 100)
{
// Calculate the derivative.
dp = derivative(a0, a1, a2, a0, x);

// Calculate next estimated root.


x = x - p/dp;

// Evaluate p at estimated root.


p = polynomial(a0, a1, a2, a3, x);
tol = abs(p);
iterations++;
}
if(tol < 0.001)
{
cout << "Root is " << x << endl
<< iterations << " iterations\n";
}
else
cout << "Did not converge after 100 iterations\n";
return 0;
}
/*-------------------------------------------------------------------------*/
/* This function calculates the value of a polynomial function given */
/* coefficients. */
double polynomial(double a, double b, double c, double d, double x)
{
return a*pow(x,3) + b*x*x + c*x + d;
}
/*-------------------------------------------------------------------------*/
/* This function calculates the derivative of a polynomial function */

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


/* given coefficients. */
double derivative(double a, double b, double c, double d, double x)
{
return 3*a*x*x + 2*b*x + c;
}
/*-------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------*/
/* Program chapter6_43 */
/* */
/* This program estimates the area under a given curve */
/* using trapezoids with equal bases. */

#include <iostream>
#include <cmath>

using namespace std;

// Function prototypes.
double integrate(double a, double b, int n);
double f(double x);

int main()
{
// Declare objects
int num_trapezoids;
double a, b, area;

// Get input from user.


cout << "Enter the interval endpoints, a and b\n";
cin >> a >> b;
cout << "Enter the number of trapezoids\n";
cin >> num_trapezoids;
// Estimate area under the curve of 4e^-x
area = integrate(a, b, num_trapezoids);

// Print result.
cout << "Using " << num_trapezoids << " trapezoids, the estimated "
<< area is " << area << endl;

return 0;
}
/*------------------------------------------------------------------------*/
double integrate(double a, double b, int n)
{
// Declare objects.
double sum = 0, x, base, area;

base = (b-a)/n;
for(int k=2; k<=n; k++)
{
x = a + base*(k-1);
sum = sum + f(x);
}
area = 0.5*base*(f(a) + 2*sum + f(b));
return area;
}

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


/*-----------------------------------------------------------------------*/
double f(double x)
{
return (3*x - 2*pow(x,2));
}
/*-----------------------------------------------------------------------*/

/*------------------------------------------------------------------------*/
/* Program chapter6_44 */
/* */
/* This program estimates the area under a given curve */
/* using trapezoids with equal bases. The x- and y-coordinates of the */
/* trapezoid endpoints are printed to a data file called */
/* plotTrapezoids.txt so they can be plotted later. */

#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;

// Function prototypes.
double integrate(double a, double b, int n);
double f(double x);

int main()
{
// Declare objects
int num_trapezoids;
double a, b, area;

// Get input from user.


cout << "Enter the interval endpoints, a and b\n";
cin >> a >> b;
cout << "Enter the number of trapezoids\n";
cin >> num_trapezoids;
// Estimate area under the curve of 4e^-x
area = integrate(a, b, num_trapezoids);

// Print result.
cout << "Using " << num_trapezoids << " trapezoids, the estimated "
<< "area is " << area << endl;

return 0;
}
/*-----------------------------------------------------------------------*/
double integrate(double a, double b, int n)
{
// Declare objects.
double sum = 0, x, base, area;
ofstream out;

//Open output file


out.open("plotTrapezoids.txt");
if (out.fail()){
cerr << "Output file did not open.";
exit(1);
}

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


base = (b-a)/n;
out << a << " " << f(a);
for(int k=2; k<=n; k++)
{
x = a + base*(k-1);
sum = sum + f(x);
out << x << " " << f(x) << endl;
}
out << b << " " << f(b) << endl;
area = 0.5*base*(f(a) + 2*sum + f(b));

out.close();
return area;
}
/*-----------------------------------------------------------------------*/
double f(double x)
{
return(4*exp(-x));
}
/*-----------------------------------------------------------------------*/

/*-------------------------------------------------------*/
/* Problem chapter6_45 */
/* */
/* This program estimates the area under a curve */
/* using trapezoids. The curve is defined by a set of */
/* experimental data. The spacing of the independent */
/* variable across the interval is not uniform. */

#include<iostream>
#include<fstream>

using namespace std;

//Function prototype.
double integrate(istream&);

int main()
{
ifstream fin;
string filename;
double area;

cout << "enter the name of the data file ";


cin >> filename;
fin.open(filename.c_str());
if(fin.fail())
{
cerr << "error opening file " << filename << endl;
exit(1);
}
area = integrate(fin);
cout << "The area under the curve is " << area << endl;
return 0;
}
/*-------------------------------------------------------*/

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


double integrate(istream& in)
{
double x1, x2, y1, y2, base, area(0);
in >> x1 >> y1;
in >> x2 >> y2;
while(!in.eof())
{
base = x2-x1;
area += 0.5*base*(y1 + y2);
x1 = x2;
y1 = y2;
in >> x2 >> y2;
}
return area;
}
/*--------------------------------------------------------------------*/
Value Returning Functions

/*--------------------------------------------------------------------*/
/* Function chapter6_46 */
/* */
/* This function calculates the number of permutations of n things, */
/* taken k at a time. */

/* Declare function prototype. */


int n_fact(int);

int permute(int n, int k)


{

/* Return number of permuations. */


return (int)(n_fact(n)/(n_fact(n-k)) + 0.5 );
}
/*-------------------------------------------------------------------*/
/* (n_fact function */
int n_fact(int n)
{
int rValue=1;
for(int i=n; i>1; --i)
{
rValue *= i;
}
return rValue;
}
/*-------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/
/* Function chapter6_47 */
/* */
/* This function calculates the number of combinations of n things, */
/* taken k at a time using a factorial function from problem 20. */

/* Define function prototype. */


int n_fact(int);

int combine(int n, int k)

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


{

/* Return number of combinations. */


return (int)(n_fact(n)/(n_fact(k)*n_fact(n-k)) + 0.5 );
}
/*--------------------------------------------------------------------*/
/* (n_fact function from Problem 6_46) */
/*--------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/
/* Problem chapter6_48 */
/* */
/* This program compares the cosine of an angle using the library */
/* function with the value computed from the first five terms */
/* of this series: cos x = 1 - x^2/2! + x^4/4! ..... */

#include <iostream>
#include <cmath>
using namespace std;

const double EULER = 2.718282;


const double PI = 3.141593;
const int SERIES_LENGTH = 5;

int n_fact(int n);


double s_cosine(double x);

int main()
{
/* Define variables. */
double x;

/* Get x from user. */


cout << "\nEnter x in radians: ";
cin >> x;

/* Get series cosine. */


cout << "Series cosine: "<< s_cosine(x) << endl;
cout << "C library cosine: " << cos(x) << endl;

/* Exit program. */
return 0;
}
/*-------------------------------------------------------------------*/
/* This function calculates the series for cosine */
/* for a specified number of terms. */

double s_cosine(double x)
{
/* Declare variables. */
int i;
double sum=1;

/* Compute cosine sum. */


for (i=1; i<SERIES_LENGTH; i++)
{
sum += pow((double)-1,i)*pow(x,2*i)/n_fact(2*i);

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


}

/* Return series sum. */


return sum;
}
/*--------------------------------------------------------------------*/
/* (n_fact function from Problem 6_46) */
/*--------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/
/* Problem chapter5_49 */
/* */
/* This program compares the cosine of an angle using the library */
/* function with the value computed from terms > 0.0001 */
/* of this series: cos x = 1 - x^2/2! + x^4/4! ..... */

#include <iostream>
#include <cmath>
using namespace std;

const double EULER = 2.718282;


const double PI = 3.141593;
const double MAX_TERM = 0.001;

int n_fact(int n);


double s_cosine(double);

int main()
{
/* Define variables. */
double x;

/* Get x from user. */


cout << "\nEnter x in radians: ";
cin >> x;

/* Get series cosine. */


cout << "Series cosine: " << s_cosine(x) << endl;
cout << "C library cosine: " << cos(x) << endl;

/* Exit program. */
return 0;
}
/*--------------------------------------------------------------------*/
/* This function caluclates the series for cosine using terms */
/* that are greater than a specified value. */

double s_cosine(double x)
{
/* Declare variables. */
int i=0;
double sum=0, term=1;

/* Determine cosine sum. */


while (fabs(term) > MAX_TERM)
{
sum += term;

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


i++;
term = pow((double)-1,i)*pow(x,2*i)/n_fact(2*i);
}
cout << "Number of terms in the series: " << i << endl;

/* Return cosine sum. */


return sum;
}
/*-------------------------------------------------------------------*/
/* (n_fact function from Problem 6_46) */
/*-------------------------------------------------------------------*/

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

You might also like