Iterative Consturcts in Java
Iterative Consturcts in Java
Question 1
1. initialisation
2. test condition
3. update expression
4. All of these
Answer
All of these
Reason — A for loop can also be written as for( ; ; ) within the program code.
Question 2
1. while
2. for
3. do-while
4. None of these
Answer
do-while
Reason — do-while is an exit controlled loop and the test condition is checked at the end of
the loop. Hence, it always executes at least once.
Question 3
1. while
2. do-while
3. for
4. None of these
Answer
do-while
Reason — do-while is an exit-controlled loop as the test condition is checked at the end of
the loop.
Question 4
1. repeat
2. for
3. do-while
4. while
Answer
repeat
Question 5
1. continue
2. jump
3. break
4. terminate
Answer
break
Question 6
Answer
Reason — The statement for(i = 0; i < 5; i++); has a semicolon at its end. Thus, any
statement following it will be treated as outside the for loop.
Question 7
Answer
jump
Question 8
1. 0
2. 1
3. 5
4. 4
Answer
Reason — Since for loop has a semicolon at its end, the block following the loop will be
executed after the for loop is terminated. Thus, Java will be printed only once.
Question 9
1. 15
2. 21
3. 5
4. 0
Answer
Reason — The last value of i for which the condition i <= 5 will be true is 5. Thus, 5 will
be assigned to sum after which the condition will become false and the loop will terminate.
Thus, 5 will be printed as output.
Question 10
1. 5
2. 0
3. 15
4. Infinite loop
Answer
Infinite loop
Reason — The initial value of i is 10 and the test condition is i > 5 is true. In the next
iteration, the value of i is incremented by 1 and again the condition is true. Thus, the value
of i will keep on incrementing and the test expression will remain true, creating an infinite
loop.
Question 11
Which of the following for loops will cause the body of the loop to be executed 10 times?
Answer
for (int i = 0; i < 10; i++ )
Reason — The initial value of i is 0 and the test expression i < 10 will remain true till the
value of i becomes 9. So, the body of the loop will be executed till the value of i remains
between 0 to 9, i.e. 10 times.
Question 12
1. 4
2. 5
3. 0
4. 10
Answer
Reason — There is a misprint in the book. The loop executes 9 times. Value of i is printed 4
times inside the loop. The condition if (i++ % 2 == 0) will be false when i is odd
and true when i is even. Value of i will be incremented after if check is performed due to
post increment opertor i++. Execution of the loop is summarized in the table below:
Iterations i i++ % 2 Outpu
== 0 Remarks
t
Value of i becomes 2 after if check as i++ increments it after
1st 1 False
the evaluation of i++ % 2 == 0
2nd 2 True 3 i becomes 3 after if check, hence 3 is printed in this iteration
3rd 3 False i becomes 4.
4th 4 True 5 i becomes 5.
5th 5 False i becomes 6.
6th 6 True 7 i becomes 7.
7th 7 False i becomes 8.
8th 8 True 9 i becomes 9.
9th 9 False i becomes 10.
As value of i is now 10, the test condition of while loop becomes false hence, 10th iteration
of the loop is not executed.
State whether the given statements are True or False
Question 1
Question 2
Question 3
Question 4
All types of loops in Java (for, while, and do-while) can be infinite loops.
True
Question 5
The continue statement terminates the current loop and then continues from the statement
immediately following the current loop.
False
Question 6
Question 7
Question 8
Question 9
The do-while loop executes at least once even if the condition is false.
True
Question 10
Question 11
Question 12
The statements that facilitate unconditional transfer of control are called jump statements.
True
Assignment questions
Question 1
What are loop control structures? What are the essential segments of a loop control structure?
Answer
A loop is a set of instructions that is continually repeated until a certain condition is met.
Looping control structures refer to certain looping constructs which execute a block of code
repeatedly until a certain condition remains true. For example, for loop, while loop, do -
while loop etc.
1. Initialisation — This segment initialises the loop control variable before starting the
loop. It is executed only once at the beginning of the loop.
For example, int counter = 1;
2. Test-condition — The test-condition is the expression that is evaluated at the
beginning of each iteration. Its value determines whether the body of the loop is to be
executed (test condition is true) or the loop is to be terminated (test condition is false).
For example, counter <= 10
3. Update — This is the increment or decrement operation of the control variable. This
operation is performed at the end of each iteration.
For example, counter++;
Question 2
iii. System.exit(0)
iv. return
Answer
(i) The break statement terminates the current loop or switch statement. The execution then
continues from the statement immediately following the current loop or switch statement.
(ii) The continue statement tells the computer to skip the rest of the current iteration of the
loop. However, instead of jumping out of the loop completely like break statement, it jumps
back to the beginning of the loop and continues with the next iteration. This includes the
evaluation of the loop controlling condition to check whether any further iterations are
required.
(iii) Unlike break and continue statements which are used to control the flow of
execution, System.exit(0) command terminates the execution of the program by stopping the
Java Virtual Machine which is executing the program. It is generally used when due to some
reason it is not possible to continue with the execution of the program.
(iv) A return statement is used to end the execution of a method and return a value to the
calling method, optionally.
Question 3(i)
The test expression i > 0 will always remain true and hence, the for loop will become an
infinite loop and keep on iterating.
Question 3(ii)
The test expression x < 1 && x > 50 will never be true as the conditions x < 1 and x >
50 cannot be true at the same time. Thus, the && operator will always result in false.
Question 3(iii)
while (x == y)
{
xx = yy;
x = y;
}
Answer
The test expression x == y will always remain true as in each iteration x = y is executed,
which will store the value of y in x. Thus, an infinite loop will be generated.
Question 4
Answer
Empty statement consists only of a semicolon ;. It is useful when we want to make a loop an
empty loop.
To make a for loop an empty loop, we write the following code:
Question 5
Convert the following for loop statement into the corresponding while loop and do-while
loop:
int sum = 0;
for (int i = 0; i <= 50; i++)
sum = sum + i;
Answer
while loop
int sum = 0, i = 0;
while (i <= 50) {
sum = sum + i;
i++;
}
do-while loop
int sum = 0, i = 0;
do {
sum = sum + i;
i++;
} while(i <= 50);
Question 6
What are the differences between while loop and do-while loop?
Answer
do-while loop checks the test condition at the end while loop checks the test condition at the beginning
of the loop. of the loop.
do-while loop is suitable when we need to display while loop is helpful in situations where number of
a menu to the user. iterations is not known.
Question 7(i)
How many times are the following loop bodies repeated? What is the final output in each
case?
int x = 2;
while (x < 20)
if (x % 2 == 0)
System.out.println(x);
Answer
Output
2
2
2
2
2
.
.
.
.
Explanation
The value of x is 2. The test condition of while loop — x < 20 is true and the test condition
of if — x % 2 == 0 is also true. So the loop prints the value of x i.e., 2 for the first time.
In the absence of update expression, the while loop continues infinitely and keeps on
printing 2 on the output screen.
Question 7(ii)
How many times are the following loop bodies repeated? What is the final output in each
case?
int y = 2;
while (y < 20)
if (y % 2 == 0)
System.out.println(y++);
Answer
Output
Explanation
The value of y is 2. The test condition of while loop — y < 20 is true and the test condition
of if — y % 2 == 0 is also true. So the loop prints the value of y i.e., 2 for the first time and
then the postfix operator increments it to 3.
In the next iteration, the test condition y < 20 is true but the condition of if — y % 2 ==
0 is false. Thus, there is no updation in the value of y and y remains less than 20. This
creates an infinite loop.
Question 7(iii)
How many times are the following loop bodies repeated? What is the final output in each
case?
int z = 2;
while (z < 20)
if ((z++) % 2 == 0)
System.out.println(z);
Answer
Output
3
5
7
9
11
13
15
17
19
Explanation
The loop executes 18 times. Value of z is printed 9 times inside the loop. The
condition if((z++) % 2 == 0) will be false when z is odd and true when z is even. Value
of z will be incremented after if check is performed due to post increment operator z++.
Execution of the loop is summarized in the table below:
(z++) % Outpu
Iterations z Remarks
2 == 0 t
Question 8
int n = 20;
do {
System.out.println(n);
n = n - 3;
} while (n > 0);
Answer
Output
20
17
14
11
8
5
2
Explanation
The initial value of n is 20. Every time the do-while loop is executed, n decreases by 3.
Execution of the loop is summarized in the table below:
Iteration n Output Test Condition Remarks
n > 0
Question 9
Output
18
16
14
12
10
8
6
Finished
Explanation
The initial value of num is 20. Every time the while loop is executed, num decreases by 2.
Execution of the loop is summarized in the table below:
Iteration num Test Condition Output Remarks
num > 0
Question 10
Output
8
6
4
0
Finished
Explanation
The initial value of num is 10. Every time the while loop is executed, num decreases by 2.
Execution of the loop is summarized in the table below:
nu Test
Iteration Outpu
m Condition Remarks
t
num > 0
Question 11
import java.util.Scanner;
}
}
Output
Question 12
Write a program using do-while loop to compute the sum of the first 500 positive odd
integers.
Output
Question 13
Write three different programs using for, while, and do-while loops to find the product of
series 3, 9, 12,... 30.
Output
Output
public class KBoatSeries
{
public static void main(String args[]) {
long pro = 1;
int num = 3, t = 1;
do {
pro *= num;
if(t % 2 == 0)
num += 3;
else
num += 6;
t++;
} while(num <= 30);
Output
Question 14
Write a program to convert kilograms to pounds in the following tabular format (1 kilogram
is 2.2 pounds):
Kilograms Pounds
1 2.2
2 4.4
20 44.0
Output
Question 15
Write a program that displays all the numbers from 150 to 250 that are divisible by 5 or 6, but
not both.
public class KboatFactorCheck
{
public static void main(String args[]) {
if ((mod5 == 0 || mod6 == 0)
&& !(mod5 == 0 && mod6 == 0)) {
System.out.println(i);
}
}
}
}
Output
Question 16
Write a program in Java to read a number and display its digits in the reverse order. For
example, if the input number is 2468, then the output should be 8642.
Output:
Enter a number: 2468
Original number: 2468
Reverse number: 8642
import java.util.Scanner;
while(copyNum != 0) {
int digit = copyNum % 10;
copyNum /= 10;
revNum = revNum * 10 + digit;
}
Output
Question 17
Write a program in Java to read a number, remove all zeros from it, and display the new
number. For example,
import java.util.Scanner;
while (n != 0) {
int d = n % 10;
if (d != 0) {
newNum += (int)(d * Math.pow(10, idx));
idx++;
}
n /= 10;
}
Output
Question 18
Write a program to read the number n using the Scanner class and print the Tribonacci series:
0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81 ...and so on.
Hint: The Tribonacci series is a generalisation of the Fibonacci sequence where each term is
the sum of the three preceding terms.
import java.util.Scanner;
if(n < 3)
System.out.print("Enter a number greater than 2");
else {
int a = 0, b = 0, c = 1;
System.out.print(a + " " + b + " " + c);
Output
Question 19
Write a program to calculate the value of Pi with the help of the following series:
Pi = (4/1) - (4/3) + (4/5) - (4/7) + (4/9) - (4/11) + (4/13) - (4/15) ...
Hint: Use while loop with 100000 iterations.
}
}
Output
Question 20
Write a program to display the following patterns as per the user's choice.
Pattern 1
I
C
S
E
Pattern 2
I
C
S
E
import java.util.Scanner;
case 2:
for (int i = len - 1; i >= 0; i--) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
System.out.println(str.charAt(len - 1 -
i));
}
break;
default:
System.out.println("Incorrect choice");
break;
}
}
}
Output
Question 21
Write a menu-driven program to display the pattern as the per user's choice:
Pattern 1
ABCDE
ABCD
ABC
AB
A
Pattern 2
B
LL
UUU
EEEE
For an incorrect option, an appropriate error message should be displayed.
import java.util.Scanner;
case 2:
String word = "BLUE";
int len = word.length();
for(int i = 0; i < len; i++) {
for(int j = 0; j <= i; j++) {
System.out.print(word.charAt(i));
}
System.out.println();
}
break;
default:
System.out.println("Incorrect choice");
break;
}
}
}
Output
Question 22
Write a program to input a number and check and print whether it is a Pronic number or not.
(Pronic number is a number which is the product of two consecutive integers.)
Example: 12 = 3 x 4
20 = 4 x 5
42 = 6 x 7
import java.util.Scanner;
if (isPronic)
System.out.println(num + " is a pronic number");
else
System.out.println(num + " is not a pronic
number");
}
}
Output
Question 23
Write a program to accept a number and check and display whether it is a spy number or not.
(A number is called a spy number if the sum of its digits equals the product of the digits.)
Example:
Consider the number 1124.
Sum of the digits = 1 + 1 + 2 + 4 = 8.
Product of the digits = 1 * 1 * 2 * 4 = 8.
Refer to Program 9.44 for the solution.
import java.util.Scanner;
public class KboatSpyNumber
{
public static void main(String args[]) {
sum += digit;
prod *= digit;
num /= 10;
}
if (sum == prod)
System.out.println(orgNum + " is Spy Number");
else
System.out.println(orgNum + " is not Spy Number");
}
}
Output
Question 24
Write a program to accept a number and check and display whether it is a Niven number or
not. (Niven number number which is divisible by the sum of its digits).
Example:
Consider the number 126.
Sum of its digits is 1 + 2 + 6 = 9 and 126 is divisible by 9. Refer to Program 9.45 for the
solution.
import java.util.Scanner;
int digitSum = 0;
while (num != 0) {
int digit = num % 10;
num /= 10;
digitSum += digit;
}
/*
* digitSum != 0 check prevents
* division by zero error for the
* case when users gives the number
* 0 as input
*/
if (digitSum != 0 && orgNum % digitSum == 0)
System.out.println(orgNum + " is a Niven number");
else
System.out.println(orgNum + " is not a Niven
number");
}
}
Output
Question 25
1. Generate and display the first 10 terms of the Fibonacci series 0, 1, 1, 2, 3, 5.... The
first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of
the previous two.
2. Find the sum of the digits of an integer that is input.
Sample Input: 15390
Sample Output: Sum of the digits = 18
For an incorrect choice, an appropriate error message should be displayed.
import java.util.Scanner;
switch (ch) {
case 1:
int a = 0, b = 1;
System.out.print(a + " " + b);
/*
* i is starting from 3 below
* instead of 1 because we have
* already printed 2 terms of
* the series. The for loop will
* print the series from third
* term onwards.
*/
for (int i = 3; i <= 10; i++) {
int term = a + b;
System.out.print(" " + term);
a = b;
b = term;
}
break;
case 2:
System.out.print("Enter number: ");
int num = in.nextInt();
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
System.out.println("Sum of Digits " + " = " +
sum);
break;
default:
System.out.println("Incorrect choice");
break;
}
}
}
Output
Question 26
Write a menu driven program to accept a number and check and display whether (i) it is a
Prime Number or not (ii) it is an Automorphic Number or not. (Use switch-case statement).
import java.util.Scanner;
switch (choice) {
case 1:
int c = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
c++;
}
}
if (c == 2)
System.out.println(num + " is Prime");
else
System.out.println(num + " is not Prime");
break;
case 2:
int numCopy = num;
int sq = num * num;
int d = 0;
/*
* Count the number of
* digits in num
*/
while(num > 0) {
d++;
num /= 10;
}
/*
* Extract the last d digits
* from square of num
*/
int ld = (int)(sq % Math.pow(10, d));
if (ld == numCopy)
System.out.println(numCopy + " is
automorphic");
else
System.out.println(numCopy + " is not
automorphic");
break;
default:
System.out.println("Incorrect Choice");
break;
}
}
}
Output
Question 27
Write a menu driven program to accept a number from the user and check whether it is a
BUZZ number or to accept any two numbers and to print the GCD of them.
import java.util.Scanner;
public class KboatBuzzGCD
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Buzz number");
System.out.println("2. Calculate GCD");
System.out.print("Enter your choice: ");
int choice = in.nextInt();
switch (choice) {
case 1:
System.out.print("Enter a number: ");
int num = in.nextInt();
if (num % 10 == 7 || num % 7 == 0)
System.out.println(num + " is a Buzz
Number");
else
System.out.println(num + " is not a Buzz
Number");
break;
case 2:
System.out.print("Enter first number: ");
int a = in.nextInt();
System.out.print("Enter second number: ");
int b = in.nextInt();
while (b != 0) {
int t = b;
b = a % b;
a = t;
}
System.out.println("GCD = " + a);
break;
default:
System.out.println("Incorrect Choice");
break;
}
}
}
Output
Question 28
Write a program to read the number x using the Scanner class and compute the series:
Output
Question 29
Write a program in Java to compute and display factorial of numbers up to a number entered
via the Scanner class. The output should look like as shown below when 7 is input.
Enter a number: 7
1! (=1) = 1
2! (= 1 x 2) = 2
3! (= 1 x 2 x 3) = 6
4! (= 1 x 2 x 3 x 4) = 24
5! (= 1 x 2 x 3 x 4 x 5) = 120
6! (= 1 x 2 x 3 x 4 x 5 x 6) = 720
7! (= 1 x 2 x 3 x 4 x 5 x 6 x 7) = 5040
import java.util.Scanner;
Output
Question 30(i)
x1 + x2 + x3 + x4 + ..... + xn
import java.util.Scanner;
Output
Question 30(ii)
x1 - x2 + x3 - x4 + ..... - xn , where x = 3
import java.util.Scanner;
Output
Question 30(iii)
1x1+2x2+3x3+...+nxnx11+x22+x33+...+xnn
import java.util.Scanner;
System.out.println("Sum=" + sum);
}
}
Output
Question 30(iv)
12+23+34+...+495021+32+43+...+5049
import java.util.Scanner;
Output
Question 30(v)
11+22+33+...+101011+22+33+...+1010
public class KboatSeries
{
public static void main(String args[]) {
double sum = 0;
for (int i = 1; i <= 10; i++)
sum += i / Math.sqrt(i);
System.out.println("Sum = " + sum);
}
}
Output
Question 30(vi)
double sum = 0;
for (int i = 1, j = 3; i <= n; i++, j += 2) {
sum += (x + i) / (double)j;
}
System.out.println("Sum = " + sum);
}
}
Output
Question 30(vii)
x2!+x3!+x4!+...+x20!2!x+3!x+4!x+...+20!x
import java.util.Scanner;
}
}
Output
Question 30(viii)
x22!+x33!+x44!+...+xnn!,where n = 102!x2+3!x3+4!x4+...+n!xn,where n =
10
import java.util.Scanner;
}
}
Output
Question 30(ix)
1 + 3 + 7 + 15 + 31 + ..... + (220 - 1)
double sum = 0;
}
}
Output
Question 30(x)
1 * 2 * 4 * 8 * ..... * 220
double sum = 0;
}
}
Output
Question 31
Write a menu driven class to accept a number from the user and check whether it is
Palindrome or a Perfect number.
import java.util.Scanner;
switch (choice) {
case 1:
int copyNum = num;
int revNum = 0;
while(copyNum != 0) {
int digit = copyNum % 10;
copyNum /= 10;
revNum = revNum * 10 + digit;
}
if (revNum == num)
System.out.println(num + " is palindrome");
else
System.out.println(num + " is not
palindrome");
break;
case 2:
int sum = 0;
if (num == sum)
System.out.println(num + " is a perfect
number");
else
System.out.println(num + " is not a perfect
number");
break;
default:
System.out.println("Incorrect Choice");
break;
}
}
}
Output
Question 32
Write a program to print the sum of negative numbers, sum of positive even numbers and
sum of positive odd numbers from a list of n numbers entered by the user. The program
terminates when the user enters a zero.
import java.util.Scanner;
if (n == 0) {
break;
}
if (n < 0) {
nSum += n;
}
else if (n % 2 == 0) {
eSum += n;
}
else {
oSum += n;
}
}
Output