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);
}
Java Iterative Stmts
1 Like
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
xandyare initialized before thedo-whileloop:int x = 1, y = 2;.
2. Loop Body:
- The statements inside the
forloop are moved into the body of thedoblock:
System.out.println(x + "\t" + y);
x += 2;
y += 2;
3. Condition Check:
- The condition
x < 11is evaluated after executing the loop body, ensuring the loop is exit-controlled.
Answered By
1 Like
Related Questions
Rewrite the following do while program segment using for:
x = 10; y = 20; do { x++; y++; } while (x<=20); System.out.println(x * y );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:
13Define a class to accept a number and check whether it is a SUPERSPY number or not. A number is called SUPERSPY if the sum of the digits equals the number of the digits.
Example1:
Input: 1021 output: SUPERSPY number [SUM OF THE DIGITS = 1+0+2+1 = 4, NUMBER OF DIGITS = 4 ]Example2:
Input: 125 output: Not an SUPERSPY number [1+2+5 is not equal to 3]