KnowledgeBoat Logo
OPEN IN APP

Chapter 9

Iterative Constructs in Java

Class 10 - Logix Kips ICSE Computer Applications with BlueJ



Multiple Choice Questions

Question 1

Which of the following segment can be omitted in a for loop?

  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

Which of the following loop executes at least once?

  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

Which of the following is an exit-controlled loop?

  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

Which of the following is an invalid loop?

  1. repeat
  2. for
  3. do-while
  4. while

Answer

repeat

Reason — repeat is not a loop.

Question 5

Which of the following statement causes complete termination of the loop?

  1. continue
  2. jump
  3. break
  4. terminate

Answer

break

Reason — break statement causes complete termination of the loop.

Question 6

Which of the following is an empty loop?

  1. for(i = 0; i < 5; i++);
  2. while (i < 5) i++;
  3. do {i++;} while (i < 5);
  4. All of these

Answer

for(i = 0; i < 5; i++);

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

Which of the following is not a jump statement in Java?

  1. break
  2. jump
  3. return
  4. continue

Answer

jump

Reason — jump is not a jump statement in Java.

Question 8

How many times will the following code print "Java"?

for (int i = 1; i <= 5; i ++);    
{
    System.out.println("Java");
}  
  1. 0
  2. 1
  3. 5
  4. 4

Answer

1

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

What will be the output of the following code?

public static void main(String args[]) 
{  
    int sum = 0;   
    for (int i = 1; i <= 5; i++)    
    {    
        sum = i;    
    }    
    System.out.println(sum); 
}  
  1. 15
  2. 21
  3. 5
  4. 0

Answer

5

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

How many times will the following loop execute?

public static void main(String args[])
{
    int sum = 0;
    for (int i = 10; i > 5; i++)
    {
        sum += i;    
    }
    System.out.println(sum);
}
  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?

  1. for (int i = 0; i <= 10; i++)
  2. for (int i = 1; i < 10; i++ )
  3. for (int i = 10; i > 1; i-- )
  4. for (int i = 0; i < 10; i++ )

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

How many times will the following loop execute?

public static void main(String args[])
{
    int i = 1;
    while (i < 10)
        if (i++ % 2 == 0)
            System.out.println(i);
}
  1. 4
  2. 5
  3. 0
  4. 10

Answer

Loop executes 9 times

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:

Iterationsii++ % 2 == 0OutputRemarks
1st1False Value of i becomes 2 after if check as i++ increments it after the evaluation of i++ % 2 == 0
2nd2True3i becomes 3 after if check, hence 3 is printed in this iteration.
3rd3False i becomes 4.
4th4True5i becomes 5.
5th5False i becomes 6.
6th6True7i becomes 7.
7th7False i becomes 8.
8th8True9i becomes 9.
9th9False 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

The while loop is an exit-controlled loop.
False

Question 2

To execute a do-while loop, the condition must be true in the beginning.
False

Question 3

The while part of a do-while statement must be terminated by a semicolon.
True

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

The return statement is a jump statement.
True

Question 7

The for loop may contain multiple initialisations and updates.
True

Question 8

A loop that never terminates is called an empty loop.
False

Question 9

The do-while loop executes at least once even if the condition is false.
True

Question 10

The do-while loop is an exit-controlled loop.
True

Question 11

An infinite loop can be constructed using a while loop only.
False

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.

The essential parts of a looping control structure are as follows:

  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

How are these statements different from each other?
i. break

ii. continue

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)

Identify all the errors in the following statements.

for (int i = 5; i > 0; i++)
{
    System.out.println("Java is fun!");
}

Answer

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)

Identify all the errors in the following statements.

while (x < 1 && x > 50)
{
    a = b;
}

Answer

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)

Identify all the errors in the following statements.

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

What is an empty statement? Explain its usefulness.

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:

for (int i = 1 ; i <=10 ; i ++);

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 loopwhile loop
do-while is an exit-controlled loop.while is an entry-controlled loop.
do-while loop checks the test condition at the end of the loop.while loop checks the test condition at the beginning of the loop.
do-while loop executes at least once, even if the test condition is false.while loop executes only if the test condition is true.
do-while loop is suitable when we need to display a menu to the user.while loop is helpful in situations where number of 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

