Ok, let's do an analysis step by step.
The first instruction
cin >> n
counts as one operation: 1.
Then the loop
for(i=1;i<=n;i++)
for (j = 1; j <= n; j ++)
A[i][j] = 0;
Let's go from inside out. The j
loop performs n array assignments (A[i][j] = 0
), (n + 1) j <= n
comparisons and n j ++
assignments. It also performs once the assignment j = 1
. So in total this gives: n + (n +1) + n + 1 = 3n + 2.
Then the outer i
loop performs (n + 1) i <= n
comparisons, n i ++
assignments and executes n times the j
loop. It also performs one i = 1
assignment. This results in: n + (n + 1) + n * (3n + 2) + 1 = 3n^2 + 4n + 2.
Finally the last for loop performs n array assignments, (n + 1) i <= n
comparisons and n i ++
assignments. It also performs one assignment i = 1
. This results in: n + (n + 1) + n + 1 = 3n + 2.
Now, adding up three operations we get:
(1) + (3n^2 + 4n + 2) + (3n + 2) = 3n^2 + 7n + 5 = T(n) total operations.
The time function is equivalent, assuming that assignments, comparisons, additions and cin
are all done in constant time. That would yield an algorithm of complexity O(n^2).
This is of curse assuming that n >= 1.