Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views56 pages

Java Programs

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views56 pages

Java Programs

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Algorithm for Strontio Number

START
1. Read an integer number from the user.
2. Multiply the number by 2.
3. Convert the result into a string.
4. Extract the middle two digits of the result.
5. If both middle digits are the same, then the number is a Strontio
Number.
6. Otherwise, it is not a Strontio Number.
END

Java Program
import java.util.Scanner;

class Strontio {
int num; // variable to hold input number

// Constructor to initialize variable


Strontio(int n) {
num = n;
}

// Function to check Strontio number


boolean isStrontio() {
int result = num * 2;
String str = String.valueOf(result);
int mid1 = str.length() / 2 - 1;
int mid2 = str.length() / 2;
return str.charAt(mid1) == str.charAt(mid2);
}
}

public class Main {


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

// Input
System.out.print("Enter a number: ");
int n = sc.nextInt();

// Object creation
Strontio s = new Strontio(n);

// Output
if (s.isStrontio())
System.out.println(n + " is a Strontio Number.");
else
System.out.println(n + " is NOT a Strontio Number.");

sc.close();
}
}
Variable Description
Variable Name Data Type Description (Purpose)
num int Stores the input number to check Strontio property
result int Stores the doubled value of the input number
str String Holds the string representation of result
mid1 int Index of first middle digit of str
mid2 int Index of second middle digit of str
n int Temporary variable in main to store user input
Algorithm for EVIL Number
START
1. Read an integer number from the user.
2. Convert the number into its binary equivalent.
3. Count the number of 1s in the binary representation.
4. If the count of 1s is even, then it is an EVIL number.
5. Otherwise, it is NOT an EVIL number.
END

Java Program
import java.util.Scanner;

class Evil {
int num; // variable to hold input number

// Constructor
Evil(int n) {
num = n;
}

// Function to check Evil number


boolean isEvil() {
String binary = Integer.toBinaryString(num);
int count = 0;
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '1') {
count++;
}
}
return count % 2 == 0;
}
}

public class Main {


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

// Input
System.out.print("Enter a number: ");
int n = sc.nextInt();

// Object creation
Evil e = new Evil(n);

// Output
if (e.isEvil())
System.out.println(n + " is an EVIL Number.");
else
System.out.println(n + " is NOT an EVIL Number.");

sc.close();
}
}
Variable Description
Variable Name Data Type Description (Purpose)
num int Stores the input number to check EVIL property
binary String Holds the binary representation of the number
count int Counts the number of 1s in the binary string
n int Temporary variable in main to store user input
Algorithm for Keith Number
START
1. Read an integer number from the user.
2. Store its digits in an array (digit by digit).
3. Repeatedly:
a) Add all the digits of the array.
b) Shift the array left (discard the first digit).
c) Append the sum at the end of the array.
4. Continue until the sum is greater than or equal to the original number.
5. If the sum equals the original number, it is a Keith Number.
6. Otherwise, it is NOT a Keith Number.
END

Java Program
import java.util.Scanner;

class Keith {
int num; // input number

// Constructor
Keith(int n) {
num = n;
}

// Function to check Keith number


boolean isKeith() {
String s = String.valueOf(num);
int d = s.length(); // number of digits
int arr[] = new int[d];

// store digits in array


for (int i = 0; i < d; i++) {
arr[i] = Character.getNumericValue(s.charAt(i));
}

int sum = 0;
while (sum < num) {
sum = 0;
for (int i = 0; i < d; i++) {
sum += arr[i];
}
if (sum == num) return true;

// shift and append sum


for (int i = 0; i < d - 1; i++) {
arr[i] = arr[i + 1];
}
arr[d - 1] = sum;
}
return false;
}
}

public class Main {


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

// Input
System.out.print("Enter a number: ");
int n = sc.nextInt();

// Object
Keith k = new Keith(n);

// Output
if (k.isKeith())
System.out.println(n + " is a Keith Number.");
else
System.out.println(n + " is NOT a Keith Number.");

sc.close();
}
}

Variable Description
Variable Name Data Type Description (Purpose)
num int Stores the input number to check Keith property
s String Holds string form of number to count digits
d int Number of digits in the input number
arr[] int[] Array storing digits and later sequence values
sum int Stores sum of last d terms for Keith sequence
n int Temporary variable in main to store user input
Algorithm for Pronic Number
START
1. Read an integer number from the user.
2. Initialize i = 0.
3. Repeat until i * (i + 1) is greater than or equal to the number:
a) If i * (i + 1) = number, then it is a Pronic Number.
b) Otherwise increase i by 1.
4. If no such i exists, then it is NOT a Pronic Number.
END

Java Program
import java.util.Scanner;

class Pronic {
// Function to check Pronic number
boolean isPronic(int num) {
for (int i = 0; i <= num; i++) {
if (i * (i + 1) == num)
return true;
}
return false;
}
}