The loop repeats for infinite times.

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

The loop repeats for infinite times.

Output
2
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

The loop repeats for 18 times.

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:

Iterationsz(z++) % 2 == 0OutputRemarks
1st2True3Value of z becomes 3 after if check as z++ increments it after the evaluation of (z++) % 2 == 0. Hence, 3 is printed.
2nd3Falsez becomes 4 after if check
3rd4True5z becomes 5.
4th5Falsez becomes 6.
5th6True7z becomes 7.
6th7Falsez becomes 8.
7th8True9z becomes 9.
8th9Falsez becomes 10.
9th10True11z becomes 11.
10th11Falsez becomes 12.
11th12True13z becomes 13.
12th13Falsez becomes 14.
13th14True15z becomes 15.
14th15Falsez becomes 16.
15th16True17z becomes 17.
16th17Falsez becomes 18.
17th18True19z becomes 19.
18th19Falsez becomes 20.

As value of z is now 20, the test condition of while loop becomes false hence, 19th iteration of the loop is not executed.

Question 8

What is the output produced by the following code?

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:

IterationnOutputTest Condition
n > 0
Remarks
1st2020Truen is initially 20. After updation, it becomes 17 (20 - 3)
2nd1717Truen becomes 14 (17 - 3)
3rd1414Truen becomes 11 (14 - 3)
4th1111Truen becomes 8 (11 - 3)
5th88Truen becomes 5 (8 - 3)
6th55Truen becomes 2 (5 - 3)
7th22Truen becomes -1 (2 - 3)

Since, the condition of while loop becomes false, the loop terminates.

Question 9

What is the output produced by the following code?

int num = 20;
while (num > 0) 
{
    num = num - 2;
    if (num == 4)
        break ;
    System.out.println(num);
}
System.out.println("Finished");

Answer

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:

IterationnumTest Condition
num > 0
OutputRemarks
1st20True18num becomes 18 (20 - 2)
if condition false
2nd18True16num becomes 16 (18 - 2)
if condition false
3rd16True14num becomes 14 (16 - 2)
if condition false
4th14True12num becomes 12 (14 - 2)
if condition false
5th12True10num becomes 10 (12 - 2)
if condition false
6th10True8num becomes 8 (10 - 2)
if condition false
7th8True6num becomes 6 (8 - 2)
if condition false
8th6Truenum becomes 4 (6 - 2)
if condition becomes true, loop terminates.

Since, in 8th iteration num becomes 4, the condition of if statement becomes true. break statement is executed and control jumps out of while loop to the println statement and "Finished" is printed on the screen.

Question 10

What is the output produced by the following code?

int num = 10;
while (num > 0)
{
    num = num - 2;
    if (num == 2)
        continue;   
    System.out.println(num);
}
System.out.println("Finished");

Answer

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:

IterationnumTest Condition
num > 0
OutputRemarks
1st10True8num becomes 8 (10 - 2)
if condition false
2nd8True6num becomes 6 (8 - 2)
if condition false
3rd6True4num becomes 4 (6 - 2)
if condition false
4th4Truenum becomes 2 (4 - 2)
if condition becomes true, Continue statement sends control to next iteration of while loop
5th2True0num becomes 0 (2 - 0)
if condition false

After 5th iteration, num becomes 0 so the loop terminates.

Since, the body of if contains continue statement, when num becomes 2, control ignores the remaining statements in the loop and starts the next iteration of the loop.

Question 11

Write a program to input n number of integers and find out:

i. Number of positive integers

ii. Number of negative integers

iii. Sum of positive numbers

iv. Product of negative numbers

v. Average of positive numbers

import java.util.Scanner;

public class KboatIntegers
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int pSum = 0, pCount = 0, nPro = 1, nCount = 0;
        System.out.println("Enter n:");
        int n = in.nextInt();
        
        System.out.println("Enter " + n + " integers:");
        for (int i = 1; i <= n; i++) {
            int num = in.nextInt();
            if (num >= 0) {
                pSum += num;
                pCount++;
            }
            else {
                nPro *= num;
                nCount++;
            }
        }
        
        double pAvg = pSum/(double)pCount;
        System.out.println("Positive Integers = " + pCount);
        System.out.println("Negative Integers = " + nCount);
        System.out.println("Sum of Positive = " + pSum);
        System.out.println("Product of Negative = " + nPro);
        System.out.println("Average of Positive = " + pAvg); 
        
    }
}
Output
BlueJ output of KboatIntegers.java

