190 views
3 votes
3 votes

Consider the following C function and an input array to it as $[1, 4, 10, 12]$ and len as $4.$ The return value of the function will be

int foo(int arr[], int len) {
    int result = 0;
    for (int i = 0; i < len; i++) {
        result += arr[i] * (i + 1) * (len - i);
    }
    return result;
}

 

2 Answers

4 votes
4 votes

Given that, $arr[0]  = 1,arr[1]  = 4,arr[2]  = 10,arr[3]  = 12,$ and len $ = 4$

Initially, the value of $\text{result} = 0$

  • When $i = 0\;\mid\; \text{result = result} + arr[0] \ast (0+1) \ast (4-0) = 0 + 1\ast 1 \ast 4 = 4$
  • When $i = 1\;\mid\; \text{result = result} + arr[1] \ast (1+1) \ast (4-1) = 4 + 4\ast 2 \ast 3 = 28$
  • When $i = 2\;\mid\; \text{result = result} + arr[2] \ast (2+1) \ast (4-2) = 28 + 10 \ast 3 \ast 2 = 88$
  • When $i = 3\;\mid\; \text{result = result} + arr[3] \ast (3+1) \ast (4-1) = 88 + 12\ast 4 \ast 1 = 136$

So, the correct answer is $136.$ 

2 votes
2 votes
The function is doing the sum of all subarrays of the given array. We have the following subarrays:

$1\;4\;10\;12$

$1\;4\;10$

$4\;10\;12$

$1\;4$

$4\;10$

$10\;12$

$1$

$4$

$10$

$12$

Adding their sum gives $136.$
Answer:

Related questions

3 votes
3 votes
2 answers
1
gatecse asked Aug 18, 2020
159 views
Consider a min heap implemented as an array with the elements $1,2,3,6,7,8,9,10.$ The level (starting from 1) in which $7$ is stored is _______
3 votes
3 votes
2 answers
2
gatecse asked Aug 18, 2020
145 views
Consider the binary tree shown below, which is an almost max-heap with the node $22$ violating the max-heap property. Once heapify procedure is applied to it, which posit...
4 votes
4 votes
1 answer
3
gatecse asked Aug 18, 2020
638 views
In a hashtable with $20$ slots $30$ records are inserted with collisions being resolved by chaining. What is the expected number of key comparisons in an unsuccessful sea...