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
2 Likes
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.
Answered By
3 Likes
Related Questions
Give the output of the following program segment. How many times is the loop executed?
for(x=10; x>20;x++) System.out.println(x); System.out.println(x*2);
Define a class to accept a number and check whether it is an FDS Number or not. A number is called an FDS Number if the sum of the factorials of its digits equals the number itself.
Example 1:
Input: 145
Output: FDS Number [1! + 4! + 5! = 1 + 24 + 120 = 145]Example 2:
Input: 123
Output: Not an FDS Number [1! + 2! + 3! = 1 + 2 + 6 ≠ 123]import java.util.Scanner; class KboatFDSNum { static int fact(int d) { int f = 1; _______(1)_________ { _______(2)_________ } _______(3)_________ } public static void main(String args[]) { Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); int num = in.nextInt(); int t = num, sum = 0; _______(4)_________ { _______(5)_________ _______(6)_________ _______(7)_________ } _______(8)_________ { _______(9)_________ } else { _______(10)_________ } } }
How many times will the following loop execute? Write the output of the code:
int a = 5; while (a > 0) { System.out.println(a-- + 2); if (a % 3 == 0) break; }
Write a program to input a number and find whether the number is an emirp number or not. A number is said to be emirp if the original number and the reversed number both are prime numbers.
For example, 17 is an emirp number as 17 and its reverse 71 are both prime numbers.