Question 12

Write a program using do-while loop to compute the sum of the first 500 positive odd integers.

public class KboatSumOdd
{
    public static void main(String args[]) {
        long sumOdd = 0;  
        int num = 1;
        do  {
            sumOdd += num;
            num += 2;
        }while(num <= 500);
                    
        System.out.println("Sum of 500 odd positive numbers = "
                            + sumOdd);        
    }
}
Output
BlueJ output of KboatSumOdd.java

Question 13

Write three different programs using for, while, and do-while loops to find the product of series 3, 9, 12,... 30.

public class KBoatSeries
{
    public static void main(String args[]) {
        int pro = 1;
        for(int i = 3, t = 1; i <= 30; t++) { 
            pro *= i;
            if(t % 2 == 0)
                i += 3;
            else
                i += 6;
        }
        System.out.println("Product = " + pro);
    }
}
Output
BlueJ output of KBoatSeries.java
public class KBoatSeries
{
    public static void main(String args[]) {
        long pro = 1;  
        int num = 3, t = 1;
        
        while(num <= 30)    {
            pro *= num;
            if(t % 2 == 0)
                num += 3;
            else
                num += 6;
            t++;
        }            
        System.out.println("Product = " + pro);
    }
}
Output
BlueJ output of KBoatSeries.java
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);
                    
        System.out.println("Product = " + pro);
    }
}
Output
BlueJ output of KBoatSeries.java

Question 14

Write a program to convert kilograms to pounds in the following tabular format (1 kilogram is 2.2 pounds):

KilogramsPounds
12.2
24.4
2044.0
public class KboatKiloToPound
{
    public static void main(String args[]) {
        System.out.println("Kilograms \t Pounds");
        for(int i = 1; i <= 20; i++) {
            double p = i * 2.2;
            System.out.println(i + "\t\t" + p);
        }
    }
}
Output
BlueJ output of KboatKiloToPound.java

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[]) {

        for (int i = 150; i <= 250; i++) {
            int mod5 = i % 5;
            int mod6 = i % 6;
            
            if ((mod5 == 0 || mod6 == 0) 
                    && !(mod5 == 0 && mod6 == 0)) {
                System.out.println(i);
            }
        }
    }
}
Output
BlueJ output of KboatFactorCheck.java

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;

public class KboatDigitReverse
{
    public static void main(String args[]) {
        
        Scanner in = new Scanner(System.in);
        System.out.print("Enter Number: ");
        int orgNum = in.nextInt();
        
        int copyNum = orgNum;
        int revNum = 0;
        
        while(copyNum != 0) {
            int digit = copyNum % 10;
            copyNum /= 10;
            revNum = revNum * 10 + digit;
        }
        
        System.out.println("Original Number = " + orgNum);
        System.out.println("Reverse Number = " + revNum);
    }
}
Output
BlueJ output of KboatDigitReverse.java

Question 17

Write a program in Java to read a number, remove all zeros from it, and display the new number. For example,

Sample Input: 45407703
Sample Output: 454773

import java.util.Scanner;

public class KboatRemoveZeros
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: ");
        int num = in.nextInt();
        int idx = 0;
        int newNum = 0;
        int n = num;
        
        while (n != 0) {
            int d = n % 10;
            if (d != 0) {
                newNum += (int)(d * Math.pow(10, idx));
                idx++;
            }
            n /= 10;
        }
        
        System.out.println("Original number = " + num);
        System.out.println("New number = " + newNum);
    }
}
Output
BlueJ output of KboatRemoveZeros.java

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;

public class KboatTribonacci
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter no. of terms : ");
        int n = in.nextInt();
        
        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);
        
            for (int i = 4; i <= n; i++) {
                int term = a + b + c;
                System.out.print(" " + term);
                a = b;
                b = c;
                c = term;
            }
        }
    }
}
Output
BlueJ output of KboatTribonacci.java

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.

