Dee Khan
Dee Khan

Reputation: 83

Running time calculation example

I was going through the examples of Big Oh to calculate Running time calculation from Data Structures and Algorithm Analysis using C by mark Weiss.

The example is:

int sum(int N)
/*1*/ int sum=0;
/*2*/ for (int i=1;i<=N;i++)
/*3*/      sum=sum+i*i*i;
/*4*/      return sum;

I understand the cost for each line, but I have confusion for the line no 2, that in line 2 there are three things, initialization, testing and increment. so the total cost for initialization is 1 and for testing (n+1) and n for all the increment. I want to know that how for testing the cost is n+1 because from the condition, the loop will run n time then how the cost will be n+1?

Upvotes: 2

Views: 749

Answers (1)

Aadnan Farooq A
Aadnan Farooq A

Reputation: 646

Let's say n=5. The condition will run 6 times and for 6th time the condition will not be true so n+1 testing.

Upvotes: 1

Related Questions