For each sample of code given below, indicate precisely how many times each line
ID: 3843582 • Letter: F
Question
For each sample of code given below, indicate precisely how many times each line runs in terms of the variables given. 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. Providing a detailed explanation would be greatly appreciated.
Q3.
for (int i=0; i<n; i++) {
for (int j=n; j>=i; j--)
cout << i << “,” << j <<endl;
}
Q4.
for (int i=0; i<n; i++) { //assume n is divisible by 2 => n = 2*k
for (j=n/2; j>i; j--)
sum = i+j;
}
Explanation / Answer
Q3
for (int i=0; i<n; i++) { =-======> Runs n times
for (int j=n; j>=i; j--)=======> Runs n, n-1, n-2....1
cout << i << “,” << j <<endl;
}
Inner loops runs: 1+ +2+3...+n-2+n-2 = n(n-1)/2 .
Q4.
for (int i=0; i<n; i++) { //assume n is divisible by 2 => n = 2*k ==========> Runs N times
for (j=n/2; j>i; j--)==========> Runs N/2 , N/2-1 , N/2- 2 , N/2-3 .........1
sum = i+j;
}
Total runs : n/2 + n/2 -1 + n/2-2+ .... + 1
=> n(n-1)/4
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.