You are on page 1of 4

2CEIT402: Design & Analysis of Algorithm 21012012014

Practical-1

AIM: 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.

 CODE:

#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;
}
2CEIT402: Design & Analysis of Algorithm 21012012014

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;
system("cls");
printf("\nEnter value of n\n");
scanf("%d", &n);
printf("\nFor Loop");
sum = uloop(n);
2CEIT402: Design & Analysis of Algorithm 21012012014

printf("\nsum is %d", sum);

printf("\n\nFor Equation");
sum = uequation(n);
printf("\nsum is %d", sum);

printf("\n\nFor Recursion");
sum = urecursion(n);
printf("\ncount is :%d", rcount);
printf("\nsum is %d", sum);

getch();
}

 OUTPUT:
2CEIT402: Design & Analysis of Algorithm 21012012014

Graph:

45

40

35

30

25

20

15

10

0
5 10 15 20

LOOP EQUATION RECURSION

TABLE:
N LOOP EQUATION RECURSION

5 6 3 12

10 11 3 22

15 16 3 32

20 21 3 42

You might also like