For each sample of code given below, indicate precisely how many times each line
ID: 3686185 • Letter: F
Question
For each sample of code given below, indicate precisely how many times each line runs in terms of the variables given. Sometimes, you will be able to give an exact integral answer, like "10". Other times, your answer will be in terms of n or some other variable or combination of variables. If the snippet of code is a method, you do not have to write the number of times the top line (the method declaration itself) is executed.
for (int i=0; i<n; i++) //assume n is divisible by 2
for (j=n/2; j>i; j--)
sum = i+j;
Explanation / Answer
1. for (int i=0; i<n; i++) //assume n is divisible by 2
2. for (j=n/2; j>i; j--)
3. sum = i+j;
Line 1: executs n times
Line 2: it will executes for each i=0 to i=n/2, after that condition is false(j > i)
Total number of times:
line 2 will exeutes (n/2-1 + n/2-2, n/2-3, ....,1) times
= n(n-2)/8
Line 3: = n(n-2)/8 , same as line 2 (it is part of line 2 block)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.