Chapter 6: Statements and Scope

PrevNextBack

Chapter 6: Statements and Scope

Contents

Multiple choice questions

Question 1

In a switch case statement, when no case is available for a given switch value, the control gets transfers to

  1. a break statement
  2. a default case
  3. a loop
  4. none

Question 2

A compound statement in a Java programming is enclosed under

  1. parenthesis
  2. curly braces
  3. square brackets
  4. none

Question 3

A condition is essentially formed by using

  1. arithmetic operators
  2. relational operators
  3. logical operators
  4. none

Question 4

if((a!=b)&&(a == c)) then which of the following statement is true:

  1. b is the smallest number
  2. b is the greatest number
  3. a is the smallest number
  4. none

Question 5

Given is a program snippet:

{
    if(a != b)
    c = a;
    else
    c = b;
}

It can be stated as

  1. c = (a == b) ? a : b;
  2. c = (a != b) ? a : b;
  3. c = (a != b) ? b : a;
  4. none

Question 6

if((a>b)&&(b>c)&&(c>d)) means:

  1. d is the greatest number
  2. d is the smallest number
  3. a is the smallest number
  4. none

Question 7

In an if statement two conditions are separated with the help of a:

  1. arithmetic operator
  2. relational operator
  3. logical operator
  4. none

Question 8

Which of the following is a conditional statement?

  1. if
  2. goto
  3. break
  4. none

Question 9

Which of the following is invalid for a break statement?

  1. Cannot be used in a switch statement
  2. Can be used in a switch statement
  3. Is compulsory to be used in a switch statement
  4. Used for unnatural termination of a loop.

Question 10

A Java program executes but does not give the desired output. It is due to the

  1. logical error in the program
  2. syntax error in the program
  3. grammatical error
  4. none

Rewrite the following statements using if-else

Question 1

commission=(sale > 5000) ? sale*10/100 : 0;
Answer
if (sale > 5000)
    commission = sale * 10 / 100;
else
    commission = 0;

Question 2

net=(salary > 10000) ? salary — (8.33/100)*salary : salary — (5/100)*salary;
Answer
if (salary > 10000)
    net = salary — (8.33/100)*salary;
else
    net = salary — (5/100)*salary;

Question 3

s = (a + b < c || a + c <= b || b + c <= a) ? "Triangle is not possible": "Triangle is possible";
Answer
if (a + b < c || a + c <= b || b + c <= a)
    s = "Triangle is not possible";
else
    s = "Triangle is possible";

Question 4

c = (x >= 'A' && x <= 'Z') ? "Upper Case Letter": "Lower Case Letter";
Answer
if (x >= 'A' && x <= 'Z')
    c = "Upper Case Letter";
else
    c = "Lower Case Letter";

Rewrite the following for loops by using while and do-while loops

Question 1

for(i=1,j=1;i<=10;i++,j++)
{
    System.out.println(i*j);
}
Answer
// Using while loop
int i = 1, j = 1;
while (i <= 10) {
    System.out.println(i*j);
    i++;
    j++;
}
// Using do-while loop
int i = 1, j = 1;
do {
    System.out.println(i*j);
    i++;
    j++;
} while (i <= 10);

Question 2

int p = 20;
for(k=p;k>=0;k-=2)
{
    s += k;
}
System.out.println("Sum="+s);
Answer
// Using while loop
int p = 20;
k = p;
while (k >= 0) {
    s += k;
    k-=2;
}
System.out.println("Sum="+s);
// Using do-while loop
int p = 20;
k = p;
do {
    s += k;
    k-=2;
} while (k >= 0);
System.out.println("Sum="+s);

Question 3

int a=37, b, c=0;
for(b=1;b<=a;b++)
{
    if (a % b == 0)
        c = c + 1;
}
if(c == 2)
    System.out.println(a + " is a prime number"); 
else
    System.out.println(a + " is not a prime number");
Answer
// Using while loop
int a=37, b=1, c=0;
while (b <= a) {
    if (a % b == 0)
        c = c + 1;
    b++;
}

if(c == 2)
    System.out.println(a + " is a prime number"); 
else
    System.out.println(a + " is not a prime number");
// Using do-while loop
int a=37, b=1, c=0;
do {
    if (a % b == 0)
        c = c + 1;
    b++;
} while (b <= a);

if(c == 2)
    System.out.println(a + " is a prime number"); 
else
    System.out.println(a + " is not a prime number");

Re-write the following using for loop

Question 1

int i = 1, f = 1;
do
{ 
f=f*i;
i++;
} 
while(i<=10);
System.out.println(f);
Answer
int f = 1;
for (int i = 1; i <= 10; i++) {
    f=f*i;
}
System.out.println(f);

Question 2

a=1;
while(a<=5)
{b = 1;
while(b<=a)
{ 
System.out.print(b);
b++;
} 
System.out.println();
a++;
}
Answer
for (a = 1; a <= 5; a++) {
    for (b = 1; b <= a; b++) {
        System.out.print(b);
    }
    System.out.println();
}

