14.
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
(C Question) Loop**
How many times 'MATLAB' will be printed in the following C code?
#include <stdio.h>
int main()
{
int i = 1024;
for (; i; i >>= 1)
printf("MATLAB");
return 0;
}
Pick ONE option
Show answer & explanation
Answer: B. 11
The loop continues while i is non-zero. The right shift operator >>= divides i by 2 in each iteration. Starting from 1024 (2^10), we get: 1024 → 512 → 256 → 128 → 64 → 32 → 16 → 8 → 4 → 2 → 1 → 0, which is 11 iterations total before i becomes 0 and the loop terminates.
Step-by-step Derivation:
Trace the loop iterations:
- i = 1024 (binary: 10000000000), condition true, print MATLAB, i >>= 1 → 512
- i = 512 (binary: 1000000000), condition true, print MATLAB, i >>= 1 → 256
- i = 256 (binary: 100000000), condition true, print MATLAB, i >>= 1 → 128
- i = 128 (binary: 10000000), condition true, print MATLAB, i >>= 1 → 64
- i = 64 (binary: 1000000), condition true, print MATLAB, i >>= 1 → 32
- i = 32 (binary: 100000), condition true, print MATLAB, i >>= 1 → 16
- i = 16 (binary: 10000), condition true, print MATLAB, i >>= 1 → 8
- i = 8 (binary: 1000), condition true, print MATLAB, i >>= 1 → 4
- i = 4 (binary: 100), condition true, print MATLAB, i >>= 1 → 2
- i = 2 (binary: 10), condition true, print MATLAB, i >>= 1 → 1
- i = 1 (binary: 1), condition true, print MATLAB, i >>= 1 → 0
- i = 0, condition false, loop exits
Total iterations: 11