public class Main {


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

// Input
System.out.print("Enter a number: ");
int n = sc.nextInt();

// Object creation
Pronic p = new Pronic();

// Output
if (p.isPronic(n))
System.out.println(n + " is a Pronic Number.");
else
System.out.println(n + " is NOT a Pronic Number.");

sc.close();
}
}

Variable Description
Variable Name Data Type Description (Purpose)
num int Stores the input number to check Pronic property
i int Loop variable used to test i * (i+1)
n int Temporary variable in main to store user input
Algorithm for Composite Magic Number
START
1. Read a number from the user.
2. Check if the number is composite:
- If it has more than 2 factors, it is composite.
3. If composite:
a) Find the sum of its digits.
b) Repeat: Replace the number by the sum of its digits until it
becomes a single digit.
c) If the final single digit = 1, then it is a Magic Number.
4. If both composite AND magic → Composite Magic Number.
5. Else → Not a Composite Magic Number.
END

Java Program
import java.util.Scanner;

class CompositeMagic {
// Function to check composite number
boolean isComposite(int num) {
if (num <= 3) return false;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0)
return true;
}
return false;
}

// Function to calculate sum of digits repeatedly


int digitSum(int num) {
while (num > 9) { // keep reducing until single digit
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
num = sum;
}
return num;
}

// Function to check magic number


boolean isMagic(int num) {
return digitSum(num) == 1;
}
}

public class Main {


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

// Input
System.out.print("Enter a number: ");
int n = sc.nextInt();
CompositeMagic cm = new CompositeMagic();

// Output
if (cm.isComposite(n) && cm.isMagic(n))
System.out.println(n + " is a Composite Magic Number.");
else
System.out.println(n + " is NOT a Composite Magic Number.");

sc.close();
}
}

Variable Description
Variable Name Data Type Description (Purpose)
num int General variable used in checking composite/magic
i int Loop variable for checking factors
sum int Stores digit sum at each reduction step
n int Stores user input in main
Algorithm for ORE Number
START
1. Read a number from the user.
2. Find all divisors of the number.
3. Count the number of divisors and compute their sum.
4. Find the sum of digits of the number.
5. Count the number of digits in the number.
6. Calculate both ratios:
- Divisor ratio = (sum of divisors) / (count of divisors)
- Digit ratio = (sum of digits) / (count of digits)
7. If both ratios are equal → ORE Number.
8. Otherwise → Not an ORE Number.
END

Java Program
import java.util.Scanner;

class ORE {
// Function to check ORE number
boolean isORE(int num) {
int sumDiv = 0, countDiv = 0;

// find divisors
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
sumDiv += i;
countDiv++;
}
}

// sum of digits and digit count


int temp = num, sumDig = 0, countDig = 0;
while (temp > 0) {
sumDig += temp % 10;
temp /= 10;
countDig++;
}

// compare ratios using cross multiplication to avoid fractions


return (sumDiv * countDig) == (sumDig * countDiv);
}
}

public class Main {


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

// Input
System.out.print("Enter a number: ");
int n = sc.nextInt();

ORE o = new ORE();

// Output
if (o.isORE(n))
System.out.println(n + " is an ORE Number.");
else
System.out.println(n + " is NOT an ORE Number.");

sc.close();
}
}

Variable Description
Variable Name Data Type Description (Purpose)
num int Stores the input number to check ORE property
sumDiv int Sum of divisors of the number
countDiv int Count of divisors of the number
temp int Temporary copy of num used for digit operations
sumDig int Sum of digits of the number
countDig int Count of digits of the number
n int User input stored in main
Algorithm For Kaprekar number
START
1. Read a number from the user.
2. Compute square of the number.
3. Count the number of digits in the original number.
4. Split the square into two parts:
- Right part: last (digit count) digits of the square.
- Left part: remaining digits of the square.
5. If (left part + right part) = original number, it is a Kaprekar Number.
6. Otherwise, it is NOT a Kaprekar Number.
END

Java Program
import java.util.Scanner;

class Kaprekar {
// Function to check Kaprekar number
boolean isKaprekar(int num) {
if (num == 1) return true; // 1 is Kaprekar by definition

long sq = (long) num * num; // square may be big


int d = String.valueOf(num).length(); // digits in num

// Split into parts


long right = sq % (long) Math.pow(10, d);
long left = sq / (long) Math.pow(10, d);

// Compare sum with original number


return (left + right) == num;
}
}

public class Main {


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

// Input
System.out.print("Enter a number: ");
int n = sc.nextInt();

Kaprekar k = new Kaprekar();

// Output
if (k.isKaprekar(n))
System.out.println(n + " is a Kaprekar Number.");
else
System.out.println(n + " is NOT a Kaprekar Number.");

sc.close();
}
}
Variable Description
Variable Name Data Type Description (Purpose)
num int Stores the input number to check Kaprekar property
sq long Stores the square of the number (can be large)
d int Number of digits in the input number
right long Last d digits of the square
left long Remaining digits of the square
n int User input stored in main
Algorithm For Goldbach number
START
1. Read an even number n from the user (n > 2).
2. For every i from 2 to n/2:
a) Check if both i and (n - i) are prime.
b) If yes, then n can be expressed as sum of two primes → Goldbach
Number.
3. If no such pair exists, then it is NOT a Goldbach Number.
END

