The fourth sample array program below should help you with this part of the lab.
Like the sample program, calculate a range of x-values, then calculate a set of y and a set of z values based on the x values.
Calculate X from -2.0 to 2.0, in steps of 0.1 .
calculate y=x-squared for each value of x,
calculate z=x-cubed for each value of x.
Output results to a file "powers.txt". You can verify your results fairly easily by hand-checking a few of the values (be sure to check beginning and end of your data), then plot the entire sequence with excel or matlab to see if looks correct. (You do not need to turn in a plot of your data…that’s to help you verify that you got it right.)
#include <iostream>
#include <fstream>
#include <cmath>
usingnamespace std;
/* sample program to demonstrate two parallel arrays.
array X contains x-values from 0 to 2 PI.
array Y contains the sin(X) for each X element.
*/
constdouble PI = acos(-1.0); // get PI using a little trigonometry
constint NPTS = 100; // define NPTS to be 100, the # of data points we'll use
int main()
{
int i;
double x[NPTS], y[NPTS]; // note: NPTS has to be a constant here.
// initialize the X array.
for (i=0;i<NPTS;i++)
x[i] = i * 2*PI/NPTS;
// now fill in the Y values. Yi = sine(Xi).
for (i=0;i<NPTS;i++)
y[i] = sin(x[i]);
// now output the results to a CSV file which can be read by excel
ofstream ofs("sines.csv");
for (i=0;i<NPTS;i++)
ofs << x[i]<<" , "<<y[i]<<endl;
cout << endl<<"results written to \"sines.csv\". \nYou should be able to open this with Excel, plot it and see a sine wave."<<endl;
return 0;
}
Please don't just copy us your homework assignment.
If you need help, please formulate your questions, errors, etc. clearly so we can take it from there.