a. Consider the following algorithm segment: for i := 1 to 4, for j := 1 to i, [Statements in body of inner loop. None contain branching statements that lead outside the loop.] next j, next i. How many times will the inner loop be iterated when the algorithm is implemented and run?
b. Let n be a positive integer, and consider the following algorithm segment: for i := 1 to n, for j := 1 to i, [Statements in body of inner loop. None contain branching statements that lead outside the loop.], next j, next i. How many times will the inner loop be iterated when the algorithm is implemented and run?

Respuesta :

Answer:

(a) 4i times

(b) "i × n" times

Step-by-step explanation:

(a) Given the algorithm segment;

       for i := 1 to 4,  (Outer loop)

            for j := 1 to i   (Inner loop)

            next j,

       next i

The inner loop runs for i times, while the outer loop runs for 4 times.

The total times the inner loop would run when the entire algorithm is run is:

      = i × 4

      = 4i times

(b) Given the algorithm segment;

     for i := 1 to n,  (Outer loop)

            for j := 1 to i   (Inner loop)

            next j,

      next i

Where n is a set of positive integers.

The inner loop runs for "i" times, while the outer loop runs for "n" times.

The total times the inner loop would run when the entire algorithm is run is:

      = i × n

      = "i × n" times