Java Program
import java.util.Scanner;

class Goldbach {
// Function to check prime
boolean isPrime(int num) {
if (num < 2) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0)
return false;
}
return true;
}

// Function to check Goldbach number


boolean isGoldbach(int num) {
if (num <= 2 || num % 2 != 0) return false; // only even > 2
for (int i = 2; i <= num / 2; i++) {
if (isPrime(i) && isPrime(num - i)) {
System.out.println(num + " = " + i + " + " + (num - i));
return true;
}
}
return false;
}
}

public class Main {


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

// Input
System.out.print("Enter an even number greater than 2: ");
int n = sc.nextInt();

Goldbach g = new Goldbach();

// Output
if (g.isGoldbach(n))
System.out.println(n + " is a Goldbach Number.");
else
System.out.println(n + " is NOT a Goldbach Number.");

sc.close();
}
}

Variable Description
Variable Name Data Type Description (Purpose)
num int Input number to check Goldbach property
i int Loop variable to try prime pairs
n int User input in main
Algorithm for ISBN Number
START
1. Read a 10-digit number from the user.
2. Initialize sum = 0.
3. For each digit (from left to right):
- Multiply the digit by its position (1 to 10).
- Add to sum.
4. If sum % 11 == 0 → Valid ISBN number.
5. Otherwise → Invalid ISBN number.
END

Java Program
import java.util.Scanner;

class ISBN {
// Function to check ISBN number
boolean isISBN(long num) {
String s = String.valueOf(num);
if (s.length() != 10) return false; // must be 10 digits

int sum = 0;
for (int i = 0; i < 10; i++) {
int digit = s.charAt(i) - '0';
sum += (i + 1) * digit;
}

return sum % 11 == 0;
}
}

public class Main {


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

// Input
System.out.print("Enter a 10-digit number: ");
long n = sc.nextLong();

ISBN obj = new ISBN();

// Output
if (obj.isISBN(n))
System.out.println(n + " is a Valid ISBN Number.");
else
System.out.println(n + " is NOT a Valid ISBN Number.");

sc.close();
}
}
Variable Description
Variable Name Data Type Description (Purpose)
num long Stores the input 10-digit number
s String String form of the number (to access each digit)
sum int Stores weighted sum of digits
digit int Individual digit extracted from the string
i int Loop counter for digit positions
n long User input stored in main
Algorithm for Potential of String
START
1. Read a string from the user.
2. Initialize sum = 0.
3. For each character in the string:
a) Convert it to uppercase.
b) If it is a letter between A–Z:
- Find its position: (ch - 'A' + 1).
- Add to sum.
4. Print the sum as the potential of the string.
END

Java Program
import java.util.Scanner;

class Potential {
// Function to calculate potential of a string
int getPotential(String str) {
int sum = 0;
str = str.toUpperCase();

for (int i = 0; i < str.length(); i++) {


char ch = str.charAt(i);
if (ch >= 'A' && ch <= 'Z') {
sum += (ch - 'A' + 1);
}
}
return sum;
}
}

public class Main {


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

// Input
System.out.print("Enter a string: ");
String s = sc.nextLine();

Potential p = new Potential();

// Output
int pot = p.getPotential(s);
System.out.println("Potential of \"" + s + "\" = " + pot);

sc.close();
}
}
Variable Description
Variable Name Data Type Description (Purpose)
str String Stores the input string
sum int Stores the total potential of the string
ch char Holds individual character of the string
i int Loop counter for traversing characters
s String User input stored in main
pot int Final computed potential value
Algorithm for Clockwise Rotation of a Matrix
START
1. Read the size (n) of the matrix.
2. Input the n×n matrix elements.
3. To rotate clockwise:
a) Transpose the matrix (swap rows with columns).
b) Reverse each row.
4. Print the rotated matrix.
END

Java Program
import java.util.Scanner;

class MatrixRotation {
// Function to rotate matrix clockwise by 90 degrees
void rotateClockwise(int[][] mat, int n) {
// Step 1: Transpose
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}

// Step 2: Reverse each row


for (int i = 0; i < n; i++) {
for (int j = 0; j < n / 2; j++) {
int temp = mat[i][j];
mat[i][j] = mat[i][n - 1 - j];
mat[i][n - 1 - j] = temp;
}
}
}

// Function to print matrix


void printMatrix(int[][] mat, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
}
}

public class Main {


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

System.out.print("Enter size of matrix (n): ");


int n = sc.nextInt();

int[][] mat = new int[n][n];


System.out.println("Enter " + (n * n) + " elements:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
mat[i][j] = sc.nextInt();
}
}

MatrixRotation mr = new MatrixRotation();

System.out.println("Original Matrix:");
mr.printMatrix(mat, n);

mr.rotateClockwise(mat, n);

System.out.println("Matrix after 90° Clockwise Rotation:");


mr.printMatrix(mat, n);

sc.close();
}
}

