We need to sum n numbers using for,while, and do while loops..
and need to compare the execution time for each of them.
I wrote the following code.
but every time the output comes out to be different!!
so not able to decide which loop executes the fastest.
kindly help me figure this out..
Code:
#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<dos.h>
#define n 20000
int sumfor();
int sumwhile();
int sumdowhile();
int a[n];
time_t first,second;
double tfor,twhile,tdowhile;
void main()
{
int i,s1,s2,s3;
// initializing the array..
for(i=0;i<n;i++)
{
a[i]=1;
}
}
s1=sumfor();
s2=sumwhile();
s3=sumdowhile();
if ((s1==s2) && (s2==s3))
printf("\nsum is %d",s1);
else
printf("\nerror!!!");
printf("\ntime with for loop %f",tfor);
printf("\ntime with while loop %f",twhile);
printf("\ntime with do-while loop %f",tdowhile);
getch();
}
int sumfor()
{ int i,p=0;
printf("\nRunning for loop");
first=time(NULL);
for(i=0;i<n;i++)
{
p=p+a[i];
printf("\nadding %d th element",i);
}
second=time(NULL);
tfor=difftime(second,first);
return p;
}
int sumwhile()
{
int i,p;
i=0;
p=0;
printf("\nRunning for while loop");
first=time(NULL);
while(i<n)
{
p=p+a[i];
printf("\n adding %d th element",i);
i++;
}
second=time(NULL);
twhile=difftime(second,first);
return p;
}
int sumdowhile()
{
int i,p;
i=0;
p=0;
printf("\nRunning for do while loop");
first=time(NULL);
do
{
p=p+a[i];
i++;
printf("\n adding %d th element",i);
}while(i<n);
second=time(NULL);
tdowhile=difftime(second,first);
return p;
}