How many iterations will this code segment make How many com
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.