Variable Description
Variable Name Data Type Description
n int Size of the square matrix
mat int[][] 2D array storing matrix elements
i, j int Loop counters for rows and columns
temp int Temporary variable for swapping elements
sc Scanner To take user input
Algorithm for Anticlockwise Rotation of a
Matrix
START
1. Read the size (n) of the matrix.
2. Input the n×n matrix elements.
3. To rotate anticlockwise:
a) Transpose the matrix (swap rows with columns).
b) Reverse each column.
4. Print the rotated matrix.
END

Java Program (90° Anticlockwise Rotation)


import java.util.Scanner;

class MatrixRotation {
// Function to rotate matrix anticlockwise by 90 degrees
void rotateAnticlockwise(int[][] mat, int n) {
// Step 1: Transpose
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}

// Step 2: Reverse each column


for (int j = 0; j < n; j++) {
for (int i = 0; i < n / 2; i++) {
int temp = mat[i][j];
mat[i][j] = mat[n - 1 - i][j];
mat[n - 1 - i][j] = temp;
}
}
}

// Function to print matrix


void printMatrix(int[][] mat, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
}
}

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter size of matrix (n): ");
int n = sc.nextInt();

int[][] mat = new int[n][n];


System.out.println("Enter " + (n * n) + " elements:");

for (int i = 0; i < n; i++) {


for (int j = 0; j < n; j++) {
mat[i][j] = sc.nextInt();
}
}

MatrixRotation mr = new MatrixRotation();

System.out.println("Original Matrix:");
mr.printMatrix(mat, n);

mr.rotateAnticlockwise(mat, n);

System.out.println("Matrix after 90° Anticlockwise Rotation:");


mr.printMatrix(mat, n);

sc.close();
}
}

🔹 Variable Description
Variable Name Data Type Description
n int Size of the square matrix
mat int[][] 2D array storing matrix elements
i, j int Loop counters for rows and columns
temp int Temporary variable for swapping elements
sc Scanner To take user input
Concept/Algorithm
 Octal Number System → Base 8 (digits: 0–7).
 Decimal Number System → Base 10.
 To convert an octal number to decimal, multiply each digit by the corresponding
power of 8 and sum the results. The rightmost digit is multiplied by 8⁰ (which is 1),
the next digit to the left by 8¹, then 8², and so on for the whole number part. For
fractional parts, the powers of 8 become negative (8⁻¹, 8⁻², etc.).

Java Program (Octal → Decimal)


import java.util.Scanner;

public class OctalToDecimal {


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

System.out.print("Enter an octal number: ");


int octal = sc.nextInt();

int decimal = 0, base = 1, temp = octal;

// Conversion
while (temp > 0) {
int lastDigit = temp % 10; // extract last digit
decimal += lastDigit * base; // add to decimal
base *= 8; // increase power of 8
temp /= 10; // remove last digit
}

System.out.println("Octal Number: " + octal);


System.out.println("Decimal Equivalent: " + decimal);

sc.close();
}
}

Variable Description
Variable Name Data Type Description
octal int Stores input octal number
decimal int Stores converted decimal value
base int Keeps track of powers of 8 (1, 8, 64, …)
temp int Temporary copy of octal for processing
lastDigit int Extracted last digit of the octal number
Algorithm FOR ODIOUS NUMBER
START
Step 1: Input a number n.
Step 2: Initialize count = 0.
Step 3: Repeat until n > 0:
- If n % 2 == 1, increase count by 1.
- Divide n by 2 (n = n / 2).
Step 4: If count is odd → Odious Number.
Step 5: Else → Not Odious Number.
END

Java Program
import java.util.Scanner;

public class OdiousNumber {


public static boolean isOdious(int n) {
int count = 0;
while (n > 0) {
if (n % 2 == 1) // check remainder
count++;
n = n / 2; // reduce number
}
return (count % 2 != 0); // odd number of 1s → Odious
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");


int num = sc.nextInt();

if (isOdious(num))
System.out.println(num + " is an Odious Number");
else
System.out.println(num + " is NOT an Odious Number");

sc.close();
}
}

Variable Description
Variable Name Data Type Description
n int Number being checked in the function
count int Counts number of 1’s in binary representation
num int User input number
sc Scanner To accept user input
Algorithm (Mystery Number)
START
Step 1: Input a number n.
Step 2: For i = 1 to n/2:
- Reverse i → rev
- If i + rev = n, then n is a Mystery Number.
Step 3: If such i exists, print "Mystery Number".
Step 4: Otherwise, print "Not a Mystery Number".
END

Java Program
import java.util.Scanner;

public class MysteryNumber {


// function to reverse a number
public static int reverse(int n) {
int rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n = n / 10;
}
return rev;
}

// function to check Mystery number


