Write a function for each of the following problems and count the number of steps for execution and write the time complexity of each function,
1. To calculate the sum of 1 to N numbers using loop.
2. To calculate the sum of 1 to N numbers using equation.
3. To calculate the sum of 1 to N numbers using recursion.
#include <stdio.h>
#include <conio.h>
int rcount=0;
int uloop(int n)
{
int sum=0,count=0, i;
count++;
count++;
for(i=1;i<=n;i++)
{
sum=sum+i;
count++;
}
count++;
printf("\nCount is:%d",count);
return sum;
}
int uequation(int n)
{
int sum,count=0;
count++;
sum=(n*(n+1))/2;
count ++;
count ++;
printf("\ncount is:%d",count);
return sum;
}
int urecursion(int n)
{ rcount++;
if(n<=0)
{
rcount++;
return n;
}
else
{
rcount++;
return urecursion(n-1)+n;
}
}
void main()
{
int n,choice, sum;
clrscr();
printf("\nEnter value of n\n");
scanf("%d",&n);
printf(“\n==For Loop==”);
sum=uloop(n);
printf("\nsum is %d",sum);
printf(“\n\n==For Equation==”);
sum=uequation(n);
printf("\nsum is %d",sum);
printf(“\n\n==For Recursion==”);
sum=urecursion(n);
printf("\ncount is :%d",rcount);
printf("\nsum is %d",sum);
getch();
}
Comments
Post a Comment