Thomas Chadwick
Thomas Chadwick

Reputation: 13

Using a variable outside of a loop, value changes within the loop

I am relatively new to programming and I have come across an issue whilst trying to write a function that utilizes loops. The function should work as such:

The array Data consists of a 51X2 set of doubles, which are all used in the program through the initial for loop, the a variable and the b variable. The X and Y variables are both set to the minimum values of the array.

Using the a and X variables as an example, the X value is compared to a and incremented until it surpasses a. The number of loop iterations are tracked by the c variable. This c variable is then used in the Graph array. The same procedure occurs for the b and Y variables. This process is repeated for every value of S to analyse all data points from the Data array.

The issue I'm having is that the c and d variables don't change relative to the changes inside the loops. The variables will not change from their initialized value. I am looking to find a solution that allows for the c and d variables to change in relation to the number of iterations of the for loop.

The relevant function code can be seen below:

void Data_Plot(double Data[51][2], char Graph[44][56])
{
    int N = 50;
    int S,q,r;
    int c = 0;
    int d = 0;
    double a = Data[S][0];
    double b = Data[S][1];
    double X = Data[0][0];
    double Y = Data[0][1];
    for (S=0;S<N;S++)
    {   
        for(X;X<a;X+=0.1428571429)
        {
            c++;
        }
        for(Y;Y<b;Y+=2)
        {
            d++;
        }

        Graph[c][d] = '*'; 
    }

I am aware that my code is very unoptimized and messy, but I can fix those issues up with future projects after I have finished this one.

Edit: I would like to note that I have attempted this with c and d being set to other values, as well as being left as NULL. The same result occurred regardless of the variable initialization.

Upvotes: 1

Views: 3954

Answers (1)

Barmar
Barmar

Reputation: 780724

Since a and b depend on S, which you change during the for loop, you need to move those variables inside the loop.

void Data_Plot(double Data[51][2], char Graph[44][56])
{
    int N = 50;
    int S,q,r;
    int c = 0;
    int d = 0;
    double X = Data[0][0];
    double Y = Data[0][1];
    for (S=0;S<N;S++)
    {   
        double a = Data[S][0];
        for(X;X<a;X+=0.1428571429)
        {
            c++;
        }

        double b = Data[S][1];
        for(Y;Y<b;Y+=2)
        {
            d++;
        }

        Graph[c][d] = '*'; 
    }

Upvotes: 2

Related Questions