How many iterations will this code segment make How many com

How many iterations will this code segment make? How many comparisons are made during the execution of this code segment? What would the code segment output? Rewrite the for-loop in the code segment without the use of the if-statement so that the output remains the same? How many iterations will the revised version of the code segment make? How many comparisons will the revised version of the code segment make? Is the revised version more efficient than the original? Why or why not? Given an integer n, write a loop that generates the following alternating series.1-2 + 3- 4 + 5- 6.+ 7... n

Solution

GIVEN CODE SNIPPET:

    int i = 2;
       System.out.printf(\"{%d \", i);
       for(i = 4;i < 10;i++)
       {
       if( i % 2 == 0)
           System.out.printf(\" ,%d\",i);
       }
       System.out.println(\"}\");

OUTPUT:

a) Number of iterations made by the code snippet/segment: The for loop starts with initial value 4 and the value of i gets incremented each time the loop is run.SO for lop will have 6 iterations(from 4 to 9). As soon as value of i is incremented when it is 9, it will become 10 and that\'s when loop will exit.

b) The comparison are made inside the if block. It compares the value of i and checks if the remainder comes out to be 0. As tthe loop runs 6 times and the value of i changes six times from being 4 to 9 the comparison is made 6 times.

c) As mentioned above, the output will be :

{2 is printed as a result of the second line of the code and 4,6 and 8 gets printed by the System.out.printf statement used inside the loop after checking for the number is even(divisible by2). The loop runs till 9 so no number after 8 will be printed.

 How many iterations will this code segment make? How many comparisons are made during the execution of this code segment? What would the code segment output? R

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site