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
A tech number has even number of digits. If the number is split in two equal halves, then the square of sum of these halves is equal to the number itself. Write a program to generate and print all four digits tech numbers.
Example:
Consider the number 3025
Square of sum of the halves of 3025 = (30 + 25)2
= (55)2
= 3025 is a tech number.Which of the following are entry controlled loops?
(a) for
(b) while
(c) do..while
(d) switch
- only a
- a and b
- a and c
- c and d
To execute a loop 5 times, which of the following is correct?
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 number