MERU UNIVERSITY OF SCIENCE AND TECHNOLOGY
UNIT: OOP2 CIT3203
NAME:DERICK KARIUKI MURIUKI
REG NO:CT205/104966/20
6.2(Sum the digits in an integer) Write a method that computes the sum of the digits in an integer.
Use the following method header:
public static int sumDigits(long n)
For example, sumDigits(234) returns 9 (= 2 + 3 + 4). (Hint: Use the % opera tor to extract digits and the
/operator to remove the extracted digit. For instance, to extract 4 from 234, use 234 % 10 (= 4). To
remove 4 from 234, use 234 / 10 (= 23). Use a loop to repeatedly extract and remove the digit until all
the digits are extracted. Write a test program that prompts the user to enter an integer then displays
the sum of all its digits.
import java.util.Scanner;
public class SumOfDigits {
// Method to compute the sum of digits in an integer
public static int sumDigits(long n) {
int sum = 0;
// Loop to extract and sum each digit
while (n != 0) {
sum += n % 10; // Extract the last digit and add it to sum
n /= 10; // Remove the last digit
return sum;
}
public static void main(String[] args) {
// Create a Scanner object to get user input
Scanner input = new Scanner(System.in);
// Prompt the user to enter an integer
System.out.print("Enter an integer: ");
long number = input.nextLong();
// Call the sumDigits method and display the result
int result = sumDigits(number);
System.out.println("The sum of the digits is: " + result);
input.close(); // Close the Scanner
6.3 (Palindrome integer) Write the methods with the following headers
: // Return the reversal of an integer, e.g., reverse(456) returns 654 public static int reverse(int
number)
// Return true if number is a palindrome public static boolean isPalindrome(int number)
Use the reverse method to implement isPalindrome. A number is a palin drome if its reversal is the
same as itself. Write a test program that prompts the user to enter an integer and reports whether
the integer is a palindrome.
import java.util.Scanner;
public class PalindromeInteger {
// Method to reverse an integer
public static int reverse(int number) {
int reversed = 0;
// Loop to reverse the digits
while (number != 0) {
int digit = number % 10; // Extract the last digit
reversed = reversed * 10 + digit; // Append the digit to reversed
number /= 10; // Remove the last digit
return reversed;
// Method to check if the integer is a palindrome
public static boolean isPalindrome(int number) {
return number == reverse(number); // A number is a palindrome if it equals its reverse
public static void main(String[] args) {
// Create a Scanner object to get user input
Scanner input = new Scanner(System.in);
// Prompt the user to enter an integer
System.out.print("Enter an integer: ");
int number = input.nextInt();
// Call the isPalindrome method and display the result
if (isPalindrome(number)) {
System.out.println(number + " is a palindrome.");
} else {
System.out.println(number + " is not a palindrome.");
}
input.close(); // Close the Scanner
*6.7 (Financial application: compute the future investment value) Write a method that computes
future investment value at a given interest rate for a specified number of years. The future investment
is determined using the formula in Programming Exercise 2.21.
futureInvestmentValue =
investmentAmount * (1 + monthlyInterestRate)numberOfYears*12
For example, if you enter amount 1000, annual interest rate 3.25%, and number of years 1, the future
investment value is 1032.98.
import java.util.Scanner;
public class FutureInvestmentValue {
// Method to compute the future investment value
public static double futureInvestmentValue(double investmentAmount, double annualInterestRate,
int numberOfYears) {
// Convert annual interest rate to monthly interest rate
double monthlyInterestRate = annualInterestRate / 1200;
// Calculate future investment value using the formula
double futureValue = investmentAmount * Math.pow(1 + monthlyInterestRate, numberOfYears *
12);
return futureValue;
public static void main(String[] args) {
// Create a Scanner object to get user input
Scanner input = new Scanner(System.in);
// Prompt the user to enter the investment amount
System.out.print("Enter investment amount: ");
double investmentAmount = input.nextDouble();
// Prompt the user to enter the annual interest rate
System.out.print("Enter annual interest rate (e.g., 3.25 for 3.25%): ");
double annualInterestRate = input.nextDouble();
// Prompt the user to enter the number of years
System.out.print("Enter number of years: ");
int numberOfYears = input.nextInt();
// Call the method to calculate the future investment value
double futureValue = futureInvestmentValue(investmentAmount, annualInterestRate,
numberOfYears);
// Display the result, formatted to two decimal places
System.out.printf("Future investment value is: %.2f%n", futureValue);
input.close(); // Close the Scanner
*6.20 (Count the letters in a string) Write a method that counts the number of letters in a string using
the following header:
public static int countLetters(String s)
Write a test program that prompts the user to enter a string and displays the num ber of letters in the
string.
import java.util.Scanner;
public class LetterCount {
// Method to count the number of letters in a string
public static int countLetters(String s) {
int letterCount = 0;
// Loop through each character in the string
for (int i = 0; i < s.length(); i++) {
// Check if the character is a letter
if (Character.isLetter(s.charAt(i))) {
letterCount++; // Increment the counter if it is a letter
return letterCount;
public static void main(String[] args) {
// Create a Scanner object to get user input
Scanner input = new Scanner(System.in);
// Prompt the user to enter a string
System.out.print("Enter a string: ");
String userInput = input.nextLine();
// Call the countLetters method and display the result
int result = countLetters(userInput);
System.out.println("The number of letters in the string is: " + result);
input.close(); // Close the Scanner
**7.3 (Count occurrence of numbers) Write a program that reads the integers between 1 and 50 and
counts the occurrences of each. Assume the input ends with 0
import java.util.Scanner;
public class NumberOccurrenceCounter {
public static void main(String[] args) {
// Array to hold the count of numbers from 1 to 50 (index 0 to 49)
int[] counts = new int[50];
// Create a Scanner object to get user input
Scanner input = new Scanner(System.in);
// Prompt the user to enter numbers
System.out.println("Enter integers between 1 and 50 (0 to stop): ");
while (true) {
int number = input.nextInt();
// End input when user enters 0
if (number == 0) {
break;
}
// If the number is between 1 and 50, count it
if (number >= 1 && number <= 50) {
counts[number - 1]++; // Increment the count for this number
} else {
System.out.println("Invalid input, please enter a number between 1 and 50.");
// Display the occurrence of each number that was entered
System.out.println("Occurrences of each number:");
for (int i = 0; i < counts.length; i++) {
if (counts[i] > 0) {
System.out.println((i + 1) + " occurs " + counts[i] + " time" + (counts[i] > 1 ? "s" : ""));
input.close(); // Close the Scanner
7.8 (Average an array) Write two overloaded methods that return the average of an array with the
following headers:
public static int average(int[] array)
public static double average(double[] array)
Write a test program that prompts the user to enter 10 double values, invokes this method, then
displays the average value.
import java.util.Scanner;
public class AverageArray {
// Method to calculate the average of an integer array
public static int average(int[] array) {
int sum = 0;
for (int num : array) {
sum += num;
return sum / array.length;
// Method to calculate the average of a double array
public static double average(double[] array) {
double sum = 0;
for (double num : array) {
sum += num;
return sum / array.length;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Create an array of 10 doubles
double[] doubleArray = new double[10];
// Prompt the user to enter 10 double values
System.out.println("Enter 10 double values:");
for (int i = 0; i < doubleArray.length; i++) {
doubleArray[i] = input.nextDouble();
}
// Call the average method for doubles and display the result
double avg = average(doubleArray);
System.out.println("The average of the entered values is: " + avg);
input.close();
7.9 (Find the largest element) Write a method that finds the largest element in an array of double
values using the following header:
public static double max(double[] array)
public class FindMax {
// Method to find the largest element in an array of double values
public static double max(double[] array) {
double max = array[0]; // Initialize max with the first element of the array
// Loop through the array to find the largest element
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i]; // Update max if a larger value is found
return max; // Return the largest value found
public static void main(String[] args) {
// Example usage of the max method
double[] sampleArray = {1.5, 7.2, 3.8, 9.4, 2.1};
// Find and print the maximum value in the array
System.out.println("The maximum value is: " + max(sampleArray));
Write a test program that prompts the user to enter ten numbers, invokes this method to return the
maximum value, and displays the maximum value. Here is a sample run of the program:
import java.util.Scanner;
public class FindMaxElement {
// Method to find the maximum element in a double array
public static double max(double[] array) {
double max = array[0]; // Initialize max with the first element
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i]; // Update max if a larger value is found
return max;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Create an array of 10 doubles
double[] doubleArray = new double[10];
// Prompt the user to enter 10 double values
System.out.println("Enter 10 double values:");
for (int i = 0; i < doubleArray.length; i++) {
doubleArray[i] = input.nextDouble();
// Call the max method to find the largest element and display the result
double maximum = max(doubleArray);
System.out.println("The maximum value is: " + maximum);
input.close();
7.14 (Computing lcm) Write a method that returns the lcm (least common multiple) of an unspecified
number of integers. The method header is specified as follows:
public static int lcm(int... numbers)
Write a test program that prompts the user to enter five numbers, invokes the method to find the
lcm of these numbers, and displays the lcm.
public class ComputeLCM {
// Method to compute the greatest common divisor (GCD) of two numbers
public static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
// Method to compute the least common multiple (LCM) of two numbers
public static int lcmOfTwo(int a, int b) {
return Math.abs(a * b) / gcd(a, b);
// Method to compute the LCM of an unspecified number of integers
public static int lcm(int... numbers) {
if (numbers.length == 0) {
return 0; // If no numbers are provided, return 0
int lcm = numbers[0];
for (int i = 1; i < numbers.length; i++) {
lcm = lcmOfTwo(lcm, numbers[i]); // Calculate LCM iteratively
return lcm;
public static void main(String[] args) {
// Example usage
System.out.println("LCM of 4, 5, and 6: " + lcm(4, 5, 6));
System.out.println("LCM of 12, 15, 20: " + lcm(12, 15, 20));
System.out.println("LCM of 7, 11, 13: " + lcm(7, 11, 13));
}
7.15 (Eliminate duplicates) Write a method that returns a new array by eliminating the duplicate
values in the array using the following method header:
public static int[] eliminateDuplicates(int[] list)
Write a test program that reads in 10 integers, invokes the method, and displays the distinct numbers
separated by exactly one space.
import java.util.Scanner;
import java.util.Arrays;
public class EliminateDuplicates {
// Method to eliminate duplicate values from an integer array
public static int[] eliminateDuplicates(int[] list) {
int[] tempArray = new int[list.length];
int newSize = 0;
// Loop through the list and add only distinct elements to tempArray
for (int i = 0; i < list.length; i++) {
boolean isDuplicate = false;
// Check if the element is already in tempArray
for (int j = 0; j < newSize; j++) {
if (list[i] == tempArray[j]) {
isDuplicate = true;
break;
}
// If the element is not a duplicate, add it to tempArray
if (!isDuplicate) {
tempArray[newSize] = list[i];
newSize++;
// Create a new array with the exact size of unique elements
int[] distinctArray = Arrays.copyOf(tempArray, newSize);
return distinctArray;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Create an array to hold 10 integers
int[] numbers = new int[10];
// Prompt the user to enter 10 integers
System.out.println("Enter 10 integers:");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextInt();
// Call the method to eliminate duplicates
int[] distinctNumbers = eliminateDuplicates(numbers);
// Display the distinct numbers
System.out.println("The distinct numbers are:");
for (int num : distinctNumbers) {
System.out.print(num + " ");
input.close();