public class KboatValOfPi
{
        public static void main(String args[]) {
            double pi = 0.0d, j = 1.0d;
            int i = 1;
            while(i <= 100000)  {
                if(i % 2 == 0)
                    pi -= 4/j;
                else
                    pi += 4/j;
                j += 2;
                i++;
            }
            System.out.println("Pi = " + pi);
        
    }
}
Output
BlueJ output of KboatValOfPi.java

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;

public class KboatMenuPattern
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter 1 for Pattern 1");
        System.out.println("Enter 2 for Pattern 2");
        System.out.print("Enter your choice: ");
        int ch = in.nextInt();
        String str = "ICSE";
        int len = str.length();
        switch (ch) {
            case 1:
                for (int i = 0; i < len; i++) {
                    for (int j = 0; j < i; j++) {
                        System.out.print(" ");
                    }
                    System.out.println(str.charAt(i));
                }
                break;

            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
BlueJ output of KboatMenuPattern.java
BlueJ output of KboatMenuPattern.java

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;

public class KboatMenuPattern
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter 1 for pattern 1");
        System.out.println("Enter 2 for Pattern 2");
        System.out.print("Enter your choice: ");
        int choice = in.nextInt();
        switch (choice) {
            case 1:
            for (int i = 69; i >= 65; i--) {
                for (int j = 65; j <= i; j++) {
                    System.out.print((char)j);
                }
                System.out.println();
            }
            break;

            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
BlueJ output of KboatMenuPattern.java
BlueJ output of KboatMenuPattern.java

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;

public class KboatPronicNumber
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number to check: ");
        int num = in.nextInt();
        
        boolean isPronic = false;
        
        for (int i = 1; i <= num - 1; i++) {
            if (i * (i + 1) == num) {
                isPronic = true;
                break;
            }
        }
        
        if (isPronic)
            System.out.println(num + " is a pronic number");
        else
            System.out.println(num + " is not a pronic number");
    }
}
Output
BlueJ output of KboatPronicNumber.java
BlueJ output of KboatPronicNumber.java

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[]) {
        
        Scanner in = new Scanner(System.in);
        
        System.out.print("Enter Number: ");
        int num = in.nextInt();
        
        int digit, sum = 0;
        int orgNum = num;
        int prod = 1;
        
        while (num > 0) {
            digit = num % 10;
            
            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
BlueJ output of KboatSpyNumber.java
BlueJ output of KboatSpyNumber.java

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;

public class KboatNivenNumber
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: ");
        int num = in.nextInt();
        int orgNum = num;
        
        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
BlueJ output of KboatNivenNumber.java
BlueJ output of KboatNivenNumber.java

Question 25

Using the switch statement, write a menu driven program to:

  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;

public class KboatFibonacciNDigitSum
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("1. Fibonacci Series");
        System.out.println("2. Sum of digits");
        System.out.print("Enter your choice: ");
        int ch = in.nextInt();

        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
BlueJ output of KboatFibonacciNDigitSum.java
BlueJ output of KboatFibonacciNDigitSum.java

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).

  1. Prime number: A number is said to be a prime number if it is divisible only by 1 and itself and not by any other number. Example: 3, 5, 7, 11, 13 etc.
  2. Automorphic number: An automorphic number is the number which is contained in the last digit(s) of its square. Example: 25 is an automorphic number as its square is 625 and 25 is present as the last two digits.
import java.util.Scanner;

public class KboatPrimeAutomorphic
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("1. Prime number");
        System.out.println("2. Automorphic number");
        System.out.print("Enter your choice: ");
        int choice = in.nextInt();
        System.out.print("Enter number: ");
        int num = in.nextInt();

        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
BlueJ output of KboatPrimeAutomorphic.java
BlueJ output of KboatPrimeAutomorphic.java

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.

  1. A BUZZ number is the number which either ends with 7 or is divisible by 7.
  2. GCD (Greatest Common Divisor) of two integers is calculated by continued division method. Divide the larger number by the smaller; the remainder then divides the previous divisor. The process is repeated till the remainder is zero. The divisor then results the GCD.
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
BlueJ output of KboatBuzzGCD.java
BlueJ output of KboatBuzzGCD.java

Question 28

Write a program to read the number x using the Scanner class and compute the series:

Sum = x/2 + x/5 + x/8 + x/11+ ..... + x/20

The output should look like as shown below:

Enter the value of x: 10
Sum of the series is: 10.961611917494269

import java.util.Scanner;

public class KboatSeries
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter x: ");
        int x = in.nextInt();
        double sum = 0.0;
        for (int i = 2; i <= 20; i += 3)
            sum += (double)x / i;
        System.out.println("Sum = " + sum);
    }
}
Output
BlueJ output of KboatSeries.java

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;