Predict the output of the given snippet. Show the dry run.

Question 1

State the final value of q at the end of the following program segment after execution. Show the dry run.

for(m=2;m<=3;++m)
{
for(n=1;n<=m;++n)
{
p=m+n-1;
if(p%3 == 0)
q += p;
else
q += p+4;
}
}
Answer

Final value of q = 29.

Dry Run

mnpqRemarks
0000Assuming initial value of all variables to be zero.
2000First iteration of outer loop begins, m is initialized to 2.
2100First iteration of inner loop begins, n is initialized to 1.
2120p = 2 + 1 - 1 = 2
2126q = 0 + 2 + 4 = 6 as p%3 != 0
2226Second iteration of inner loop begins, n is incremented to 2.
2236p = 2 + 2 - 1 = 3
2239q = 6 + 3 = 9 as p%3 == 0
2339Inner loop terminates as n becomes greater than m.
3339Second iteration of outer loop begins, m is incremented to 3.
3139Inner loop restarts from first iteration, n is initialized to 1..
3139p = 3 + 1 - 1 = 3
31312q = 9 + 3 = 12 as p%3 == 0
32312Second iteration of inner loop begins, n is incremented to 2.
32412p = 3 + 2 - 1 = 4
32420q = 12 + 4 + 4 = 20 as p%3 != 0
33420Third iteration of inner loop begins, n is incremented to 3.
33520p = 3 + 3 - 1 = 5
33529q = 20 + 5 + 4 = 29 as p%3 != 0
43529Outer loop terminates as m becomes greater than 3, final value of q is 29.

Question 2

Write the following statement using switch case construct.

if (a==1)
{
b += 10;
System.out.println(b);
}
else if (a == 2)
{
b -= 10;
System.out.println(b);
}
else
{
b *= a;
System.out.println(b); 
}
Answer
switch (a) {
    case 1:
    b += 10;
    System.out.println(b);
    break;

    case 2:
    b -= 10;
    System.out.println(b);
    break;

    default:
    b *= a;
    System.out.println(b); 
}

Write short answers

Question 1

What is meant by statement? Name the different types of statements which are used in Java programming.

Statement are instructions which tell the computer what to do. Statements are composed of valid tokens and keywords of the computer language in which they are coded. The different types of statements used in Java are:

  1. Declarative Statements
  2. Assignment Statements
  3. Input/Output Statements
  4. Control Statements
  5. Looping Statements
  6. Jump Statements

Question 2

Write short notes on:

(a) Control statement

The order in which the statements of a program are executed is known as control flow. By default, the statements of a program are executed from top to bottom in order in which they are written. But most of the times our programs require to alter this top to bottom control flow based on some condition. The statements that enable us to alter the control flow of the program are known as control statements. Control flow can be altered in the following two ways:

  1. Bi-Directional flow of control
    In Bi-Directional flow of control, control flow is transferred to one set of statements if the condition is true and to a different set of statements if the condition is false. We can perform Bi-Directional flow of control using if and if-else statements.
  2. Multiple Branching of control
    In Multiple Branching of control, multiple conditions are tested and then control flow is transferred to that branch (comprising of a particular set of statements) whose condition tests true. We can perform Multiple Branching of control using if-else-if ladder and switch-case statements.

(b) Looping statement

Looping statements are used to repeat a single statement or a set of statements as long as the desired condition remains true. There are two types of looping statements in Java:

  1. Entry-Controlled Loops
    An entry-controlled loop checks the condition at the time of entry. Only if the condition is true, the program control enters the body of the loop. for and while loops are entry-controlled loops.
  2. Exit-Controlled Loops
    An exit-controlled loop checks the condition after executing its body. If the condition is true, loop will perform the next iteration otherwise program control will move out of the loop. do-while loop is an exit-controlled loop.

Question 3

What is the purpose of default in a switch statement? Explain with the help of an example.

When none of the case values are equal to the expression of switch statement then default case is executed. In the example below, value of number is 4 so case 0, case 1 and case 2 are not equal to number. Hence println statement of default case will get executed printing "Value of number is greater than two" to the console.

int number = 4;
    
switch(number) {
    
    case 0:
        System.out.println("Value of number is zero");
        break;
        
    case 1:
        System.out.println("Value of number is one");
        break;
        
    case 2:
        System.out.println("Value of number is two");
        break;
        
    default:
        System.out.println("Value of number is greater than two");
        break;
        
}

Question 4

What are the different ways to input the values in a Java Programming? Name them

Different ways to input the values in a Java Program are:

  1. Using Method Arguments
  2. Using InputStreamReader Class
  3. Using Command Line Arguments
  4. Using Scanner Class

Question 5

Write down the syntax with reference to Java Programming:

(a) to accept an integral value

Answer
//Input through InputStreamReader Class
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
int a = Integer.parseInt(in.readLine());
//Input through Scanner Class
Scanner in = new Scanner(System.in);
int a = in.nextInt();

(b) to accept a fractional number

