Implement a function for each of following problems and count the number of steps executed | C Programming

 

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.

  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.



#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*/
  }
}
AJ Blogs

Hello everyone, My name Arth and I like to write about what I learn. Follow My Website - https://sites.google.com/view/aj-blogs/home

Post a Comment

Previous Post Next Post
Best Programming Books

Facebook

AJ Facebook
Checkout Our Facebook Page
AJ Blogs
Checkout Our Instagram Page