Challenge question 2: Consider the following two C++ program segments being run
ID: 3877589 • Letter: C
Question
Challenge question 2:
Consider the following two C++ program segments being run on a computer with virtual memory that has a small amount of real memory. Note the only difference in the two segments is that the loops in segment I change variable i first then j while segment 2 changes j first then i.
int A [1024] [1024];
int B, i, j;
/ * segment 1 * /
B = 0;
for (i =1; i < 1024; i++)
for (j=1; j<1024; j++)
B = B + A[ i ][ j ];
/ * segment 2 * /
for ( j =1; j < 1024; j++)
for ( i =1; i <1024; i++)
B = B + A[ i ][ j ];
Will one segment take longer to run than the other? Explain why or why not.
Explanation / Answer
Both segments will take the same time because in both segments we are looping through same number of iterations, adding to the number. Changing i, j positions will not matter what i feel. But values will come different way
for example
In first segment i, j values will come like
1,1 1,1 1,2 1, 3 ..... 1023, 1023
In second segment i,j values will be like
1,1 2,1 3,1 4,1 5,1 ...... 1022,1023 1023,1023
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.