Answer
//Input through InputStreamReader Class
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
double d = Double.parseDouble(in.readLine());
//Input through Scanner Class
Scanner in = new Scanner(System.in);
double d = in.nextDouble();

(c) to accept a line of text

Answer
//Input through InputStreamReader Class
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
String str = in.readLine();
//Input through Scanner Class
Scanner in = new Scanner(System.in);
String str = in.nextLine();

Question 6

Explain the use of the following Mathematical functions:

(a) Math.rint( )

Math.rint method rounds off its argument to the nearest mathematical integer and returns its value as a double type. This method behaves in a particular way at the mid-point i.e. when the decimal part of the argument is 0.5. In such cases, the result is the integer value that is even. Let's understand this with an example. Math.rint(97.5) and Math.rint(98.5) will both return 98.0. In the case of 97.5, both 97.0 and 98.0 are equally close to 97.5. Math.rint choses the integer that is even so 98.0 is returned. In the case of 98.5, both 98.0 and 99.0 are equally close to 98.5. Math.rint again choses the integer that is even so 98.0 is returned.

(b) Math.ceil( )

Math.ceil method returns the smallest double value that is greater than or equal to the argument and is equal to a mathematical integer.
Example, System.out.println(Math.ceil(65.5)); will print 66.0. Here 66.0 is the smallest mathematical integer greater than 65.5 so it is the output.

(c) Math.log( )

Math.log returns the natural logarithm of its argument. Both, return type and argument is of double data type.

(d) Math.exp( )

This method returns e (Euler's number) raised to the power of a double value. It has the following syntax:
double exp(double a)

(e) Math.sin( )

This method returns the trigonometric sine of an angle. Its argument is the angle in radians. It has the following syntax:
double sin(double a)

(f) Math.atan( )

This method returns the arc tangent of its argument. It has the following syntax:
double atan(double a)

Question 7

What are the advantages of Scanner Class? Explain.

The advantages of Scanner Class are:

  1. The end of data element can be determined through a special token.
  2. It not only reads data but also parses it into specific types like short, int, float, boolean, etc.
  3. It can read String as well as primitive data types.
  4. Sting manipulation is easier as each word can be obtained as a token and handled separately.

Question 8

What is a token? Explain these methods while reading token from Scanner object.

(a) nextlnt( )      (b) nextDouble( )
(c) next( )           (d) nextLine( )

Token is a set of characters separated by simultaneous blank spaces or delimiters. The different methods to read tokens from Scanner object are:

nextInt()

It reads the next token from Scanner object which can be expressed as an integer and stores in integer type variable. Its syntax is:

int <variable> = <ScannerObject>.nextInt();

Example:

Scanner in = new Scanner(System.in);
int p;
p = in.nextInt();

nextDouble()

It reads the next token from Scanner object which can be expressed as a double type value and stores it in double type variable. Its syntax is:

double <variable> = <ScannerObject>.nextDouble();

Example:

Scanner in = new Scanner(System.in);
double d;
d = in.nextDouble();

next()

It reads the next complete token from Scanner object and returns it as a String. A complete token is preceded and followed by input that matches the delimiter pattern set by useDelimiter method. If no pattern is explicitly set, space is used as the default delimiter to separate tokens. Its syntax is:

String <variable> = <ScannerObject>.next();

Example:

Scanner in = new Scanner(System.in);
String str;
str = in.next();

nextLine()

It reads a complete line from Scanner object and returns it as a String. Its syntax is:

String <variable> = <ScannerObject>.nextLine();

Example:

Scanner in = new Scanner(System.in);
String str;
str = in.nextLine();

Question 9

With reference to switch case, explain the following:

(a) Default case

When none of the case values are equal to the expression of switch statement then default case is executed. In the example below, value of number is 4 so case 0, case 1 and case 2 are not equal to number. Hence SOPLN of default case will get executed printing "Value of number is greater than two" to the console.

int number = 4;
    
switch(number) {
    
    case 0:
        System.out.println("Value of number is zero");
        break;
        
    case 1:
        System.out.println("Value of number is one");
        break;
        
    case 2:
        System.out.println("Value of number is two");
        break;
        
    default:
        System.out.println("Value of number is greater than two");
        break;
        
}

(b) Fall through

break statement at the end of case is optional. Omitting break leads to program execution continuing into the next case and onwards till a break statement is encountered or end of switch is reached. This is termed as Fall Through in switch case statement.

int number = 1;
    
switch(number) {
        
    case 1:
        System.out.println("Value of number is one");
    case 2:
        System.out.println("Value of number is two");
        break;    
    case 3:
        System.out.println("Value of number is three");
    case 4:
        System.out.println("Value of number is four");
        break;
        
    default:
        System.out.println("Value of number is greater than four");
        break;
        
}

In the above example, as number is 1, case 1 matches and Value of number is one gets printed. But as there is no break in case 1 so program control falls through to case 2 and Value of number is two also gets printed. Case 2 has a break statement that transfers the program control to the end of switch-case statement. This continuation of program execution to case 2 is termed as Fall through.

Question 10

Distinguish between:

(a) Finite loop and Infinite loop

Finite loopInfinite loop
It iterates for a finite number of iterations.It continues iterating indefinitely.
Example:
int i = 1;
while(i <= 10) {
  System.out.println(i);
  i++;
}
Example:
int i = 0;
while(i <= 10) {
  System.out.println(i);
}

(b) Exit controlled loop and Entry controlled loop

Exit controlled loopEntry controlled loop
It checks the condition after executing its body. If the condition is true, loop will perform the next iteration otherwise program control will move out of the loop.It checks the condition at the time of entry. Only if the condition is true, the program control enters the body of the loop.
The loop executes at least once even if the condition is false.Loop does not execute at all if the condition is false.
Example: do-while loopExample: for and while loops

Solutions to Unsolved Programs on Decision making and Iteration through Loops

Question 1

A company deals with two types of customers (i.e. dealer and retailer) for selling its goods. The company also offers discount to the dealer and retailer at the time of purchasing goods for paying the bill, as per the tariff given below:

Days of paymentDiscount for DealerDiscount for Retailer
Within 30 days15%10%
31 to 45 days12%8%
46 to 60 days10%5%
More than 60 daysNo discountNo discount

Write a program in Java to accept:
(a) The number of days within which the bill is to be paid.
(b) The type of customer 'D' for dealer and 'R' for retailer.
(c) The amount of purchase.

The program displays the details to the customer at the time of paying the bill.

import java.util.Scanner;

public class KboatCompany
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter No. of days: ");
        int days = in.nextInt();
        System.out.print("Enter Type('D' - Dealer & 'R' - Retailer): ");
        char type = in.next().charAt(0);
        System.out.print("Enter Purchase Amount: ");
        double amt = in.nextDouble();
        int discPercent = 0;
        
        //Check if Customer Type is valid
        if (type != 'D' && type != 'R') {
            System.out.println("ERROR!!!Incorrect Customer Type.");
            return;
        }
        
        if (days <= 30)
            discPercent = type == 'D' ? 15 : 10;
        else if (days <= 45)
            discPercent = type == 'D' ? 12 : 8;
        else if (days <= 60)
            discPercent = type == 'D' ? 10 : 5;
        else
            discPercent = 0;
            
        double disc = amt * discPercent / 100;
        double billAmt = amt - disc;
        
        System.out.println("No. of days for bill payment = " + days);
        System.out.println("Customer Type = " + type);
        System.out.println("Purchase Amount = " + amt);
        System.out.println("Discount Amount = " + disc);
        System.out.println("Bill Amount = " + billAmt);
    }
}
Output
BlueJ output of KboatCompany.java

