0

I don't understand why the running time of the following loop is n+2 ? Also why the running time of the statements inside the loop is n+1 ?

Double test(int n){  
      int sum=0;  -> 1 time
      int i;  -> 0 time
      for(i=0; i<=n;i++)  -> n+2 times
      {
        scanf("%d",&a);  -> n+1 times
        sum=sum+a;  -> n+1 times
      }
      return sum;  -> 1 time
    }
  • Use paper & pencil and walk through this by hand for n = 3. You'll probably see the answer. – Dan Pichelman Nov 20 '14 at 2:21
2

The body of loop you've written is entered n+1 times (i from 0 to n), after that the variable i is incremented again, it's value now becomes n+1. Then it is compared to n ( i <= n ), this test fails and the body of the loop is skipped.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.