I want to ask a question about time complexity.
Sum (array,n)
{
1.1 total_sum = 0;
1.2 for (i=0;i<n;i++)
1.2.1 total_sum = total_sum +array[i];
1.3 return total_sum;
}
the total steps for 1.2 statement is 2(n+1)..
could anyone tell me that why it is 2(n+1) ?
Say, i=n-1. It gets incremented, and the loop returns; one more comparison is made, this time it evaluates to false (because i is now equal to n). All in all, you run this 0, 1, … ,n times, each time doing two operations — together 2(n+1). Note that the i++ statement is evaluated only n times, but you have one extra statement at the beginning of the loop (i=0).