Basically in my program, I am using a for loop, it assigns values to each element of the array and stores them in it and then writes them out and it gives good results. However, when I exit the loop and want to write out the elements of this array I get wrong results all equal to 0.0000. How do I overcome this and keep the results outside of the for loop ?
// declares arrays of the given size
double array[50];
// I calculate the length of the array using sizeof
double array_lenght = sizeof(array) / sizeof(array[0]);
printf("%lf \n", array_lenght);
//declares two variables of type double one for the area over which it will generate x the other for incrementing the deltaX difference
double length;
double deltaX;
// I count the differences of the domains and the value of one sample for x and display it
length = Dmax - Dmin;
deltaX = length / 50;
printf("Delta x = %lf \n", deltaX);
double i;
for(i = Dmin; i < Dmax; i =deltaX)
{
// assigns to each element in the array the value of x increased by delta x and stores them in my array.
int k = 0;
array[k] = i;
double y = A * cos(i/B) C * sin(i) D;
printf("For a sample of %lf, the assigned function is %lf \n", array[k], y);
k ;
}
printf("Elements of original array: \n");
for (int i = 0; i < array_length; i ) {
printf("%lf ", array[i]);
}
CodePudding user response:
You're writing to the same array element (element 0) over and over again:
double i;
for(i = Dmin; i < Dmax; i =deltaX)
{
// assigns to each element in the array the value of x increased by delta x and stores them in my array.
int k = 0;
array[k] = i;
double y = A * cos(i/B) C * sin(i) D;
printf("For a sample of %lf, the assigned function is %lf \n", array[k], y);
k ;
}
The initializer for k
sets k
to 0
on each loop iteration. Just move it outside the loop:
double i;
int k = 0;
for(i = Dmin; i < Dmax; i =deltaX)
{
// assigns to each element in the array the value of x increased by delta x and stores them in my array.
array[k] = i;
double y = A * cos(i/B) C * sin(i) D;
printf("For a sample of %lf, the assigned function is %lf \n", array[k], y);
k ;
}
That way it will step through the array as intended.
CodePudding user response:
I think you misplaced your k declaration.
double i;
int k = 0; // <--- moved outside of the loop
for(i = Dmin; i < Dmax; i =deltaX)
{
//int k = 0; <--- keeps resetting k
array[k] = i;
double y = A * cos(i/B) C * sin(i) D;
printf("For a sample of %lf, the assigned function is %lf \n", array[k], y);
k ;
}