how to store value of index of an array during while loop in C

int main()
{
   int abc[2][2];
   int i,j,q,r,u,k;
   char *A = malloc(sizeof(*A));

   abc[0][0] = 1;
   abc[1][0] = 0;
   abc[0][1] = 7;
   abc[1][1] = 480;

    do
    {
        if( abc[1][1]>abc[0][1])
        {

            q = floor((abc[1][1] - 1)/abc[0][1]);
            r = abc[1][1] - q*abc[0][1];
            abc[1][0] = q*abc[0][0] + abc[1][0];
            abc[1][1] = r;
        }

        if( abc[0][1]>abc[1][1])
        {
            q = floor((abc[0][1] - 1)/abc[1][1]);
            r = abc[0][1] - q*abc[1][1];
            abc[0][0] = q*abc[1][0] + abc[0][0];
            abc[0][1] = r;
        }

        u = abc[0][0];
        A[k] = abc[1][0];

    } while (abc[0][1]>1);
    return 0;
}

I want to store each the values for the index - abc[1][0] in array A[] so that I cant use that array further but I'm stuck at storing all the values

2 answers

  • answered 2018-04-17 05:49 Shahrukh Mushtaq

    A[k] = abc[1][0];
    

    You are storing a double dimension array to a single dimension.

  • answered 2018-04-17 06:01 4386427

    If you want to record the value of abc[1][0] in the end of each loop, you can do like this:

    int* A = malloc(1000 * sizeof(*A));  // Note: Room for 1000 values
    k = 0;
    
    ....
    ....
    do
    {
        ....
        ....
    
        if (k < 1000)
        {
            A[k] = abc[1][0];
            ++k;
        }
    } while (abc[0][1]>1);
    
    // Print the recorded values
    printf("Recorded %d values\n", k);
    int t;
    for (t = 0; t < k; ++t) printf("Value[%d]=%d\n", t, A[t]);
    

    This will record the first 1000 values.

    If you want to be able to record "any" number of values, you shall take a look at realloc so that you can assign more memory when you reach 1000