public static boolean isMystery(int n) {
for (int i = 1; i <= n / 2; i++) {
int rev = reverse(i);
if (i + rev == n)
return true;
}
return false;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");


int num = sc.nextInt();

if (isMystery(num))
System.out.println(num + " is a Mystery Number");
else
System.out.println(num + " is NOT a Mystery Number");

sc.close();
}
}
Variable Description
Variable Name Data Type Description
n int Number to be checked
i int Iterator for possible parts of n
rev int Stores reverse of i
num int User input number
sc Scanner For user input
Algorithm (Undulating Number)
START
Step 1: Input a number n.
Step 2: Convert n into a string s.
Step 3: If length of s < 3, then not undulating.
Step 4: Let first digit = a, second digit = b.
Step 5: If a == b, then not undulating.
Step 6: For i from 0 to length-1:
- If i is even → digit must be a
- If i is odd → digit must be b
- If condition fails → not undulating.
Step 7: If loop completes, then n is undulating.
END

Java Program
import java.util.Scanner;

public class UndulatingNumber {

// function to check if undulating


public static boolean isUndulating(int n) {
String s = String.valueOf(n);

if (s.length() < 3)
return false;

char a = s.charAt(0);
char b = s.charAt(1);

if (a == b)
return false;

for (int i = 0; i < s.length(); i++) {


if (i % 2 == 0 && s.charAt(i) != a) return false;
if (i % 2 == 1 && s.charAt(i) != b) return false;
}
return true;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");


int num = sc.nextInt();

if (isUndulating(num))
System.out.println(num + " is an Undulating Number");
else
System.out.println(num + " is NOT an Undulating Number");

sc.close();
}
}
Variable Description
Variable Name Data Type Description
n int Number to be checked
s String String form of number
a char First digit
b char Second digit
i int Loop counter
num int User input number
sc Scanner For user input
Algorithm
START
Step 1: Input a number n.
Step 2: Copy n into temp.
Step 3: Initialize sum = 0.
Step 4: While temp > 0:
- Extract digit = temp % 10
- If digit == 0 → add 0
- Else → add digit^digit to sum
- temp = temp / 10
Step 5: If sum == n → n is a Münchhausen number
else not.
END

Java Program
import java.util.Scanner;

public class MunchhausenNumber {

// Function to check Münchhausen


public static boolean isMunchhausen(int n) {
int temp = n, sum = 0;

while (temp > 0) {


int digit = temp % 10;

if (digit == 0) {
sum += 0; // 0^0 = 0 (by definition here)
} else {
int power = 1;
for (int i = 1; i <= digit; i++) {
power *= digit; // calculate digit^digit
}
sum += power;
}
temp /= 10;
}
return sum == n;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");


int num = sc.nextInt();

if (isMunchhausen(num))
System.out.println(num + " is a Münchhausen Number");
else
System.out.println(num + " is NOT a Münchhausen Number");

sc.close();
}
}
Variable Description
Variable Name Data Type Description
n int Number to be checked
temp int Copy of number for digit extraction
sum int Sum of digit^digit
digit int Current extracted digit
power int Value of digit^digit
num int User input number
sc Scanner For user input
Algorithm (Steps)
1. Read the number n.
2. Find sum of digits of n.
3. Check if n % sum == 0.
o If yes → Good Number.
o Else → Not a Good Number.

Java Program
import java.util.Scanner;

public class GoodNumber {

public static boolean isGoodNumber(int n) {


int temp = n, sum = 0;

while (temp > 0) {


sum += temp % 10; // extract digit and add
temp /= 10;
}

return (n % sum == 0);


}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");


int num = sc.nextInt();

if (isGoodNumber(num))
System.out.println(num + " is a Good Number");
else
System.out.println(num + " is NOT a Good Number");

sc.close();
}
}

Variable Description
Variable Type Meaning
n int Input number to check
temp int Copy of number for digit extraction
sum int Sum of digits
num int User input number
sc Scanner Input object
Algorithm (Steps)
1. START
2. Read number n.
3. Compute cuberoot = round(cube root of n).
4. If cuberoot * cuberoot * cuberoot != n, then it is not a Dudeney Number →
END.
5. Find sum of digits of n.
6. If sum of digits = cube root → Dudeney Number.
7. Else → Not a Dudeney Number.
8. END

Java Program
import java.util.Scanner;

public class DudeneyNumber {

public static boolean isDudeney(int n) {


int cuberoot = (int)Math.round(Math.cbrt(n));

// check perfect cube


if (cuberoot * cuberoot * cuberoot != n)
return false;

int temp = n, sum = 0;


while (temp > 0) {
sum += temp % 10;
temp /= 10;
}

return (sum == cuberoot);


}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");


int num = sc.nextInt();

if (isDudeney(num))
System.out.println(num + " is a Dudeney Number");
else
System.out.println(num + " is NOT a Dudeney Number");

sc.close();
}
}
Variable Description
Variable Data Type Description
n int Input number to be checked
cuberoot int Cube root of the number
temp int Copy of number for digit extraction
sum int Sum of digits
num int User input number
sc Scanner Input object
Algorithm (Steps)

1. START
2. Read the number n.
3. Compute the sum of digits of n.
4. Reverse the sum of digits.
5. Check:
o if n % sum == 0
o AND n % reverseSum == 0
6. If both true → Doubly Markov Number.
7. Else → Not a Doubly Markov Number.
8. END

