columns of related data

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.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <fstream>
#include <cmath>
using namespace 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.
*/

const double PI = acos(-1.0);	// get PI using a little trigonometry

const int 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;
}
Last edited on
closed account (o3hC5Di1)
Hi there,

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.

All the best,
NwN
If you already did complete your sawtooth http://www.cplusplus.com/forum/beginner/111163/
then this should not be hard either.

You should already know the correct value for NPTS. It is trivial to calculate.
Topic archived. No new replies allowed.