7.
Texas Instruments technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Invoking the print statement © 0 Previous Aptitude How many times is the statement print(i,j) invoked in the following code snippet? Submitted for (i=1; i <= n-1; i++) Software for (j=i+1; j <= n; j++) print(i,j) IE Je o:> 10 - A) n2 times - B) n2 -n times - C) (n’2 - n)/2 times *2/2 times Answer Saved BEB G&G a © G>
Show answer & explanation
The code implements a nested loop structure that iterates through all unique pairs (i, j) where 1 ≤ i < j ≤ n. This is equivalent to calculating the number of combinations of n elements taken 2 at a time, which is n(n-1)/2.
Step-by-step Derivation:
Step 1: Analyze the outer loop: The variable 'i' ranges from 1 to n-1. For each value of 'i', the inner loop executes.
Step 2: Analyze the inner loop: The variable 'j' ranges from i+1 to n. The number of iterations for a fixed 'i' is (n - (i + 1) + 1) = n - i.
Step 3: Sum the iterations for all i: Total = Σ (n - i) for i = 1 to n-1.
Step 4: Expand the summation: (n-1) + (n-2) + (n-3) + ... + (n - (n-1)) = (n-1) + (n-2) + ... + 1.
Step 5: Use the arithmetic series formula Σ k from 1 to m = m(m+1)/2. Here m = n-1.
Step 6: Total = (n-1)((n-1)+1)/2 = (n-1)(n)/2 = (n^2 - n)/2.
Step 7: Match with options: Option C represents (n^2 - n)/2 (noting the typo 'n’2' as n^2).