Computer Applications
Convert the following for loop segment to an exit-controlled loop.
for (int x = 1, y = 2; x < 11; x += 2, y += 2) {
System.out.println(x + "\t" + y);
}
Answer
int x = 1, y = 2;
do {
System.out.println(x + "\t" + y);
x += 2;
y += 2;
} while (x < 11);
Reason — We need to convert the for loop given in question to a do-while
loop as do-while
is an exit-controlled loop whereas for
and while
are entry-controlled loop.
1. Initialization:
- The variables
x
andy
are initialized before thedo-while
loop:int x = 1, y = 2;
.
2. Loop Body:
- The statements inside the
for
loop are moved into the body of thedo
block:
System.out.println(x + "\t" + y);
x += 2;
y += 2;
3. Condition Check:
- The condition
x < 11
is evaluated after executing the loop body, ensuring the loop is exit-controlled.
Related Questions
How many times will the following loop execute? Write the output of the code:
int x=10; while (true){ System.out.println(x++ * 2); if(x%3==0) break; }
Define a class to accept a number from user and check if it is an EvenPal number or not.
(The number is said to be EvenPal number when number is palindrome number (a number is palindrome if it is equal to its reverse) and sum of its digits is an even number.)
Example: 121 – is a palindrome number
Sum of the digits – 1+2+1 = 4 which is an even numberGive the output of following code and mention how many times the loop will execute?
int i; for( i=5; i>=1; i--) { if(i%2 == 1) continue; System.out.print(i+" "); }
Write a program in Java to find the Fibonacci series within a range entered by the user.
Sample Input:
Enter the minimum value: 10
Enter the maximum value: 20Sample Output:
13