Question 2

Write a menu driven program using switch case statement to find the Arithmetic mean, Geometric mean and Harmonic mean which are calculated as:
(a) Arithmetic mean = (a + b) / 2
(b) Geometric mean = √ab
(c) Harmonic mean = 2ab / (a + b)

import java.util.Scanner;

public class KboatMean
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter 1 for Arithmetic mean");
        System.out.println("Enter 2 for Geometric mean");
        System.out.println("Enter 3 for Harmonic mean");
        System.out.print("Enter your choice: ");
        int choice = in.nextInt();
        System.out.print("Enter a: ");
        int a = in.nextInt();
        System.out.print("Enter b: ");
        int b = in.nextInt();
        double mean = 0.0;
        switch (choice) {
            case 1:
            mean = (a + b) / 2.0;
            System.out.println("Arithmetic mean = " + mean);
            break;
            
            case 2:
            mean = Math.sqrt(a * b);
            System.out.println("Geometric mean = " + mean);
            break;
            
            case 3:
            mean = 2.0 * a * b / (a + b);
            System.out.println("Harmonic mean = " + mean);
            break;
            
            default:
            System.out.println("Incorrect Choice!!!");
        }
    }
}
Output
BlueJ output of KboatMean.java
BlueJ output of KboatMean.java
BlueJ output of KboatMean.java

Question 3

Write a menu driven program using switch case statement to perform the given tasks as stated.
Task 1:
A Fibonacci series is given as:
0, 1, 1, 2, 3, 5, 8, 13, .......... and so on.
Display all the prime Fibonacci numbers in the range from 1 to 1000.
For example, 2, 3, 5, 13 are prime fibonacci numbers.
Task 2:
Prime factors are the factors of a number which are prime numbers. Display all the prime factors of a number.
Sample Input: 24
Sample Output: The prime factors of 24 are: 2, 2, 2, 3

