Hi, I have two programs that perform the same task:
Code:
#define N 100000000
int main()
{
long int x;
double sum=0;
char str[100];
for (x=1;x<=N;x++)
sum = sum + x;
sprintf(str,"%.0lf\n",sum);
write(1,str,strlen(str));
exit(0);
}
Code:
#define N 100000000
double sum[N+1];
int main ()
{
long int x;
char str[100];
sum[0]=0;
for (x=1;x<=N;x++)
sum[x] = sum[x-1] + x;
sprintf(str,"%.0lf\n",sum[N]);
write(1,str,strlen(str));
exit(0);
}
In the first one the intermediate additions are being stored in the variable "sum", in the second one every addition is stored in the array. What is the reason behind the second one taking so much longer, if in both cases the value is being stored anyway?