Computer Science Record
I. Java Fundamentals and Number
Programs
1. Right Angled Pattern Printer
Outline:
Prints a pattern(”*”) forming a right angled triangle when given the number of
rows to print from the user.
Algorithm:
a. Display message for user to input number of rows and store the integer
value(n)
b. . outer loop (controls rows)
Run a loop from i = 1 to n.
c. inner loop (controls columns)
For each row i, run another loop from j = 1 to i.
Print without moving to a new line.
d. move to next line
After printing all for the current row, move to the next line
e. Continue until n rows are printed.
Code:
import java.util.*;
public class Pattern1 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter number of rows:");
int n=input.nextInt();
for(int i=1;i<=n;i++){
Computer Science Record 1
for(int j=1;j<=i;j++){
System.out.print("*");
}
System.out.println("");
}
}
Input/Output:
Output: Enter number of rows:
Input: 5
Output:
*
**
***
****
*****
2. Inverted Right Angled Pattern Printer
Outline:
Prints a pattern(”*”) forming a inverted right angled triangle when given the
number of rows to print from the user.
Algorithm:
Computer Science Record 2
a. Display a message for the user to input the number of rows and store the
integer value (n).
b. outer loop (controls rows)
Run a loop from i = 1 to n.
c. inner loop 1 (prints stars)
Run a loop from j = n to i (decreasing).
Print without moving to a new line.
d. Print a newline to move to the next row.
e. inner loop 2 (prints spaces)
Run a loop from k = 1 to i.
Print a space " " without moving to a new line.
f. Continue until n rows are printed.
Code:
import java.util.*;
public class Pattern2 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter number of rows:");
int n=input.nextInt();
for(int i=1;i<=n;i++){
for(int j=n;j>=i;j--){
System.out.print("*");
}
System.out.println("");
for(int k=1;k<=i;k++){
System.out.print(" ");
}
}
}
Computer Science Record 3
Input/Output:
Output: Enter number of rows:
Input: 5
Output:
*****
****
***
**
*
3. Prime Number Checker
Outline:
Checks whether given number is a prime number or composite number.
Algorithm:
a. Display a message for the user to input a number and store the integer
value (n).
b. initialize factor counter
Set fac = 0 to count the number of factors of n.
c. loop to count factors
Run a loop from i = 1 to n.
If n is divisible by i, increase fac by 1.
d. check if the number is prime, composite, or neither
If fac == 2, print that n is a prime number.
Else, if n == 1, print that 1 is not a prime number.
Otherwise, print that n is a composite number.
Code:
Computer Science Record 4
import java.util.Scanner;
public class PrimeNos {
public static void main(String[] args) {
System.out.println("Enter a number:");
Scanner monkey =new Scanner(System.in);
int n=monkey.nextInt();
int fac=0; //factors if more than 2 then it is prime
int i;
for(i=1;i<=n;i++){
if(n%i==0)
fac=fac+1;
}
if(fac==2)
System.out.println(n+" is a prime number");
else if (n==1)
System.out.print("1 is not a prime number");
else
System.out.println(n+" is a composite number");
}
}
Input/Output:
Output: Enter a number.
Input: 9
Output: 9 is a composite number
4. Simple Calculator
Computer Science Record 5
Outline:
Calculates arithmetic operations( addition, subtraction, multiply and division)
between two numbers given by the user.
Algorithm:
a. Display a menu with four operations: Addition, Subtraction, Multiplication,
and Division.
b. Prompt the user to enter the number corresponding to the desired
operation and store it as n.
c. Ask the user to enter the first number and store it as a.
d. Ask the user to enter the second number and store it as b.
e. perform the selected operation using a switch case
If n == 1, call the add(a, b) function and print the sum.
If n == 2, call the sub(a, b) function and print the difference.
If n == 3, call the multi(a, b) function and print the product.
If n == 4, call the div(a, b) function and print the quotient and remainder.
Code:
import java.util.*;
public class JavaApplication2 {
public static void add(int a,int b){
System.out.println("The answer is "+a+b);
}
public static void sub(int a,int b){
System.out.println("The answer is "+(a-b));
}
public static void multi(int a,int b){
System.out.println("The answer is "+a*b);
}
public static void div(int a,int b){
int q=a/b;
int r=a%b;
Computer Science Record 6
System.out.println("Quotient"+q);
System.out.println("reminder"+r);
}
public static void main(String[] args) {
Scanner monkey =new Scanner(System.in);
System.out.println("Menu");
System.out.println("1.Addition");
System.out.println("2.Subtraction");
System.out.println("3.Multiplication");
System.out.println("4.Division");
System.out.println("Enter the number of the operati
on you want to use");
int n=monkey.nextInt();
System.out.println("Enter the 1st number you want
to operate");
int a=monkey.nextInt();
System.out.println("Enter the 2nd number you want
to operate");
int b=monkey.nextInt();
switch(n){
case 1:JavaApplication2.add(a,b);
break;
case 2:JavaApplication2.sub(a,b);
break;
case 3:JavaApplication2.multi(a,b);
break;
case 4:JavaApplication2.div(a,b);
break;
}
}
}
Input/Output:
Output:
Menu
1.Addition
2.Subtraction
3.Multiplication
Computer Science Record 7
4.Division
Enter the number of the operation you want to use
Input: 4
Output: Enter the 1st number you want to operate
Input: 12
Output: Enter the 2nd number you want to operate
Input: 2
Output: Quotient:6
reminder:0
5. Crazy Number Checker
Outline:
The program defines a function isCrazyNumber() to check if a number which
the user inputs, is equal to the sum of its digits each raised to the power of the
number of digits.
Algorithm:
a. Ask the user to enter a positive number.
b. Define a function isCrazyNumber() to check if a number is a Crazy number:
If the number is less than or equal to 0, return false.
Calculate the number of digits in the number.
Initialize a variable sum to 0.
Loop through each digit of the number
Raise each digit to the power of the number of digits and add to sum.
If the sum equals the original number, return true; otherwise, return
false.
c. Call the function isCrazyNumber() with the user input.
Computer Science Record 8
d. Display the result:
If the number is a Crazy number, print that it is a Crazy number.
Otherwise, print that it is not a Crazy number.
Code:
import java.util.Scanner;
class CrazyNumberChecker{
public static boolean crzChecker(int n){
int temp= n, pow= 0; double sum= 0;
while(temp> 0){
temp= temp/ 10;
pow++;
}
temp= n;
while(temp> 0){
int digit= temp%10;
sum= sum +(Math.pow(digit, pow));
temp= temp/10;
pow--; }
if(n==sum){
return true;
}
else{
return false;
}
}
public static void main(String[] args){
Scanner monkey =new Scanner(System.in);
System.out.print("Enter the number to check whethe
r it is a Crazy number or not+ : ");
int n= monkey.nextInt();
if(crzChecker(n)==true){
System.out.println("it is a crazy number");
}
else{ System.out.println("it is not a crazy numbe
Computer Science Record 9
r.");
}
}
}
Input/Output:
Output: Enter the number to check whether it is a Crazy number or not:
Input: 89
Output: it is a crazy number
6. Floyd’s Triangle
Outline:
1. Prints the program prints Floyd's Triangle, a triangular arrangement of
numbers where the numbers get incremented by one from top to bottom.
The user inputs the number rows needed to generate.
Algorithm:
a. Ask the user to enter the number of rows to print the triangle (n).
b. Initialize a variable count = 1 to keep track of the next number to be printed.
c. Outer loop (controls rows)
Run a loop from i = 0 to n - 1 to print n rows.
d. Inner loop (controls columns)
For each row i, run another loop from j = 0 to i to print i + 1 numbers in
each row.
Print the value of count, then increment count by 1.
e. After printing each row, move to the next line.
Code:
Computer Science Record 10
import java.util.Scanner;
class FloydsTriangle {
public static void main(String[] args) {
Scanner monkey= new Scanner(System.in);
System.out.println("Floyd's Triangle");
System.out.print("Enter the number of rows to print
: ");
int n= monkey.nextInt();
System.out.println();
long count= 1;
for(int i= 0; i<n; i++){
for(int j=0; j<=i;j++){
System.out.print(count+" ");
count++;
}
System.out.println();
}
}
}
Input/Output:
Output:
Floyd’s Triangle
Enter the number of rows to print :
Input: 5
Output:
1
23
456
7 8 9 10
11 12 13 14 15
II. String Programs
Computer Science Record 11
7. Anagram Checker
Outline:
Checks whether two words are anagrams (words formed by rearranging the
letters of another word) by using a recursive method.
Algorithm:
a. Start the program and take two inputs.
b. Check if the lengths of the two strings are equal.
If not, print false and stop.
c. If both strings are empty (base case), print true and stop.
d. Take the first character from the first string.
e. Find the position of this character in the second string.
f. If the character is not found, print false and stop.
g. Remove the first character from the first string and the found character from
the second string.
h. If the base case has not been reached, go back to step d.
i. After reaching the base case, print true (all characters matched) and stop.
Code:
import java.util.Scanner;
public class JavaApplication2 {
public static boolean Anagram(String s, String t) {
// Base case: if lengths are unequal, not an anagra
m
if (s.length() != t.length()) {
return false;
}
// Base case: if one string is empty, anagram confi
rmed
if (s.length() == 0) {
Computer Science Record 12
return true;
}
// Find the index of the first character of s in t
int i = t.indexOf(s.charAt(0));
// If the character is not found in t, not an anagr
am
if (i < 0) {
return false;
}
// Recursively check remaining characters
return Anagram(
s.substring(1),
t.substring(0, i) + t.substring(i + 1)
);
}
public static void main(String[] args) {
// Create a Scanner object named "monkey"
Scanner monkey = new Scanner(System.in);
// Prompt the user for input
System.out.println("Enter the first string:");
String s = monkey.nextLine();
System.out.println("Enter the second string:");
String t = monkey.nextLine();
// Check if the strings are anagrams
boolean result = Anagram(s, t);
// Print the result
if (result) {
System.out.println("The strings \"" + s + "\" a
nd \"" + t + "\" are anagrams.");
} else {
Computer Science Record 13
System.out.println("The strings \"" + s + "\" a
nd \"" + t + "\" are NOT anagrams.");
}
}
}
Input/Output:
Output: Enter the first string:
Input: seat
Output: Enter the second string:
Input: eats
Output: The strings "seat" and "eats" are anagrams.
8. Palindrome Checker
Outline:
Checks whether a string is a palindrome or not by reversing and verifiying
whether its true or not.
Algorithm:
a. Input Acquisition:
Ask the user to enter a word/phrase.
Read the input string.
b. Normalization:
Convert the string to lowercase (case-insensitive check).
Remove non-alphanumeric characters (optional, for phrase checks).
c. Initialize Indices:
Computer Science Record 14
Let a = 0 (starting index).
Let b = length of string - 1 (ending index).
d. Character Comparison Loop:
While a < b:
If character at a ≠ character at b:
Terminate: Not a palindrome.
Increment a (a++).
Decrement b (b--).
e. Result:
If all characters match, declare the string a palindrome
Code:
import java.util.Scanner;
public class LetterCounter{
public static void main(String[] args) {
Scanner monkey = new Scanner(System.in); // Scanner
object
System.out.print("Enter a word to check if it's a p
alindrome: ");
String word = monkey.nextLine(); // Take input
word = word.toLowerCase(); // Convert to lowercase
for case-insensitive check
// Reverse the word
StringBuilder sb = new StringBuilder(word);
sb.reverse();
String reversed = sb.toString();
// Check if the word is a palindrome
if (word.equals(reversed)) {
System.out.println(word + " is a palindrome.");
Computer Science Record 15
} else {
System.out.println(word + " is not a palindrom
e.");
}
}
}
Input/Output:
Output: Enter a word to check if it's a palindrome:
Input: racecar
Output: racecar is a palindrome.
9. Lowercase to Uppercase Converter
Outline:
Converts lowercase characters to uppercase using ASCII values.
Algorithm:
a. Prompt the user to enter a string.
b. String Processing:
Initialize a StringBuilder to build the modified string.
Loop through each character in the input:
Convert the character to uppercase using ASCII logic).
Append the uppercase character to the StringBuilder.
c. Print the fully uppercase string.
Code:
Computer Science Record 16
import java.util.Scanner;
public class AsciiUppercaseConverter {
public static void main(String[] args) {
Scanner monkey = new Scanner(System.in);
System.out.print("Enter a string to make the charac
ters in it uppercase: ");
String input = monkey.nextLine();
StringBuilder result = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
// Convert lowercase 'a-z' to uppercase using A
SCII
if (c >= 97 && c <= 122) { // Check if lowerca
se
result.append((char) (c - 32)); // Convert
to uppercase
} else {
result.append(c); // Keep non-lowercase ch
aracters
}
}
System.out.println("Uppercase string: " + result);
}
}
Input/Output:
Output: Enter a string to make the characters in it uppercase:
Input: trees
Output: Uppercase string: TREES
Computer Science Record 17
10. Word Counter
Outline:
Counts the number of words in a given string( given by the user) by using
StringTokenizer.
Algorithm:
a. Prompt the user to enter a sentence.
b. Tokenization:
Use StringTokenizer to split the string into tokens.
Delimiters: , .?!*&^#$% (comma, space, period, and other specified
symbols).
c. Count the tokens generated by StringTokenizer.
d. Print the token count as the number of words.
Code:
import java.util.Scanner;
import java.util.StringTokenizer;
public class LetterCounter {
public static int count(String s) {
StringTokenizer stk = new StringTokenizer(s, ", .?!
*&^#$%");
int count = stk.countTokens();
return count;
}
public static void main(String[]args) {
Scanner monkey = new Scanner(System.in);
System.out.println("Enter a sentence to check numbe
r of words");
Computer Science Record 18
String s = monkey.nextLine();
int result = count(s);
System.out.println("Number of Words: " + result);
}
Input/Output:
Output: Enter a sentence to check number of words
Input: Its getting very late at night
Output: Number of Words: 6
III. Array Problems
11. Bubble Sort
Outline:
Sorts an array of numbers from least to greatest using Bubble Sort technique.
Algorithm:
a. Ask the user to enter the size of the array.
b. Read the array elements from the user.
c. Bubble Sort:
For each pass through the array:
Compare adjacent elements.
Swap them if they are in the wrong order.
d. Print the sorted array.
Computer Science Record 19
Code:
import java.util.Scanner;
public class BubbleSort {
public static void main(String[] args) {
Scanner monkey = new Scanner(System.in);
// Step 1: Get array size from the user
System.out.print("Enter the size of the array: ");
int n = monkey.nextInt();
// Initialize the array
int[] arr = new int[n];
// Step 2: Get array elements from the user
System.out.println("Enter " + n + " elements:");
for (int i = 0; i < n; i++) {
arr[i] = monkey.nextInt();
}
// Step 3: Bubble Sort
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
// Swap adjacent elements if they are in th
e wrong order
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Step 4: Print the sorted array
System.out.print("Sorted Array: ");
for (int num : arr) {
Computer Science Record 20
System.out.print(num + " ");
}
}
}
Input/Output
Output: Enter the size of the array:
Input: 5
Output: Enter 5 elements:
Input: 8 5 6 7 9
Output: Sorted Array: 5 6 7 8 9
12. Insertion Sort
Outline:
Sorts an array of numbers from least to greatest using Insertion Sort technique.
Algorithm:
a. Ask the user to enter the size of the array.
b. Read the array elements from the user.
c. Outer Loop:
Iterate i from 1 to n-1 (elements from index 1 onward are considered
"unsorted").
d. Store the current element a[i] as key to be inserted into the sorted subarray.
e. Inner Loop:
Initialize j = i - 1 (start comparing with the previous element in the sorted
subarray).
While j >= 0 and a[j] > key:
Computer Science Record 21
Shift a[j] to the right (a[j + 1] = a[j]).
Decrement j to check the next left element.
f. Place key into its correct position at a[j + 1].
g. Print the new sorted array.
Code:
import java.util.Scanner;
public class InsertionSort {
public static void main(String[] args) {
Scanner monkey = new Scanner(System.in);
// Get array input from user
System.out.print("Enter the size of the array: ");
int n = monkey.nextInt();
int[] a = new int[n];
System.out.println("Enter " + n + " elements:");
for (int i = 0; i < n; i++) {
a[i] = monkey.nextInt();
}
// Insertion Sort Algorithm
for (int i = 1; i < n; i++) {
int key = a[i]; // Current element to insert
int j = i - 1;
// Shift elements greater than `key` to the rig
ht
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = key; // Insert `key` in correct posi
tion
Computer Science Record 22
}
// Print sorted array
System.out.print("Sorted Array: ");
for (int num : a) {
System.out.print(num + " ");
}
}
}
Input/Output:
Output: Enter the size of the array:
Input: 5
Output: Enter 5 elements:
Input: 7 8 5 9 0
Output: Sorted Array: 0 5 7 8 9
13.
Digit Counter
Outline:
Finds the number of digits in a number given by the user using arrays.
Algorithm:
a. Prompt the user to enter an integer input (n).
b. Digit Counting:
Initialize a temporary variable t = n (to avoid modifying the original input).
Initialize a counter count = 0.
Computer Science Record 23
Loop: While t > 0:
Divide t by 10 (t = t / 10).
Increment count by 1.
This loop counts the number of digits in n (e.g., n = 123 → count = 3).
c. Create an integer array arr of size count.
d. Digit Extraction:
Reset t = n.
Initialize an index i = 0.
Loop: While i < arr.length:
Extract the last digit of t using modulo 10 (x = t % 10).
Store x in arr[i].
Update t by dividing it by 10 (t = t / 10).
Increment i by 1.
e. Print the number of digits (arr.length).
Code:
import java.util.Scanner;
public class DigitCounter {
public static void main(String[] args) {
Scanner monkey = new Scanner(System.in);
System.out.println("Enter a number whose digits you nee
d to count");
int n = monkey.nextInt();
int t = n;
int count = 0;
for(int i = 0; t>0; t=t/10) {
count++;
Computer Science Record 24
int[] arr = new int[count];
int i = 0;
t = n;
while(i<arr.length) {
int x = t%10;
arr[i] = x;
t = t/10;
i++;
}
System.out.println("The number of digits in the giv
en number: " + arr.length);
}
Input/Output:
Output: Enter a number whose digits you need to count:
Input: 476
Output: The number of digits in the given number: 3.
14. Letter Counter
Outline:
Counts the number of times a given character appears in a given string using
arrays.
Algorithm:
a. Input: Get string and target character from user
b. Convert: Change string into a character array
c. Initialize: Set counter to 0
d. Loop: Check every element in the array:
If element matches target, then increment counter
Computer Science Record 25
e. Output: Display final count
Code:
import java.util.Scanner;
public class LetterCounter {
public static void main(String[] args) {
Scanner monkey = new Scanner(System.in);
// Get user input
System.out.print("Enter a string: ");
String input = monkey.nextLine();
System.out.print("Enter letter to count: ");
char target = monkey.nextLine().charAt(0);
// Convert string to character array
char[] characters = input.toCharArray();
// Count occurrences
int count = 0;
for(char c : characters) {
if(c == target) {
count++;
}
}
System.out.println("The character '" + target + "'
appears " + count + " times.");
}
}
Input/Output:
Output: Enter a string:
Computer Science Record 26
Input: banana
Output: Enter letter to count:
Input: a
Output: The character 'a' appears 3 times.
15. Sentence Reverser
Outline:
This program reads a sentence, splits it into words, reverses the word order,
and reconstructs/prints the sentence with words in the reverse sequence of
words.
Algorithm:
a. Get a sentence from the user.
b. Break the sentence into an array of words using spaces as delimiters.
c. Create a new array and fill it by taking words from the original array in
reverse order.
For index i, use words[words.length - 1 - i] to reverse the sequence.
d. Join the reversed words into a single string with spaces.
e. Print the reversed sentence.
Code:
import java.util.*;
public class SentenceReverser {
public static void main(String[] args) {
Scanner monkey=new Scanner(System.in);
System.out.println("Enter a sentence:");
String input = monkey.nextLine();
String[] words =input.split(" ");
Computer Science Record 27
String[] reversedWords = new String[words.lengt
h];
for (int i = 0; i < words.length; i++) {
reversedWords[i] = words[words.length - 1 - i];
}
String reversedSentence = String.join(" ", reversed
Words);
System.out.println("Reversed sentence:");
System.out.println(reversedSentence);
}
}
Input/Output:
Output: Enter a sentence:
Input: Sports cars are fast
Output: Reversed sentence:
Input: fast are cars Sports
IV.
Recursion Problems
16. Factorial
Outline:
Takes user input for a non-negative integer, verifies it, and then
calculates/prints its factorial using recursions.
Algorithm:
a. Prompt the user to enter a non-negative integer.
b. Validate the input:
Computer Science Record 28
If the number is negative, print an error message.
If valid, proceed to calculate the factorial.
c. Recursive Factorial Calculation:
Base Case :
If n == 0 or n == 1, return 1 (since 0!=1!=1).
d. Recursive Step:
For n>1, compute n!=n×(n−1)
e. Print the computed factorial value.
Code:
import java.util.Scanner;
public class FactorialCalculator {
public static void main(String[] args) {
Scanner monkey = new Scanner(System.in);
System.out.print("Enter a non-negative integer: ");
int number = monkey.nextInt();
if (number < 0) {
System.out.println("Error: Negative numbers are
not allowed.");
} else {
System.out.println("Factorial of " + number + "
is " + factorial(number));
}
}
public static long factorial(int n) {
return (n <= 1) ? 1 : n * factorial(n - 1); // Base
case: 0! = 1! = 1
}
}
Input/Output:
Computer Science Record 29
Output: Enter a non-negative integer:
Input: 5
Output: Factorial of 5 is 120
17. Sum of Digits
Outline:
Calculates the sum of each digits of a given number using recursions.
Algorithm:
1. Get an integer input from the user.
2. Base Case:
If n == 0, return 0 (no digits left to process).
3. Recursive Step:
Extract the last digit using n % 10.
Add it to the sum of the remaining digits (sumdig(n / 10)).
4. Recursively reduce n by removing the last digit (n / 10) until n becomes 0.
5. Print the total sum of the digits.
Code:
import java.util.*;
public class SumDigits {
public static int sumdig(int n){
if (n == 0) {
return 0;
}
return (n%10)+sumdig(n/10);
}
public static void main(String[] args) {
Computer Science Record 30
Scanner monkey = new Scanner(System.in);
System.out.print("Enter a number: ");
int input= monkey.nextInt();
int output=sumdig(input);
System.out.println("The sum of the digits of the gi
ven number is "+output+".");
}
}
Input/Output:
Output: Enter a number:
Input: 123
Output: The sum of the digits of the given number is 6.
18. Fibonacci Sequence
Outline:
To print the first ‘n’ number of numbers in a Fibonacci sequence using
recursive technique.
Algorithm:
a. Ask the user to enter the number of terms (n) using a Scanner.
b. Use a for loop from 0 to n-1.
For each iteration, calculate the Fibonacci number using the recursive
fibonacci() method:
Base Case: Return n if n <= 1.
Recursive Case: Return the sum of fibonacci(n-1) and fibonacci(n-2).
Base Case: Return n if n <= 1.
Recursive Case: Return the sum of fibonacci(n-1) and fibonacci(n-2).
c. Print each calculated Fibonacci number separated by a space.
Computer Science Record 31
Code:
import java.util.Scanner;
public class FibRecPrinter
{public static void main(String[] args) {
System.out.println("Enter number of terms in the Fibona
cci Sequence to print");
Scanner monkey = new Scanner(System.in);
int n = monkey.nextInt();
System.out.println("Fibonacci series up to " + n + " ter
ms:");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
// Recursive method to find the nth Fibonacci number
public static int fibonacci(int n) {
if (n <= 1) { // Base cases: F(0) = 0, F(1) = 1
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2); // Recursiv
e formula
}
Input/Output:
Output: Enter number of terms in the Fibonacci Sequence to print
Input: 5
Output: 0 1 1 2 3
Computer Science Record 32
19. Palindrome Checker
Outline:
Checks whether a given string is a palindrome or not using recursions.
Algorithm:
a. Ask the user to enter a string.
trim the input (removes leading/trailing whitespace).
b. Base Case Check :
If the string length is 0 or 1, return true (empty string or single character
is a palindrome).
c. Character Comparison:
Compare the first and last characters of the string.
If they do not match, return false (not a palindrome).
d. Recursive Step:
Remove the first and last characters of the string.
Recurse on the substring
e. Repeat steps 2–4 until the base case is reached or a mismatch is found.
f. Print whether the input string is a palindrome.
Code:
import java.util.Scanner;
public class LetterCounter{
// Recursive palindrome check method
public static boolean isPalindrome(String s) {
if (s.length() <= 1) {
return true; // Base case: empty or single-char
acter string
}
if (s.charAt(0) != s.charAt(s.length() - 1)) {
Computer Science Record 33
return false; // First/last characters mismatch
}
return isPalindrome(s.substring(1, s.length() -
1)); // Recurse with inner substring
}
public static void main(String[] args) {
Scanner monkey= new Scanner(System.in);
System.out.print("Enter a string to check for palin
drome: ");
String input = monkey.nextLine().trim(); // Read an
d trim input
boolean result = isPalindrome(input);
System.out.println("The word: '" + input + "' is "
+
(result ? "" : "NOT ") + "a palin
drome.");
}
}
Input/Output:
Output: Enter a string to check for palindrome:
Input: banana
Output: The word: 'banana' is NOT a palindrome.
20. Power of Numbers
Outline:
This code computes x to the power y using iterative multiplication for positive
exponents or reciprocal results for negatives, calculating user-input integers by
using recursions.
Algorithm:
Computer Science Record 34
1. Accept integer inputs for base (x) and exponent (y).
2. Check Exponent Sign:
Case 1: Positive Exponent (y>0y>0)
Initialize result = 1.
Multiply result by x exactly y times (iterative loop).
return result.
Case 2: Non-Positive Exponent (y≤0)
Compute absolute exponent: z= ∣ y∣ .
Initialize result = 1.
Multiply result by x exactly z times (iterative loop).
Return 1 /result.
Code:
import java.util.Scanner;
public class powercalc{
public static double powxy(int x, int y) {
if(y>0){
int pow = 1;
for (int i = 1; i <= y; i++) {
pow = pow * x;
}
return pow;
}
else {
int z = -y;
double pown= 1;
for (int i = 1; i <= z; i++) {
pown = pown * x;
Computer Science Record 35
}
return 1/pown;
}
}
public static void main(String[] args) {
Scanner monkey= new Scanner(System.in);
System.out.println("Enter base:");
int base = monkey.nextInt();
System.out.println("Enter exponent");
int exponent = monkey.nextInt();
double result = powxy(base, exponent);
System.out.println(base+"^"+ exponent + " is " + re
sult);
}
}
Input/Output:
Output: Enter base:
Input: 2
Output: Enter exponent
Input: -3
Output: 2^-3 is 0.125
Computer Science Record 36