public class KboatFactorial
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = in.nextInt();
        
        for (int i = 1; i <= num; i++)  {
            int f = 1;
            System.out.print(i + "! ( = ");
            for (int j = 1; j <= i; j++)    {
                if (j == 1)
                    System.out.print(j);
                else
                    System.out.print(" x " + j);
                f *= j;
            }
            System.out.print(" ) = " + f);
            System.out.println();
        }
    }
}
Output
BlueJ output of KboatFactorial.java

Question 30(i)

Write a program in Java to find the sum of the given series:

x1 + x2 + x3 + x4 + ..... + xn

import java.util.Scanner;

public class KboatSeries
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter x: ");
        int x = in.nextInt();
        System.out.print("Enter n: ");
        int n = in.nextInt();
        long sum = 0;
        for (int i = 1; i <= n; i++)
            sum += Math.pow(x, i);
        System.out.println("Sum = " + sum);
    }
}
Output
BlueJ output of KboatSeries.java

Question 30(ii)

Write a program in Java to find the sum of the given series:

x1 - x2 + x3 - x4 + ..... - xn , where x = 3

import java.util.Scanner;

public class KboatSeries
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter n: ");
        int n = in.nextInt();
        int x = 3;
        double sum = 0;
        
        for (int i = 1; i <= n; i++) {
                double term = Math.pow(x, i);
                if (i % 2 == 0)
                    sum -= term;
                else
                    sum += term;
            }
            System.out.println("Sum = " + sum);
    }
}
Output
BlueJ output of KboatSeries.java

Question 30(iii)

Write a program in Java to find the sum of the given series:

1x1+2x2+3x3+...+nxn\dfrac{1}{x^1} + \dfrac{2}{x^2} + \dfrac{3}{x^3} + ... + \dfrac{n}{x^n}

import java.util.Scanner;

public class KboatSeries
{
    public static void main(String args[]) {

        Scanner in = new Scanner(System.in);
        System.out.print("Enter x: ");
        int x = in.nextInt();
        System.out.print("Enter n: ");
        int n = in.nextInt();
        double sum = 0;

        for (int i = 1; i <= n; i++) {
            sum += (i / Math.pow(x, i));
        }
        
        System.out.println("Sum=" + sum);
    }
}
Output
BlueJ output of KboatSeries.java

Question 30(iv)

Write a program in Java to find the sum of the given series:

12+23+34+...+4950\dfrac{1}{2} + \dfrac{2}{3} + \dfrac{3}{4} + ... + \dfrac{49}{50}

import java.util.Scanner;

public class KboatSeries
{
    public static void main(String args[]) {
        double sum = 0;
        for (int i = 1; i <= 49; i++)
            sum += i / (double)(i + 1);
        System.out.println("Sum = " + sum);
    }
}
Output
BlueJ output of KboatSeries.java

Question 30(v)

Write a program in Java to find the sum of the given series:

11+22+33+...+1010\dfrac{1}{\sqrt{1}} + \dfrac{2}{\sqrt{2}} + \dfrac{3}{\sqrt{3}} + ... + \dfrac{10}{\sqrt{10}}

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
BlueJ output of KboatSeries.java

Question 30(vi)

Write a program in Java to find the sum of the given series:

x+13+x+25+x+37+...to n terms\dfrac{x + 1}{3} + \dfrac{x + 2}{5} + \dfrac{x + 3}{7} + ...\text{to n terms}

