Consider the following fragment of C++ code, assuming that the constructor Seque
ID: 3761686 • Letter: C
Question
Consider the following fragment of C++ code, assuming that the constructor Sequence creates an empty sequence of integer objects. Recall that division between integers performs truncation (for example, 7/2 = 3). Sequence seq; for (int i = 0; i < n; i++) seq.insertAtRank(i/2, i); a. Assume that the for loop is executed 10 times, that is, n = 10, and show the sequence after each iteration of the loop. b. Draw a schematic illustration of the sequence at the end of the for loop, for a generic number n of iterations.
Explanation / Answer
Hi,
Below is the solution to your problem:
a.
Consider the following code:
Sequence seq;
for (int i = 0; i < n; i++) seq.insertAtRank(i/2, i);
1.Assume that the for loop is executed 10 times, that is, n = 10, and show the sequence after each iteration of the loop.
Solution:If the above for loop is executed 10 times,with n=10,Below is the sequence after each iteration:
I
operation
The Sequence
0
Seq.insertAtRank(1, 0)
(-,0)
1
Seq.insertAtRank(1, 1)
(-,1,0)
2
Seq.insertAtRank(2, 2)
(-,1,2,0)
3
Seq.insertAtRank(2, 3)
(-,1,3,2,0)
4
Seq.insertAtRank(3, 4)
(-,1,3,4,2,0)
5
Seq.insertAtRank(3, 5)
(-,1,3,5,4,2,0)
6
Seq.insertAtRank(4, 6)
(-,1,3,5,6,4,2,0)
7
Seq.insertAtRank(4, 7)
(-,1,3,5,7,6,4,2,0)
8
Seq.insertAtRank(5, 8)
(-,1,3,5,7,8,6,4,2,0)
9
Seq.insertAtRank(5, 9)
(-,1,3,5,7,9,8,6,4,2,0)
2.Draw a schematic illustration of the sequence at the end of the for loop, for a generic number n of iterations.
Solution:In order to prove this lets consider the odd and even case seperately,
When n is odd
(-, 1, 3, …., n-6, n-4, n-2, n , n-1, n-3, n-5, …, 2, 0)
When n is even
(-, 1, 3, …., n-5, n-3, n-1, n, n-2, n-4, n-6, …, 2, 0)
Hope that helps...HAPPY ANSWERING!!!!!!!!
I
operation
The Sequence
0
Seq.insertAtRank(1, 0)
(-,0)
1
Seq.insertAtRank(1, 1)
(-,1,0)
2
Seq.insertAtRank(2, 2)
(-,1,2,0)
3
Seq.insertAtRank(2, 3)
(-,1,3,2,0)
4
Seq.insertAtRank(3, 4)
(-,1,3,4,2,0)
5
Seq.insertAtRank(3, 5)
(-,1,3,5,4,2,0)
6
Seq.insertAtRank(4, 6)
(-,1,3,5,6,4,2,0)
7
Seq.insertAtRank(4, 7)
(-,1,3,5,7,6,4,2,0)
8
Seq.insertAtRank(5, 8)
(-,1,3,5,7,8,6,4,2,0)
9
Seq.insertAtRank(5, 9)
(-,1,3,5,7,9,8,6,4,2,0)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.