Time Complexity Code

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

Time complexity and common Asyptotic

#include<iostream>
using namespace std;
int main()
{
int myarr[10],n,i,sum=0,product=1; ------------------------------------- =1
cout<<"Enter your array size:"; --------------------------------------------- =1
cin>>n;
cout<<"Enter your array elements: "; -------------------------------------=1
for(i=0;i<n;i++) ---------------------------------------------------------------1+n+(n+1)
cin>>myarr[i];
for(i=0;i<n;i++) ----------------------------------------------------------------1+n+(n+1)
{
sum+=myarr[i]; --------------------------------------------------------------- =2n
product*=myarr[i];------------------------------------------------------------ =2n
}
cout<<"\n The sum of arry element is :"<<sum; ------------------------- =1
cout<<"\n The product of arry element is :"<<product; --------------- =1
return 0;
}

To understand the time complexity and common asymptotic notation of the above code, let’s see
how much time each statement will take:
int myarr[10],n,i,sum=0,product=1; //cost=1 no of times=1
cout<<"Enter your array size:"; //cost=1 no of times=1
cout<<"Enter your array elements: "; //cost=1 no of times=1
for(i=0;i<n;i++) // cost=2 no of times=n+1
for(i=0;i<n;i++) = cost=2 no of times=n+1
{
sum+=myarr[i]; // cost=2 no of times=n
product*=myarr[i]; // cost=2 no of times=n
}
cout<<"\n The sum of arry element is :"<<sum; // cost=1 no of times=1
cout<<"\n The product of arry element is :"<<product; // cost=1 no of times=1

Therefore the total cost to perform sum operation

Tsum=1 +1+1+ 2 * (n+1) + 2 * n + 1 +2n+2n+1+1= 8n+9= O(n)

Therefore, the time complexity of the above code is O(n)

Time complexity of this code is printed the following enter array size , enter array elements, the
sum of array element and the product of array element is 8n+9 on the screen. As the value of n
can change so time complexity is linear 0(n).

You might also like