Write a function that accepts an array of integers and determines the difference between the integers. For example, if the array [3 7 8 13 11] is passed to the function, it prints to the screen [3 4 1 5 -2].

mine give me : 3, 4 ,4 9, 2
but i cant see why its wrong! please help

#include <iostream>
using namespace std;

#define n 5

void ArraySub(double* MainArray)
{
	int i;

	for (i=1; i<n; i++)
	{
		MainArray[i] = MainArray[i] - MainArray[i-1];
	}
}

int main(void)
{
	double Array[n] = { 3, 10, 243, 8374, 102893};

	ArraySub(Array);

	for (int i=0; i<n; i++)
	{
		cout << Array[i] << endl;
	}

	return 1;
}

Write a function that accepts an array of integers and determines the difference between the integers. For example, if the array [3 7 8 13 11] is passed to the function, it prints to the screen [3 4 1 5 -2].

mine give me : 3, 4 ,4 9, 2
but i cant see why its wrong! please help

#include <iostream>
using namespace std;

#define n 5

void ArraySub(double* MainArray)
{
	int i;

	for (i=1; i<n; i++)
	{
		MainArray[i] = MainArray[i] - MainArray[i-1];
	}
}

int main(void)
{
	double Array[n] = { 3, 10, 243, 8374, 102893};

	ArraySub(Array);

	for (int i=0; i<n; i++)
	{
		cout << Array[i] << endl;
	}

	return 1;
}

Hello, when you do your first subtraction everything is ok. However, the next subtractions aren't proper, because you subtract the result you've already calculated (from the previous loop) from the elements of the array. Copy your elements in another array inside the function in order to achieve the right subtractions:

void ArraySub(double* MainArray)

      {
      double temp[n];

      for (int i = 0; i < n; i++)
       temp[i] = MainArray[i]; //here i copy all values from MainArray to temp

      for (int i=1; i<n; i++)
      MainArray[i] = MainArray[i] - temp[i-1]; //here the right subtractions take place

      }

Hint: have a double variable that holds the previous value in the array, and a variable for the current value of the array. Subtract the current from the previous. Also, remember that 2 minus 9 is -7, but the difference is an absolute number: 7. (You'll need to use fabs().)

Also, don't rely upon knowing the size of your array. Pass it as argument to your function. void ArraySub(double* MainArray, unsigned n) Finally, if your program terminates properly, you should return 0; Hope this helps.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.