Implement a function for each of following problems and count the number of steps executed/Time taken by each function on various inputs and write complexity of each function. In each of the following function N will be passed by user.
To calculate sum of 1 to N number using loop.
To calculate sum of 1 to N number using equation.
To calculate sum of 1 to N numbers using recursion.
#include <stdio.h>
int sum(int n);
int equation(int n);
int sum_recursion(int n);
int count1 = 0;
int count2 = 0;
int count3 = 0;
int main()
{
int n;
printf("Enter the Numbers for addition : ");
scanf("%d",&n);
/* Printing the sum of numbers using Loop Recursion and Equation*/
printf("Sum = %d",sum(n));
printf("\nEquation = %d",equation(n));
printf("\nSum_Recursion = %d",sum_recursion(n));
/*Number of Times Loop Recursion and Equation are running*/
printf("\nLoop Count = %d",count1);
printf("\nRecursion Count = %d",count2);
printf("\nEquation Count = %d",count3);
return 0;
}
/* To calculate sum of 1 to N number using loop */
int sum(int n)
{
int i,sum=0;
count1++;
for(i=1;i<=n;i++)
{
count1=count1+3;
sum=sum+i;
}
count1=count1+2;
return sum;
}
/* To calculate sum of 1 to N number using equation */
int equation(int n)
{
count3=count3+1;
return (n*(n+1))/2;
}
/* To calculate sum of 1 to N numbers using recursion */
int sum_recursion(int n)
{
if(n==1)
{
count2=count2+2;
return 1;
}
else
{
count2=count2+2;
return sum_recursion(n-1)+n; /*Sum From Last Number to First Number*/
}
}
Tags:
C Programs