what's wrong with my program..

I'm writing a simple program but i don't why my program does not working.

#include <stdio.h>
#include <math.h>

void main(void)
{
FILE *out;

float a[1000];
float lambda = 1.0e-3;
float s;
int k;
int m = 2;


out=fopen("myfile.txt","w");

for (s=0.1; s < 1.0; s+=0.1)
{
for (k=0; k<=1000; k++)
{
a[0]=1.0e-5;
a[k+1]=a[k] + lambda * pow((a[k]),(m/2)) * pow(s,m);
fprintf(out, "\n%lf\n",s,k,a[k+1]);
}
}

fclose(out);
}

But the generated output is not what i look for.. how i am going to fixed it?

For example i need to print out the value of s, k and a[k+1]. and the iterations seem wrong.It suppose to come out like this:

(example answer only)

s k a[k+1]

0.1 1 1.0002e-5
0.1 2 1.0003e-4
.
.
0.2 1 1.0005e-4
.
.
.
1 1000 1.011e-2

another thing: is it possible if i want to draw this number into line chart/graph through this program?

Well to start with:

1. This loop is faulty and will cause stack corruption:
for (k=0; k<=1000; k++)
{
a[0]=1.0e-5;
a[k+1]=a[k] + lambda * pow((a[k]),(m/2)) * pow(s,m);
fprintf(out, "\n%lf\n",s,k,a[k+1]);
}


2. This only prints/saves the variable s
fprintf(out, "\n%lf\n",s,k,a[k+1]);
guestgulkan: if this is the equation that i've to use.. without changing it.. is there any other way to do that?

a[k+1]=a[k] + lambda * pow((a[k]),(m/2)) * pow(s,m);

btw, thanks for your reply.. i really appreciate it.
What I'm saying is that the a array is 1000 elements. These elements are index from 0 to 999
If your loop goes up to this k<=1000 value then at some point you will
be saying a[999+1]=a[999] and then a[1000+1]=a[1000] which are array out of bounds access.

The most your loop will be able to go to and stay withing the bounds of the array is 998.
so at most you will have a[998+1]=a[998] and the loop should then stop.

Do you see what I mean??
Last edited on
closed account (S6k9GNh0)
And you don't want that big of an array on the stack. You need to stick it on the heap.

float * pA = new float[1000];
And you want int main().
From a design perspective you may want to make lambda and m constant.

Then you may think about creating a class to move only your formula calculations to it i.e. a 'PowerSeries' class and have a method 'Calculate' that returns the an array with the output you want, or just the value of the nth series, etc.

You can make your constants (lambda and m) const members of that new class and the rest of variables (if any) you can pass them on the constructor or as parameters of the 'Calculate' method, etc. Now you can reuse you power series formulae from other programs.

The above is just for future development. I think the other guys have already more than solved your run-time problem.
thanks a lot... u guys really help me..
Topic archived. No new replies allowed.