For each sample of code given below, indicate precisely how many times each line
ID: 3858633 • 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.
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++) // n times
{
for (int j=n; j>=i; j--) // (n(n+3))/2 times
cout << i << “,” << j <<endl; n(n+3))/2 times
}
when i = 0, j loops n+1 times
when i = 1, j loops n times
.
.
.
when i = n-1, j loops 2 time only
thus the nested for loop runs = (n+1 + n + (n-1)/2 + ..... 2)
=> n(n+3)/2 times
Q4.
for (int i=0; i<n; i++) // n times
{ //assume n is divisible by 2 => n = 2*k
for (j=n/2; j>i; j--) // n(n+2)/8 times
sum = i+j;// n(n+2)/8 times
when i = 0, j loops n/2 times
when i = 1, j loops n/2 -1 times
when i = 2, j loops n/2 -2 times
.
.
.
when i = n/2 -1, j loops 1 time only
thus the nested for loop runs = (n/2 + n/2 -1 + ..... 1)
=> n(n+2)/8 times
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.