import java.util.Scanner;

public class KboatSeries
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter n: ");
        int n = in.nextInt();
        System.out.print("Enter x: ");
        int x = in.nextInt();

        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
BlueJ output of KboatSeries.java

Question 30(vii)

Write a program in Java to find the sum of the given series:

x2!+x3!+x4!+...+x20!\dfrac{x}{2!} + \dfrac{x}{3!} + \dfrac{x}{4!} + ... + \dfrac{x}{20!}

import java.util.Scanner;

public class KboatSeries
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter x: ");
        int x = in.nextInt();
        double sum = 0;
        
        for (int i = 2; i <= 20; i++) {
            double f = 1;
            for (int j = 1; j <= i; j++) {
                f *= j;
            }
            sum += x / f;
        }
        System.out.println("Sum = " + sum);
        
    }
}
Output
BlueJ output of KboatSeries.java

Question 30(viii)

Write a program in Java to find the sum of the given series:

x22!+x33!+x44!+...+xnn!,where n = 10\dfrac{x^2}{2!} + \dfrac{x^3}{3!} + \dfrac{x^4}{4!} + ... + \dfrac{x^n}{n!}, \text{where n = 10}

import java.util.Scanner;

public class KboatSeries
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter x: ");
        int x = in.nextInt();
        double sum = 0;
        
        for (int i = 2; i <= 10; i++) {
            double f = 1;
            for (int j = 1; j <= i; j++) {
                f *= j;
            }
            double term = Math.pow(x,i) / f;
            sum += term;
        }
        System.out.println("Sum = " + sum);
        
    }
}
Output
BlueJ output of KboatSeries.java

Question 30(ix)

Write a program in Java to find the sum of the given series:

1 + 3 + 7 + 15 + 31 + ..... + (220 - 1)

public class KboatSeries
{
    public static void main(String args[]) {

        double sum = 0;
        
        for (int i = 1; i <= 20; i++) {
            double term = Math.pow(2,i) - 1;
            sum += term;
        }
            
        System.out.println("Sum = " + sum);
        
    }
}
Output
BlueJ output of KboatSeries.java

Question 30(x)

Write a program in Java to find the sum of the given series:

1 * 2 * 4 * 8 * ..... * 220

public class KboatSeries
{
    public static void main(String args[]) {

        double sum = 0;
        
        for (int i = 0; i <= 20; i++) {
            double term = Math.pow(2,i);
            sum += term;
        }
            
        System.out.println("Sum = " + sum);
        
    }
}
Output
BlueJ output of KboatSeries.java

Question 31

Write a menu driven class to accept a number from the user and check whether it is Palindrome or a Perfect number.

  1. Palindrome number: A number is a Palindrome which when read in reverse order is same as read in the right order Example: 11, 101, 151, etc.
  2. Perfect number: A number is called Perfect if it is equal to the sum of its factors other than the number itself.
    Example: 6 = 1 + 2 + 3
import java.util.Scanner;

public class KboatPalinOrPerfect
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("1. Palindrome number");
        System.out.println("2. Perfect number");
        System.out.print("Enter your choice: ");
        int choice = in.nextInt();
        System.out.print("Enter number: ");
        int num = in.nextInt();

        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;

            for (int i = 1; i <= num / 2; i++) {
                if (num % i == 0) {
                    sum += i;
                }
            }

            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
BlueJ output of KboatPalinOrPerfect.java
BlueJ output of KboatPalinOrPerfect.java

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;

public class KboatNumberSum
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int nSum = 0, eSum = 0, oSum = 0;
        System.out.println("Enter Numbers:");
        while (true) {
            int n = in.nextInt();
            
            if (n == 0) {
                break;
            }
            
            if (n < 0) {
                nSum += n; 
            }
            else if (n % 2 == 0) {
                eSum += n;
            }
            else {
                oSum += n;
            }
        }
        
        System.out.println("Negative No. Sum = " + nSum);
        System.out.println("Positive Even No. Sum = " + eSum);
        System.out.println("Positive Odd No. Sum = " + oSum);
    }
}
Output
BlueJ output of KboatNumberSum.java

Video Explanations

PrevNext