2

I have coded a formula to read the txt file, store it in array(1D) and then reading the array to calculate the moving average(2D). Program ask the user to input two values (k1 & k2) and calculate the moving average for every value from k1 to k2 (basically to find out the best value) Following is the code

#include<stdlib.h>
#define MAX_FILE_NAME 100
#define MAXCHAR 1000
int main()
{
  FILE *fp;
  int count = 0,k1=0,k2=0,k=0; // Line counter (result)
  int buy[k2][count],sell[k2][count];

  char filename[MAX_FILE_NAME];
  char c; // To store a character read from file

  // Get file name from user. The file should be
  // either in current folder or complete path should be provided
  printf("Enter file name or full path: ");
  scanf("%s", filename);
  printf("Enter the minimum rolling period for calculation : \n");
  scanf("%d", &k1);
  printf("Enter the maximum rolling period for calculation : \n");
  scanf("%d", &k2);
  // Open the file

  fp = fopen(filename, "r");

  // Check if file exists
  if (fp == NULL)
  {
    printf("Could not open file %s", filename);
    return 0;
  }

  // Extract characters from file and store in character c
  for (c = getc(fp); c != EOF; c = getc(fp))
    if (c == '\n') // Increment count if this character is newline
      count = count + 1;

  // Close the file
  fclose(fp);
  //printf("The file %s has %d lines\n", filename, count);

  FILE *myFile;
  myFile = fopen(filename, "r");

  //read file into array
  float numberArray[count];
  int i;

  if (myFile == NULL){
    printf("Error Reading File\n");
    exit (0);
  }
  for (i = 0; i < count; i++){
    fscanf(myFile, "%f,", &numberArray[i]);
  }

  fclose(myFile);

  for (k=k1;k<=k2;k++)
  {
    float n;
    float data[count],mag[k2][count];
    double avg,sum;
    for (i=0;i<k-1;i++)
    {
      mag[k][i-1]=0;
      sum=sum+numberArray[i];
    }

    for(i=k-1;i<=count;i++)
    {
      mag[k][i-1]=avg;
      sum=sum+numberArray[i]-numberArray[i-k];
      avg = sum/k;
    }

    //    for(i=0;i<=count;i++)
    //    {
    //        printf("MA[%d][%d] = %0.2lf     ",k,i,mag[k][i]);
    //        if (i%3==0)
    //            printf("\n");
    //    }
  }

  for(k=k1;k<=k2;k++)
  {
    for(i=0;i<=count;i++)
      printf("MA[%d][%d] = %0.2lf     ",k,i,mag[k][i]);
  }
}
}

Now when I am trying to print mag[k][i] values outside the for loop, it is showing error 'mag' undeclared. But when I am putting the print command inside the loop (comment out portion in the code), it works fine.

UPDATED CODE AFTER FOLLOWING COMMENTS (STILL NOT WORKING THOUGH)

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>

#define MAX_FILE_NAME 100
#define MAXCHAR 1000

int main()
{
  FILE *fp;
  int count,k1,k2,k; // Line counter (result)
  char filename[MAX_FILE_NAME];
  char c; // To store a character read from file

  // Get file name from user. The file should be
  // either in current folder or complete path should be provided
  printf("Enter file name or full path: ");
  scanf("%s", filename);

  printf("Enter the minimum rolling period for calculation : \n");
  scanf("%d", &k1);

  printf("Enter the maximum rolling period for calculation : \n");
  scanf("%d", &k2);

  // Open the file
  fp = fopen(filename, "r");
  // Check if file exists
  if (fp == NULL)
  {
    printf("Could not open file %s", filename);
    return 0;
  }

  // Extract characters from file and store in character c
  for (c = getc(fp); c != EOF; c = getc(fp))
    if (c == '\n') // Increment count if this character is newline
      count = count + 1;

  // Close the file
  fclose(fp);
  //printf("The file %s has %d lines\n", filename, count);

  /****************
    File opening and reading section
   *****************************************************/
  FILE *myFile;
  myFile = fopen(filename, "r");

  //read file into array
  float numberArray[count];
  int i;

  if (myFile == NULL){
    printf("Error Reading File\n");
    exit (0);
  }
  for (i = 0; i < count; i++){
    fscanf(myFile, "%f,", &numberArray[i] );
  }
  fclose(myFile);

  /***********************************************
   Calculation of Moving Average and storing it in array
   ******************************************/
  int buy[k2][count],sell[k2][count];
  float mag[k2][count];
  for (k=k1;k<=k2;k++)
  {
    float data[count];
    double avg,sum;
    for (i=1;i<k;i++)
    {
      mag[k][i-1]=0;
      sum=sum+numberArray[i];
    }

    for (i=k-1;i<=count;i++)
    {
      mag[k][i-1]=avg;
      sum=sum+numberArray[i]-numberArray[i-k];
      avg = sum/k;
    }

//    for(i=0;i<=count;i++)
//    {
//        printf("MA[%d][%d] = %0.2lf     ",k,i,mag[k][i]);
//        if (i%3==0)
//            printf("\n");
//    }
   }

   for (k=k1;k<=k2;k++)
   {
     for (i=0;i<=count;i++)
     {
       printf("MA[%d][%d] = %0.2lf     ",k,i,mag[k][i]);
     }
   }
}
12
  • 2
    Welcome to SO. You could improve the readability of your code a lot by indenting it properly. This will attract more readers. Commented Dec 20, 2018 at 8:23
  • 1
    int buy[k2][count],sell[k2][count]; At this line count contains 0. That is probably not what you want. Commented Dec 20, 2018 at 8:32
  • 3
    You might update your question to show the new code. Use the "edit" button and add the modified code below your old code. Removing the old code is not encouraged as it would make all comments and answers useless. Commented Dec 20, 2018 at 8:48
  • 2
    mag[k][i-1]=0; In that loop k runs up to <=k2 which is 1 too much and i starts at 0, making i-1 a bit too low. Commented Dec 20, 2018 at 8:49
  • 1
    char c needs to be int c otherwise you may not be able to detect EOF correctly. Commented Dec 20, 2018 at 17:01

1 Answer 1

2

The problem boils down to this: the scope of mag is limited to the inside of the for loop:

  for (k = k1; k <= k2; k++)
  {
    ...
    int mag[k2][count];
    ... 
  }

  // mag is out of scope here
  // therefore following line won't compile:

  printf("%d", mag[0][0]);

You need to declare mag outside the for loop for example like this:

  int mag[k2][count];      
  for (k = k1; k <= k2; k++)
  {
    ...
  }

  printf("%d", mag[0][0]);
  ...

Beware: there are other problems within your code, mentioned in the comments.

Sign up to request clarification or add additional context in comments.

5 Comments

If i am putting it outside the loop then it is not showing error in compilation, but when run it is showing error : The instruction at referenced memory could not be read. Click OK to terminate the program.
@MohdNaved this is because of other unrelated errors in your code. Read Gerhardh's second comment.
ohh yes, my mistake.. i just corrected as per the guidelines of Gerhardh.. now its working but a new issue arises now.. its showing all values of mag[][] equal to zero :-(
@MohdNaved that's a very different question. It's a perfect opportunity to learn how to use the debugger. It's a small invesment in time, which will pay off very quickly.
code was working fine when user was supposed to enter only one value of k, and mag was one dimensional.. but when i modified the code to let user enter two values k1 & k2.. and converted moving average into 2D, since then i am in trouble.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.