Java Program
import java.util.Scanner;

public class DoublyMarkov {

public static boolean isDoublyMarkov(int n) {


int temp = n, sum = 0;

// find sum of digits


while (temp > 0) {
sum += temp % 10;
temp /= 10;
}

// reverse of sum
int rev = 0, s = sum;
while (s > 0) {
rev = rev * 10 + (s % 10);
s /= 10;
}

// check divisibility
return (n % sum == 0 && n % rev == 0);
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");


int num = sc.nextInt();

if (isDoublyMarkov(num))
System.out.println(num + " is a Doubly Markov Number");
else
System.out.println(num + " is NOT a Doubly Markov Number");

sc.close();
}
}
Variable Description
Variable Data Type Description

n int Input number to be checked

temp int Copy of n for digit extraction

sum int Sum of digits of n

rev int Reverse of sum of digits

s int Temporary variable used to reverse sum

num int User input

sc Scanner For input


Algorithm

1. START
2. Input a number n.
3. Convert n into digits.
4. Assume two flags:
o inc = true if digits are increasing.
o dec = true if digits are decreasing.
5. Traverse the digits from left to right:
o If a digit is greater than the next, set inc = false.
o If a digit is smaller than the next, set dec = false.
6. After traversal:
o If both inc and dec are false → Bouncy Number.
o Else → Not a Bouncy Number.
7. END

Java Program
import java.util.Scanner;

public class BouncyNumber {

public static boolean isBouncy(int n) {


String num = String.valueOf(n);
boolean increasing = false, decreasing = false;

for (int i = 0; i < num.length() - 1; i++) {


int d1 = num.charAt(i) - '0';
int d2 = num.charAt(i + 1) - '0';

if (d1 < d2) increasing = true;


if (d1 > d2) decreasing = true;

// If both conditions are true, it’s bouncy


if (increasing && decreasing) return true;
}
return false;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");


int num = sc.nextInt();

if (isBouncy(num))
System.out.println(num + " is a Bouncy Number");
else
System.out.println(num + " is NOT a Bouncy Number");

sc.close();
}
}
Variable Description
Variable Data Type Description

n int Input number to check

num String String form of number for easy digit access

increasing boolean Flag to check if digits increase

decreasing boolean Flag to check if digits decrease

d1 int Current digit in comparison

d2 int Next digit in comparison

sc Scanner For user input


Algorithm

1. START
2. Input number n.
3. If number has fewer than 3 digits → Not a Fascinating Number.
4. Compute:
on2 = n * 2
on3 = n * 3
5. Concatenate → concat = n + n2 + n3.
6. Check if concat contains all digits 1–9 exactly once.
7. If yes → Fascinating Number.
Else → Not Fascinating.
8. END

🔹 Java Program
import java.util.Scanner;

public class FascinatingNumber {

public static boolean isFascinating(int n) {


if (n < 100) return false; // must be at least 3 digits

int n2 = n * 2;
int n3 = n * 3;

String concat = "" + n + n2 + n3;

// Check digits 1–9


for (char ch = '1'; ch <= '9'; ch++) {
if (concat.indexOf(ch) == -1) return false; // missing digit
}

// Also check that digits are unique (no repeats for 1–9)
for (int i = 0; i < concat.length(); i++) {
char c = concat.charAt(i);
if (c >= '1' && c <= '9') {
if (concat.indexOf(c) != concat.lastIndexOf(c))
return false;
}
}
return true;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");


int num = sc.nextInt();
if (isFascinating(num))
System.out.println(num + " is a Fascinating Number");
else
System.out.println(num + " is NOT a Fascinating Number");

sc.close();
}
}

Variable Description
Variable Data Type Description

n int Input number to check

n2 int Twice the number (n*2)

n3 int Thrice the number (n*3)

concat String Concatenated result of n + n2 + n3

ch char Each digit (1–9) being checked in string

c char Character at current index in loop

sc Scanner For user input


Algorithm

1. START
2. Input size of matrix (m, n) and matrix elements.
3. Extract all non-boundary elements into a list.
4. Sort the list.
5. Replace sorted elements back into their non-boundary positions.
6. Display final matrix.
7. END

Java Program
import java.util.*;

public class SortNonBoundaryMatrix {


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

// Input dimensions
System.out.print("Enter rows: ");
int m = sc.nextInt();
System.out.print("Enter columns: ");
int n = sc.nextInt();

int[][] matrix = new int[m][n];

// Input matrix
System.out.println("Enter matrix elements:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = sc.nextInt();
}
}

// Step 1: Collect non-boundary elements


ArrayList<Integer> nonBoundary = new ArrayList<>();
for (int i = 1; i < m - 1; i++) {
for (int j = 1; j < n - 1; j++) {
nonBoundary.add(matrix[i][j]);
}
}

// Step 2: Sort non-boundary elements


Collections.sort(nonBoundary);

// Step 3: Put sorted elements back