import java.util.Scanner;

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

        switch (choice) {
            case 1:
            int a = 0, b = 1;
            int term = a + b;
            while (term <= 1000) {
                /*
                 * Check if the this term of
                 * Fibonacci Series is Prime
                 * or not
                 */
                int c = 0;
                for (int i = 1; i <= term; i++) {
                    if (term % i == 0) {
                        c++;
                    }
                }

                if (c == 2)
                    System.out.print(term + " ");
                    
                a = b;
                b = term;
                term = a + b;
            }
            break;

            case 2:
            System.out.print("Enter Number: ");
            int num = in.nextInt();
            System.out.print("The prime factors of " + num + " are: ");
            for(int i = 2; i < num; i++) {
                while (num % i == 0) {
                    System.out.print(i + " ");
                    num = num / i;
                }
            }
            if(num > 2) {
                System.out.println(num);
            }
            break;

            default:
            System.out.println("Incorrect Choice!!!");
        }
    }
}
Output
BlueJ output of KboatFibonacciPrimeFactors.java
BlueJ output of KboatFibonacciPrimeFactors.java

Question 5

Write a program in Java to enter a natural number, where N>100 and N<1000, the natural number must not contain zeros. Print all the combinations of digits of the number including the number itself. Each new combination should appear on a new line. The program displays a message "Invalid Number", if N <100 or contains zeros.

Sample Input: Enter a number: 465
Sample Output:
456
465
546
564
645
654

Sample Input: Enter a number: -712
Sample Output: Invalid Number

Sample Input: Enter a number: 960
Sample Output: Invalid Number

import java.util.Scanner;

public class KboatNumberCombinations
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = in.nextInt();
        if (n < 100 || n > 999) {
            System.out.println("Invalid Number");
            return;
        }
        
        int digits[] = new int[3];
        int t = n;
        int idx = 2;
        while (t != 0) {
            int d = t % 10;
            if (d == 0) {
                System.out.println("Invalid Number");
                return;
            }
            digits[idx--] = d;
             t /= 10;
        }
        
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                for (int k = 0; k < 3; k++) {
                     if (i != j && j != k && i != k)
                        System.out.println(digits[i] 
                                            + "" + digits[j] 
                                            + "" + digits[k]);
                }
            }
        }
    }
}
Output
BlueJ output of KboatNumberCombinations.java
BlueJ output of KboatNumberCombinations.java
BlueJ output of KboatNumberCombinations.java

Question 6

A triangular number is formed by the addition of consecutive integers starting with 1. For example,
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
Thus, 3, 6, 10, 15, are triangular numbers.
Write a program in Java to display all the triangular numbers from 3 to n, taking the value of n as an input.

import java.util.Scanner;

public class KboatTriangularNumbers
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: ");
        int n = in.nextInt();
        
        if (n < 3) {
            System.out.println("Value of n should be greater than or equal to 3");
            return;
        }
        
        System.out.println("Triangular Numbers from 3 to " 
                            + n + ":");
        int sum = 3; //First Triangular Number
        for (int i = 3; sum <= n; i++) {
            System.out.println(sum);
            sum += i;
        }
    }
}
Output
BlueJ output of KboatTriangularNumbers.java

Question 7

A Smith number is a composite number, whose sum of the digits is equal to the sum of its prime factors. For example:
4, 22, 27, 58, 85, 94, 121 .......... are Smith numbers.

Write a program in Java to enter a number and check whether it is a Smith number or not.

Sample Input: 666
Sum of the digits: 6 + 6 + 6 = 18
Prime factors are: 2, 3, 3, 37
Sum of the digits of the prime factors: 2 + 3 + 3 + (3 + 7) = 18
Thus, 666 is a Smith Number.

import java.util.Scanner;

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

        if (n <= 0) {
            System.out.println(n + " is not a Smith Number.");
            return;
        }

        boolean isComposite = false;
        for (int i = 2; i < n; i++) {
            if (n % i == 0) {
                isComposite = true;
                break;
            }
        }

        if (isComposite && n != 1) {
            int sumDigits = 0;
            int t = n;
            while (t != 0) {
                int d = t % 10;
                sumDigits += d;
                t /= 10;
            }

            int sumPrimeDigits = 0;
            t = n;
            for(int i = 2; i < t; i++) {
                while(t % i == 0) {
                    t /= i;
                    int temp = i;
                    while (temp != 0) {
                        int d = temp % 10;
                        sumPrimeDigits += d;
                        temp /= 10;
                    }
                }
            }
            
            if(t > 2) {
                while (t != 0) {
                    int d = t % 10;
                    sumPrimeDigits += d;
                    t /= 10;
                }
            }

            if (sumPrimeDigits == sumDigits)
                System.out.println(n + " is a Smith Number.");
            else
                System.out.println(n + " is not a Smith Number.");
        }
        else {
            System.out.println(n + " is not a Smith Number.");
        }
    }
}
Output
BlueJ output of KboatSmithNumber.java
BlueJ output of KboatSmithNumber.java

Question 8

A unique-digit integer is a positive integer (without leading zeros) with no duplicates digits. For example 7, 135, 214 are all unique-digit integers whereas 33, 3121, 300 are not. Given two positive integers m and n, where m < n, write a program to determine how many unique-digit integers are there in the range between m and n (both inclusive) and output them. The input contains two positive integers m and n. Assume m < 30000 and n < 30000. You are to output the number of unique-digit integers in the specified range along with their values in the format specified below:

