Hi, I have a large array of values and would like to find a way to calculate the change in value for each period. I have been attempting to use a for command with an array to do this, but I have not been successful at all. The basic idea is this:

Value1 = A
Value 2 = B
Value 3 = C
Value 4 = D
Value 5 = D
...

I wish to return
Change1 = (B - A)/A
Change 2 = (C - B)/B
Change 3 = (D - C)/C
Change 4 = (E - D)/D
...

I have an array of a couple thousand values, so I would like to automate this.

Also, I am quite novice at C++.

I really appreciate any advice that you guys can offer. Thanks in advance.

Dani AI

Generated

A few concrete points that explain why the original program failed and a small, safer pattern to use.

The root causes in the thread were: a type mismatch (an integer array used for fractional data), a stray semicolon after the for header that made the loop body run only once, and an off‑by‑one index that accessed past the last element. addressed those directly and suggested separating the calculation from the output; ’s advice to sketch simple pseudocode first is helpful for avoiding these mistakes.

Checklist before coding:

  • Store fractional values in a floating type (double) or a container of doubles.
  • Loop only while a “next” element exists (avoid accessing index+1 when index is the last).
  • Check for zero before dividing (or use an explicit NaN/flag for undefined returns).
  • Don’t mix declaration/assignment inside a single output expression — do the math, then print.

Example (uses std::vector, safe bounds, zero check, and clearer formula curr/prev - 1):

#include <iostream>
#include <vector>
#include <iomanip>
#include <limits>

int main() {
    std::vector<double> prices = {1.01, 2.22, 3.03, 4.04, 5.05};
    if (prices.size() < 2) return 0;

    std::vector<double> changes;
    changes.reserve(prices.size() - 1);

    for (size_t k = 1; k < prices.size(); ++k) {
        double prev = prices[k - 1];
        double curr = prices[k];
        if (prev == 0.0) changes.push_back(std::numeric_limits<double>::quiet_NaN());
        else changes.push_back(curr / prev - 1.0);
    }

    for (double r : changes)
        std::cout << std::fixed << std::setprecision(6) << r << '\n';
}

Extra notes: for monetary data avoid raw doubles (use integer cents or a decimal library), and consider unit tests with small arrays to catch off‑by‑one and division‑by‑zero errors early.

Recommended Answers

All 5 Replies

for loop is very likely your best option. Can you show us any code that you have written? Even if you think the code is wrong, please link it. At the very least, consider writing up a pseduocode to see if we agree with the logical approach.

Writing pseduocode (writing in layman's terms) helps no matter what programming language you are writing in. Once you have that written down, the syntax tends to slide in nicely.

(B - A) / A can't be calculated unless A and B and the rest of the letters have numerical values, so that's a question even before getting to the array aspect of your question. I assume that all the types are doubles? You don't mention that. Best not to assume anything. For the sake of arguments, let's say everything is a double and {A,B,C,D,E} have values 1.0 to 5.0 respectively, so the math works.

So presumably you have an array of 1000 doubles called value[] and an array of 1000 doubles called change[] and you're trying to calculate change[] from value[]. Each individual calculation would go like this.

change[i] = (value[i+1]-value[i]) / value[i];

Sticking it in a for-loop would be something like this.

for(int i = 0; i < 999; i++)
{
    change[i] = (value[i+1]-value[i]) / value[i];
}

This is the code that I attempted to do. Notice that the first half shows my attempt and the second half clarifies what I would like the for command to do. I believe that my issue is in how I define the arrays. Thank you again for your help, its much appreciated.

#include <iostream>
using namespace std;

int main ()
{


/*This is my attempt to fix the problem */

    int  value[]={16.3,2.5,4.7,6.2,3.4};

    for(int i=0; i<5; i++);
        {
            cout << int change[i]=(value[i+1]-value[i])/value[i] << endl;;
        }

/*This is what I would actually like the for command to do */

 double array[5]={1.01,2.22,3.03,4.04,5.05};
    cout << (array[1]-array[0]) / array[0] << endl;
    cout << (array[2]-array[1)]) / array[1] << endl;
    cout << (array[3]-array[2]) / array[2] << endl;
    cout << (array[4]-array[3]) / array[3] << endl;
    cout << (array[5]-array[4]) / array[4] << endl;


    return 0;
}

Change line 12 from

for(int i=0; i<5; i++);

to

for(int i=0; i<4; i++)

i cannot equal 4. If it does, you are referencing value[i+1]. Stick 4 in there for i and you get value[4+1] = value[5]. That's illegal since value[] has five elements, so valid indexes would be 0 through 4.

Second, not that I got rid of the semicolon. For-loops don't have semi-colons.

Now for line 14...

You can't do this...

int change[i]

You need to declare the array like you did in line 10, just don't use any values.

double change[5];

Note that it's double, not int. You need to change line 10 to be the same. 16.3 is not an integer, so you can't use it in an array of integers. So get rid of line 10 and replace it with this.

double value[]={16.3,2.5,4.7,6.2,3.4};
double change[5];

The loop is now this.

for(int i=0; i<4; i++)
{
    cout << change[i]=(value[i+1]-value[i])/value[i] << endl;
}

That loop is trying to do an awful lot in one line. Try breaking it into two.

for(int i=0; i<4; i++)
{
    change[i]=(value[i+1]-value[i])/value[i];
    cout << change[i] << endl;
}

Wow. That fixed my problem. Thank you so much. Words can't express my gratitude.

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.