int index = 0;
for (int i = 1; i < m - 1; i++) {
for (int j = 1; j < n - 1; j++) {
matrix[i][j] = nonBoundary.get(index++);
}
}

// Step 4: Print final matrix


System.out.println("Matrix after sorting non-boundary elements:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}

sc.close();
}
}

Variable Description
Variable Data Type Description

m int Number of rows in matrix

n int Number of columns in matrix

matrix int[][] 2D array to store matrix

nonBoundary ArrayList Stores non-boundary elements for sorting

index int Iterator to insert sorted values back

i, j int Loop variables for matrix traversal

sc Scanner For user input


Algorithm
1. START
2. Input the first sentence.
3. Input the second sentence.
4. Split both sentences into words.
5. Compare each word of the first sentence with each word of the second sentence.
6. If the words are equal, print the word as a common word (avoid duplicates).
7. If no common words are found, display a suitable message.
8. END

Program (Java)
import java.util.*;

public class CommonWords {


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

// Input sentences
System.out.println("Enter first sentence: ");
String s1 = sc.nextLine();
System.out.println("Enter second sentence: ");
String s2 = sc.nextLine();

// Split into words


String[] words1 = s1.split("\\s+");
String[] words2 = s2.split("\\s+");

// Use a set to avoid duplicates


HashSet<String> common = new HashSet<>();

// Compare words
for (String w1 : words1) {
for (String w2 : words2) {
if (w1.equalsIgnoreCase(w2)) {
common.add(w1.toLowerCase());
}
}
}

// Display results
if (common.isEmpty()) {
System.out.println("No common words found.");
} else {
System.out.println("Common words: " + common);
}
}
}
Variable Description
Variable Name Data Type Description (Purpose)
sc Scanner To take input from user
s1 String Stores the first sentence
s2 String Stores the second sentence
words1 String[] Stores words of the first sentence
words2 String[] Stores words of the second sentence
common HashSet<String> Stores unique common words between both sentences
w1, w2 String Temporary variables used in comparison
Algorithm
1. START
2. Input the upper limit n.
3. For each number p from 2 to n:
o Check if (p, p+2, p+6) are all prime → print triplet.
o Else check if (p, p+4, p+6) are all prime → print triplet.
4. Repeat until all numbers up to n are checked.
5. END

Program (Java)
import java.util.*;

public class PrimeTriplets {


// Function to check if number is prime
static boolean isPrime(int num) {
if (num < 2) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Input upper limit


System.out.print("Enter upper limit: ");
int n = sc.nextInt();

System.out.println("Prime Triplets up to " + n + ":");


for (int p = 2; p <= n - 6; p++) {
if (isPrime(p) && isPrime(p+2) && isPrime(p+6)) {
System.out.println("(" + p + ", " + (p+2) + ", " + (p+6) +
")");
}
else if (isPrime(p) && isPrime(p+4) && isPrime(p+6)) {
System.out.println("(" + p + ", " + (p+4) + ", " + (p+6) +
")");
}
}
}
}
Variable Description
Variable Name Data Type Description
sc Scanner Used for input
n int Upper limit for checking triplets
p int Candidate starting prime number
isPrime() boolean function Checks if a number is prime
Algorithm
1. START
2. Input the matrix dimensions m (rows) and n (columns).
3. Input the matrix elements.
4. For each row i:
o Store the last element matrix[i][n-1] in a temporary variable.
o Shift all elements of the row one step to the right.
o Place the temporary element in the first column of that row.
5. Print the rotated matrix.
6. END

Program (Java)
import java.util.*;

public class RotateMatrixRows {


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

// Input matrix dimensions


System.out.print("Enter number of rows: ");
int m = sc.nextInt();
System.out.print("Enter number of columns: ");
int n = sc.nextInt();

int[][] matrix = new int[m][n];

// Input matrix
System.out.println("Enter matrix elements:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = sc.nextInt();
}
}

// Rotate each row by shifting right


for (int i = 0; i < m; i++) {
int temp = matrix[i][n - 1]; // last element
for (int j = n - 1; j > 0; j--) {
matrix[i][j] = matrix[i][j - 1];
}
matrix[i][0] = temp; // put last element at first position
}

// Print rotated matrix


System.out.println("Matrix after rotating rows:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

Variable Description
Variable Name Data Type Description
sc Scanner For taking input
m int Number of rows
n int Number of columns
matrix int[][] 2D array to store the matrix
i, j int Loop counters for rows and columns
temp int Temporary variable to store last element of row before shifting
Algorithm
1. START
2. Input the sentence.
3. Convert the sentence to lowercase (for case-insensitivity).
4. Create a boolean array present[26] initialized as false.
5. Traverse each character ch in the sentence:
o If ch is a letter (a–z), mark present[ch - 'a'] = true.
6. After traversal, check if all 26 positions in present[] are true.
o If yes → the sentence is a pangram.
o Otherwise → it is not a pangram.
7. Print the result.
8. END

Program (Java)
import java.util.*;

public class PangramCheck {


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

// Input sentence
System.out.println("Enter a sentence:");
String sentence = sc.nextLine().toLowerCase();

boolean[] present = new boolean[26];

// Mark letters present


for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch >= 'a' && ch <= 'z') {
present[ch - 'a'] = true;
}
}