Sample Input:
m = 100
n = 120
Sample Output:
The Unique-Digit integers are:
102, 103, 104, 105, 106, 107, 108, 109, 120.
Frequency of unique-digit integers is : 9

Sample Input:
m = 2500
n = 2550
Sample Output:
The Unique-Digit integers are:
2501, 2503, 2504, 2506, 2507, 2508, 2509, 2510, 2513, 2514, 2516, 2517, 2518, 2517, 2530, 2519, 2530, 2531, 2534, 2536, 2537, 2538, 2539, 2540, 2541, 2543, 2546, 2547, 2548, 2549.
Frequency of unique-digit integers is: 28.

import java.util.Scanner;

public class KboatUniqueIntegers
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter m: ");
        int m = in.nextInt();
        
        if (m < 1 || m > 30000) {
            System.out.println("Value of m should be between 1 and 30000");
            return;
        }
        
        System.out.print("Enter n: ");
        int n = in.nextInt();
        
        if (n < 1 || n > 30000) {
            System.out.println("Value of n should be between 1 and 30000");
            return;
        }
        
        if (m > n) {
            System.out.println("Value of m should be less than n");
            return;
        }
        
        System.out.println("The Unique-Digit integers are:");
        int count = 0;
        for (int i = m; i <= n; i++) {
            int num = i;
            boolean visited[] = new boolean[10];
            boolean isUnique = true;
            
            while (num != 0) {
                int d = num % 10;
                if (visited[d]) {
                    isUnique = false;
                    break;
                }
                visited[d] = true;
                num /= 10;
            }
            
            if (isUnique) {
                count++;
                System.out.print(i + " ");
            }
        }
        System.out.println();
        System.out.println("Frequency of unique-digit integers is: " + count);
    }
}
Output
BlueJ output of KboatUniqueIntegers.java

Question 9

A Composite Magic number is a positive integer which is composite as well as a magic number.

Composite number: A composite number is a number which has more than two factors.
For example:
Factors of 10 are: 1, 2, 5, 10

Magic number: A Magic number is a number in which the eventual sum of the digit is equal to 1.
For example: 28 = 2+8=10= 1+0=1

Accept two positive integers 'm' and 'n', where m is less than n. Display the number of composite magic integers that are in the range between m and n (both inclusive) and output them along with frequency, in the format specified below:

Sample Input:
m=10 n=100
Output: The composite magic numbers are 10,28,46,55,64,82,91,100
Frequency of composite magic numbers: 8

Sample Input:
m=120 n=90
Output: Invalid input

import java.util.Scanner;

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

        System.out.print("Enter n: ");
        int n = in.nextInt();

        if (m < 1 || n < 1 || m > n) {
            System.out.println("Invalid input");
            return;
        }

        System.out.println("The composite magic numbers are:");
        int count = 0;
        for (int i = m; i <= n; i++) {

            boolean isComposite = false;
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    isComposite = true;
                    break;
                }
            }

            if (isComposite && i != 1) {
                int num = i;
                while (num > 9) {
                    int sum = 0;
                    while (num != 0) {
                        int d = num % 10;
                        num /= 10;
                        sum += d;
                    }
                    num = sum;
                }

                if (num == 1) {
                    count++;
                    System.out.print(i + " ");
                }
            }
        }
        System.out.println();
        System.out.println("Frequency of composite magic numbers: " + count);
    }
}
Output
BlueJ output of KboatCompositeMagicNumber.java

Question 10

Given two positive numbers M and N, such that M is between 100 and 10000 and N is less than 100. Find the smallest integer that is greater than M and whose digits add up to N. For example, if M = 100 and N = 11, then the smallest integer greater than 100 whose digits add up to 11 is 119.

Write a program to accept the numbers M and N from the user and print the smallest required number whose sum of the digits is equal to N. Also, print the total number of digits present in the required number. The program should check for the validity of the inputs and display an appropriate message for an invalid input. Test your program with the sample data and some random data:

Example 1Example 2
Input:
M = 100
N = 11
Input:
M = 1500
N = 25
Output:
The required number = 119
Total number of digits = 3
Output:
The required number = 1699
Total number of digits = 4
Example 3Example 4
Input:
M = 99
N = 11
Input:
M = 112
N = 130
Output:
Invalid Input
Output:
Invalid Input
import java.util.Scanner;

public class KboatNumber
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter m: ");
        int m = in.nextInt();

        System.out.print("Enter n: ");
        int n = in.nextInt();

        if (m < 100 || m > 10000 || n < 1 || n >= 100) {
            System.out.println("Invalid Input");
            return;
        }

        int number = -1, count = 0;
        for (int i = m + 1; i < Integer.MAX_VALUE; i++) {
            int sum = 0;
            count = 0;
            int t = i;
            while (t != 0) {
                int d = t % 10;
                sum += d;
                t /= 10;
                count++;
            }

            if (sum == n) {
                number = i;
                break;
            }
        }

        if (number == -1) {
            System.out.println("Required number not found");
        }
        else {
            System.out.println("The required number = " + number);
            System.out.println("Total number of digits = " + count);
        }

    }
}
Output
BlueJ output of KboatNumber.java
BlueJ output of KboatNumber.java
BlueJ output of KboatNumber.java
BlueJ output of KboatNumber.java

Question 11

An Evil number is a positive whole number which has even number of 1's in its binary equivalent. Example: Binary equivalent of 9 is 1001, which contains even number of 1's. A few evil numbers are 3, 5, 6, 9.... Design a program to accept a positive whole number and find the binary equivalent of the number and count the number of 1's in it and display whether it is a Evil number or not with an appropriate message. Output the result in format given below:

Example 1
Input: 15
Binary Equivalent: 1111
No. of 1's: 4
Output: Evil Number

Example 2
Input: 26
Binary Equivalent: 11010
No. of 1's: 3
Output: Not an Evil Number

import java.util.Scanner;

public class KboatEvilNumber
{
     public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a positive number: ");
        int n = in.nextInt();
        if (n < 0) {
            System.out.println("Invalid Input");
            return;
        }
        
        int count = 0;
        int p = 0;
        int binNum = 0;
        
        while (n > 0) {
            int d = n % 2;
            if (d == 1)
                count++;
            binNum += (int)(d * Math.pow(10, p));
            p++;
            n /= 2;
        }
        
        System.out.println("Binary Equivalent: " + binNum);
        System.out.println("No. of 1's: " + count);
        
        if (count % 2 == 0)
            System.out.println("Output: Evil Number");
        else
            System.out.println("Output: Not an Evil Number");
    }
}
Output
BlueJ output of KboatEvilNumber.java
BlueJ output of KboatEvilNumber.java

Question 12

A number is said to Bouncy number if the digits of the number are unsorted.

For example,
22344 - It is not a Bouncy number because the digits are sorted in ascending order.
774410 - It is not a Bouncy number because the digits are sorted in descending order.
155349 - It is a Bouncy number because the digits are unsorted.
A number below 100 can never be a Bouncy number.

Write a program in java to accept a number. Check and display whether it is a Bouncy number or not.

import java.util.Scanner;

public class KboatBouncyNumber
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = in.nextInt();
        
        if (n < 100) {
            System.out.println(n + " is not a Bouncy Number.");
            return;
        }
        
        int t = n;
        boolean isIncreasing = true, isDecreasing = true;
        
        int prev = t % 10;
        while (t != 0) {
            int d = t % 10;
            if (d > prev) {
                isIncreasing = false;
                break;
            }
            prev = d;
            t /= 10;
        }
        
        t = n;
        prev = t % 10;
        while (t != 0) {
            int d = t % 10;
            if (d < prev) {
                isDecreasing = false;
                break;
            }
            prev = d;
            t /= 10;
        }
        
        if (!isIncreasing && !isDecreasing)
            System.out.println(n + " is a Bouncy Number.");
        else
            System.out.println(n + " is not a Bouncy Number.");
    }
}
Output
BlueJ output of KboatBouncyNumber.java
BlueJ output of KboatBouncyNumber.java
BlueJ output of KboatBouncyNumber.java
BlueJ output of KboatBouncyNumber.java

Question 13

Write a Program in Java to input a number and check whether it is a Pronic Number or Heteromecic Number or not.

Pronic Number: A Pronic number, oblong number, rectangular number or heteromecic number, is a number which is the product of two consecutive integers, that is, n (n + 1).

The first few Pronic numbers are:
0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132, 156, 182, 210, 240, 272, 306, 342, 380, 420, 462 ... etc.

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

Question 14

Write a Program in Java to input a number and check whether it is a Fascinating Number or not.

Fascinating Numbers: Some numbers of 3 digits or more exhibit a very interesting property. The property is such that, when the number is multiplied by 2 and 3, and both these products are concatenated with the original number, all digits from 1 to 9 are present exactly once, regardless of the number of zeroes.

Let's understand the concept of Fascinating Number through the following example:
Consider the number 192
192 x 1 = 192
192 x 2 = 384
192 x 3 = 576
Concatenating the results: 192 384 576
It could be observed that '192384576' consists of all digits from 1 to 9 exactly once. Hence, it could be concluded that 192 is a Fascinating Number. Some examples of fascinating Numbers are: 192, 219, 273, 327, 1902, 1920, 2019 etc.

import java.util.Scanner;

public class KboatFascinatingNumber
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number to check: ");
        int num = in.nextInt();
        
        if (num < 100) {
            System.out.println(num + " is not a Fascinating Number");
            return;
        }
        
        int num2 = num * 2;
        int num3 = num * 3;
        
        boolean isFascinating = true;
        String str = "" + num + num2 + num3;
        for (char i = '1'; i <= '9'; i++) {
            int idx1 = str.indexOf(i);
            int idx2 = str.lastIndexOf(i);
            if (idx1 == -1 || idx1 != idx2) {
                isFascinating = false;
                break;
            }
        }
        
        if (isFascinating)
            System.out.println(num + " is a Fascinating Number");
        else
            System.out.println(num + " is not a Fascinating Number");
    }
}
Output
BlueJ output of KboatFascinatingNumber.java

