0

Number of Operations in an Algorithm

Hi, I am taking a CS class and one exercise asks me to count the number of operations in a given algorithm containing a for loop. Can you explain the number of operations for size = n in the following algorithm please? int funcExercise7(int list[], int size) { int sum = 0 for (int index = 0; index < size, index++) sum = sum + index; return sum; } It seems to me it should be 5n + 3. 1 for "sum =...", 1 for "return...", 1 to check conditions when the loop closes, and 5n per loop. However, the book says it is 4n + 3. I assume I should not be counting one of the operations in the for loop? Can you break this down a bit more for me? Thanks.

28th May 2017, 6:02 PM
Joseph P French
Joseph P French - avatar
2 Réponses
+ 3
Checking index < size per loop, index++ per loop, sum + index per loop, and sum = sum + index per loop should be four. Then sum = 0, index = 0, and return sum should be three. 4n + 3
28th May 2017, 8:23 PM
Zeke Williams
Zeke Williams - avatar
0
Yeah that makes sense. Thank you.
28th May 2017, 8:58 PM
Joseph P French
Joseph P French - avatar