ProgrammingHard
How many times does cnt++ run in: for (i = 0; i < 10; i++) for (j = i; j < 10; j++) cnt++; ?
- A. 55
- B. 45
- C. 100
- D. 50
Correct answer: A. 55
The inner loop runs 10 + 9 + ... + 1 times, which is 10 x 11 / 2 = 55. Starting j at i halves the work compared with the full square.
More C Programming questions
- How many iterations does for (i = 1; i < 1024; i = 2) do?
- A binary search over n = 10^6 sorted records, in the worst case, takes how many loop iterations?
- A sieve of Eratosthenes up to n = 100 marks composites by starting each prime p at pp, and only for pp <= n. How many marking operations…
- With fib(1) = fib(2) = 1, what is the largest n for which fib(n) fits in a signed 64-bit long long?
- A loop appends one character to a string with strcat(s, "x") for n = 10^5 times. Each strcat calls strlen on the whole string first. What…
- for (i = 0; i < strlen(s); i++) process(s[i]); with a string of length 5. How many times is strlen called?