Implement a function for each of following problems

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

CODE:

#include<stdio.h>

#include<conio.h>

void loop(int n);

void main()

{

int n;

clrscr();

printf(“enter the value of n”);

scanf(“%d”,&n);

loop(n);

getch();

}

void loop(int n)

{

int count=0;

int i, sum=0;

count++;

for(i=1;i<=n;i++)

{

   count++;

   sum=sum+i;

   count++;

}

count++;

count++;

printf(“loop of sum=%d”,sum);

printf(“\n count for loop=%d”,count);

}

2. To calculate sum of 1 to N number using equation.

CODE:-

#include<stdio.h>

#include<conio.h>

void equation(int n);

void main()

{

int n;

clrscr();

printf(“enter the value of n”);

scanf(“%d”,&n);

equation(n);

getch();

}

 void equation(int n)

 {

   int sum,count=0;

   count++;

   sum=n*(n+1)/2;

   count++;

   printf(“—–equation—–\n”);

   printf(“sum=%d”,sum);

   printf(“\n count for loop=%d”,count);

 }

OUTPUT:

Time Complexity For Find sum using Equation:-2

3. To calculate sum of 1 to N numbers using recursion.

CODE:

#include<stdio.h>

#include<conio.h>

int recursion(int n);

int count=0;

void main()

{

int n;

clrscr();

printf(“enter the value of n”);

scanf(“%d”,&n);

printf(“recursion sum=%d\n”,recursion(n));

printf(“count=%d”,count);

getch();

}

int recursion(int n)

{

 count++;

 if(n==0)

 {

 count++;

 return 0;

 }

 else

 {

  count++;

  return (n+recursion(n-1));

  }

 }

OUTPUT:

Time Complexity For Find sum using Recursion:-2n+2

Number Loop Equation Recursion
50 103 2 102
100 203 2 202
150 303 2 302
300 603 2 602
600 1203 2 1202
1000 2003 2 2002