// Check if all letters present


boolean isPangram = true;
for (int i = 0; i < 26; i++) {
if (!present[i]) {
isPangram = false;
break;
}
}

// Output
if (isPangram) {
System.out.println("The sentence is a Pangram.");
} else {
System.out.println("The sentence is NOT a Pangram.");
}
}
}
Variable Description
Variable Name Data Type Description
sc Scanner To take input sentence
sentence String Stores the input sentence (converted to lowercase)
present boolean[] Array of size 26, tracks whether each alphabet letter is present
i int Loop counter for traversing the sentence
ch char Current character being checked
isPangram boolean Stores final result (true if pangram, false otherwise)
Algorithm
1. START
2. Input the sentence.
3. Input the word to delete.
4. Split the sentence into words using space " " as the delimiter.
5. Traverse each word:
o If it is not equal to the word to delete, keep it in the result.
o Otherwise, skip it.
6. Join the remaining words back into a sentence.
7. Print the new sentence.
8. END

Program (Java)
import java.util.*;

public class DeleteWord {


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

// Input sentence
System.out.println("Enter a sentence:");
String sentence = sc.nextLine();

// Input word to delete


System.out.println("Enter the word to delete:");
String word = sc.next();

// Split sentence into words


String[] words = sentence.split(" ");
StringBuilder result = new StringBuilder();

// Check each word


for (String w : words) {
if (!w.equals(word)) { // Skip the word to delete
result.append(w).append(" ");
}
}

// Output final sentence


System.out.println("Sentence after deletion:");
System.out.println(result.toString().trim());
}
}
Variable Description
Variable Name Data Type Description
sc Scanner To take input from user
sentence String Stores the input sentence
word String Stores the word to be deleted
words String[] Array of words obtained from splitting the sentence
result StringBuilder Stores the modified sentence after deletion
w String Current word being checked in the loop
Algorithm
1. START
2. Input the sentence.
3. Input the word to insert.
4. Input the position (index) after which the word should be inserted.
o Example: Position = 2 → insert word after the 2nd word.
5. Split the sentence into words using " " as the delimiter.
6. Traverse each word:
o Copy the current word into the result.
o If the current index matches the position, insert the new word.
7. Join the modified list of words into a final sentence.
8. Print the updated sentence.
9. END

Program (Java)
import java.util.*;

public class InsertWord {


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

// Input sentence
System.out.println("Enter a sentence:");
String sentence = sc.nextLine();

// Input word to insert


System.out.println("Enter the word to insert:");
String newWord = sc.next();

// Input position
System.out.println("Enter the position (after which word to
insert):");
int pos = sc.nextInt();

// Split sentence into words


String[] words = sentence.split(" ");
StringBuilder result = new StringBuilder();

// Traverse words and insert


for (int i = 0; i < words.length; i++) {
result.append(words[i]).append(" ");
if (i == pos - 1) { // Insert after the given position
result.append(newWord).append(" ");
}
}

// Output final sentence


System.out.println("Sentence after insertion:");
System.out.println(result.toString().trim());
}
}
Variable Description
Variable Name Data Type Description
sc Scanner To take input from user
sentence String Stores the input sentence
newWord String Stores the word to be inserted
pos int Position after which the word is inserted
words String[] Array of words obtained from splitting the sentence
result StringBuilder Stores the modified sentence after insertion
i int Loop counter for traversing the words
Algorithm
1. START
2. Input the sentence from the user.
3. Split the sentence into words using " " as a delimiter.
4. For each word in the list:
o Convert the word to lowercase (for uniformity).
o Check if the first character is a vowel ( a, e, i, o, u).
o Check if the last character is also a vowel.
o If both conditions are satisfied, print the word.
5. If no such word exists, print "No word found".
6. END

Program (Java)
import java.util.*;

public class VowelWord {


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

// Input sentence
System.out.println("Enter a sentence:");
String sentence = sc.nextLine();

// Split into words


String[] words = sentence.split(" ");
boolean found = false;

// Check each word


for (String word : words) {
String lw = word.toLowerCase(); // convert to lowercase
if (lw.length() > 0) {
char first = lw.charAt(0);
char last = lw.charAt(lw.length() - 1);

if (isVowel(first) && isVowel(last)) {


System.out.println(word);
found = true;
}
}
}

if (!found) {
System.out.println("No word begins and ends with a vowel.");
}
}

// Function to check vowel


public static boolean isVowel(char ch) {
return "aeiou".indexOf(ch) != -1;
}
}
Variable Description
Variable Name Data Type Description
sc Scanner To take user input
sentence String Stores the input sentence
words String[] Array of words obtained from splitting the sentence
found boolean Flag to check if at least one valid word is found
word String Current word being checked
lw String Lowercase version of the current word
first char First character of the word
last char Last character of the word
isVowel() Method Checks if a character is a vowel

You might also like