Question 15

Permutation and combination of two numbers 'n' and 'r' are calculated as:

nPr = !n / !(n - r)

nCr = !n / (!(n - r) * !r)

where, permutation is denoted as nPr and combination is denoted as nCr. The nPr means permutation of 'n' and 'r' & nCr means combination of 'n' and 'r'.

Write a program to calculate and display the number of permutation and combinations of two numbers 'n' and 'r' by using the above formula.

Sample Input:
Enter the value of n: 11
Enter the value of r: 10
Sample Output:
nPr is : 39916800
nCr is : 11

import java.util.Scanner;

public class KboatPermutationCombination
{
    static long factorial(int num) {
        int f = 1;
        for (int i = 1; i <= num; i++) {
            f *= i;
        }
        return f;
    }
    
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the value of n: ");
        int n = in.nextInt();
        System.out.print("Enter the value of r: ");
        int r = in.nextInt();
        int p = (int)(factorial(n) / factorial(n - r));
        int c = (int)(factorial(n) 
                      / (factorial(n - r) * factorial(r)));
        System.out.println("Permutation = " + p);
        System.out.println("Combination = " + c);
    }
}
Output
BlueJ output of KboatPermutationCombination.java

Question 16

Twins primes are consecutive prime numbers whose difference is 2.

For example, (3,5), (11,13), (17,19) are all twin primes. We define the distance of any twin prime pair from a positive integer as follows:

If (p1, p2) is a twin prime pair and n is a positive integer then the distance of the twin prime from n is: minimum(abs(n-p1), abs(n-p2)) where abs returns the absolute value of its argument, and minimum returns the smaller of its two arguments.

Write a program that reads in a positive integer n and prints out the twin prime pair that has the least distance from n.

For example:
(a) if n is 30 then the pair is (29, 31),
(b) if n is 13 it is (11,13), if n is 49 it is (41,43).
(c) if n is 54 it is (59, 61).

Sample Input: 34
Sample Output:
Number read in is 34      p1= 29, p2=31

Sample Input: 60
Sample Output:
Number read in is 60      p1= 59, p2=61

import java.util.Scanner;

public class KboatTwinPrime
{
    static boolean primeCheck(int num) {
        boolean isPrime = true;
        if (num <= 1)
            return false;
        
        for (int i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                isPrime = false;
                break;
            }
        }
        
        return isPrime;
    }
    
    static void printResult(int n, int p1, int p2) {
        System.out.println("Number read in is " 
                                + n + "\tp1 = " 
                                + p1 + ", p2 = " 
                                + p2);
    }
    
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = in.nextInt();
        
        /*
         * First check if the number itself is prime
         * and forms a twin prime pair with a number
         * at distance 2 on either side. For example,
         * if n is 13 then (11, 13) forms a twin 
         * prime pair at least distance from 13
         */
        boolean res1 = primeCheck(n);
        if (res1) {
            boolean res2 = primeCheck(n - 2);
            if (res2) {
                printResult(n, n - 2, n);
                return;
            }
            
            boolean res3 = primeCheck(n + 2);
            if (res3) {
                printResult(n, n, n + 2);
                return;
            }
        }
        
        /*
         * After that check if the number falls between
         * a twin prime pair. For example, if n is 12
         * then twin prime pair at least distance is
         * (11, 13)
         */
        if (primeCheck(n - 1) && primeCheck(n + 1)) {
            printResult(n, n - 1, n + 1);
            return;
        }
        
        /*
         * Find a twin prime pair towards left
         */
        int l1 = 0, l2 = 0;
        for (int i = n - 1; i >= 5; i--) {
            if (primeCheck(i) && primeCheck(i - 2)) {
                l1 = i - 2;
                l2 = i;
                break;
            }
        }
        
        /*
         * Find a twin prime pair towards right
         */
        int r1 = 0, r2 = 0;
        for (int i = n + 1; i < Integer.MAX_VALUE - 2; i++) {
            if (primeCheck(i) && primeCheck(i + 2)) {
                r1 = i;
                r2 = i + 2;
                break;
            }
        }
        
        /*
         * Find the twin prime pair with minimum distance
         */
        if (l1 != 0 && l2 != 0 && r1 != 0 && r2 != 0) {
            int lDist = Math.min(Math.abs(n - l1), Math.abs(n - l2));
            int rDist = Math.min(Math.abs(n - r1), Math.abs(n - r2));
            if (lDist < rDist)
                printResult(n, l1, l2);
            else
                printResult(n, r1, r2);
        }
        else if (l1 != 0 && l2 != 0) {
            printResult(n, l1, l2);
        }
        else if (r1 != 0 && r2 != 0) {
            printResult(n, r1, r2);
        }
    }
}
Output
BlueJ output of KboatTwinPrime.java
BlueJ output of KboatTwinPrime.java