The following algorithm adds all the entries in a square n × n array A. Analyze this algorithm where the work unit is the addition operation. sum = 0 for i = 1 to n do for j = 1 to n do sum = sum + A[i, j] end for end for write (“Total of all array elements is”, sum)
Algorithm :
for i = 1 to n do
for j = 1 to n do
sum = sum + A[ i , j ]
end for
end for
write("Total of all upper triangular array elements is", sum)
Ananlysis :
This algorithm find the sum of a 2D matrix of size n x n . It iterate over each row by outer loop and each elemnt of that row by inner loop. It initialize sum by zero and add each element of the matrix into sum. and then print the sum.
Time complexity : O(n2) as it iterate over nested loop of n x n.
Space complexity : O(n2) as it store n x n element into 2D array.
Hope you like it
Any Query? Comment Down!
I have written for you, Please upvote the answer as it encourage us to serve you Best !
Get Answers For Free
Most questions answered within 1 hours.