Thursday, July 12, 2018

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. Also draw a comparative chart. In each of the following function N will be passed by user. 1. To calculate sum of 1 to N number using loop. 2. To calculate sum of 1 to N number using equation. 3. To calculate sum of 1 to N numbers using recursion. - DAA

#include<stdio.h>

int add(int n);
int count1=0;
int count2=0;
int count3=0;

int main()
{
 int n;
 printf("Enter the NUmbers for addition : ");
 scanf("%d",&n);
 printf("Sum = %d",add(n));
 printf("\nEquation = %d",eq(n));
 printf("\nSum_Rec = %d",sum_rec(n));
 printf("\nAddition Count = %d",count1);
 printf("\nEquation Count = %d",count3);
 printf("\nRecursion Count = %d",count2);
 return 0;
}
int add(int n)
{
 int i,sum=0;
 count1++;
 for(i=1;i<=n;i++)
 {
  count1=count1+3;
  sum=sum+i;
 }
 count1=count1+2;
 return sum;
}

int eq(int n) 
{
 count3=count3+1;
 return (n*(n+1))/2;
}

int sum_rec(int n)
{
 if(n==1)
 {
  count2=count2+2;
  return 1;
 }
 else
 {
  count2=count2+2;
  return sum_rec(n-1)+n;
 }
}

1 comment: