answer of assignment 1
answer of assignment 1
Problem: Write a Java program that takes a positive integer greater than 2 as input and outputs
the number of times the integer must be repeatedly divided by 2 before the result is less than 2.
Solution:
import java.util.Scanner;
public class RepeatedDivision {
public static void main(String args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a positive integer greater than 2: ");
int number = input.nextInt();
if (number <= 2) {
System.out.println("Invalid input. Please enter a number
greater than 2.");
return;
}
int count = 0;
while (number >= 2) {
number /= 2;
count++;
}
System.out.println("The number of times one must repeatedly
divide this number by 2 before getting a value less than 2 is " +
count);
}
}
Explanation:
1. Import Scanner: import java.util.Scanner; imports the Scanner class, which is used to get
user input.
2. Create Scanner Object: Scanner input = new Scanner(System.in); creates a Scanner
object to read input from the console.
3. Get Input: The program prompts the user to enter a positive integer greater than 2 and
stores it in the number variable.
4. Input Validation: The program checks if the input number is greater than 2. If not, it prints
an error message and exits.
5. Divide and Count:
○ A while loop repeatedly divides the number by 2 until it becomes less than 2.
○ Inside the loop, number /= 2; divides the number by 2 and updates its value.
○ count++ increments the count variable to keep track of the number of divisions.
6. Output: The program prints the final count, which represents the number of divisions
required.
Question 2:
Problem: Write a Java program that calculates the Body Mass Index (BMI) based on user input
for weight (in kilograms) and height (in meters) and categorizes the BMI according to the
following table:
Category BMI
Underweight Less than 18.5
Normal Weight 18.5 to 24.9
Overweight 25.0 to 29.9
Obese 30.0 or more
Solution:
import java.util.Scanner;
public class BMICalculator {
public static void main(String args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your weight in kilograms: ");
double weight = input.nextDouble();
System.out.print("Enter your height in meters: ");
double height = input.nextDouble();
double bmi = weight / (height * height);
String category;
if (bmi < 18.5) {
category = "Underweight";
} else if (bmi < 25) {
category = "Normal Weight";
} else if (bmi < 30) {
category = "Overweight";
} else {
category = "Obese";
}
System.out.println("Your BMI is: " + bmi);
System.out.println("Category: " + category);
}
}
Explanation:
1. Import Scanner: import java.util.Scanner; imports the Scanner class for user input.
2. Get Input: The program prompts the user to enter weight and height and stores them in
weight and height variables.
3. Calculate BMI: double bmi = weight / (height * height); calculates the BMI using the
formula.
4. Categorize BMI: An if-else if-else block determines the BMI category based on the
calculated bmi value.
5. Output: The program prints the calculated BMI and its corresponding category.
Question 3:
Problem: Write a Java program to check if a number is a "spy number." A spy number is a
number where the sum of its digits equals the product of its digits.
Solution:
import java.util.Scanner;
public class SpyNumber {
public static void main(String args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
int originalNumber = number;
int sum = 0;
int product = 1;
while (number > 0) {
int digit = number % 10;
sum += digit;
product *= digit;
number /= 10;
}
if (sum == product) {
System.out.println(originalNumber + " is a spy number.");
} else {
System.out.println(originalNumber + " is not a spy
number.");
}
}
}
Explanation:
1. Import Scanner: import java.util.Scanner; imports the Scanner class for user input.
2. Get Input: The program prompts the user to enter a number and stores it in the number
variable.
3. Initialize Variables:
○ originalNumber stores the original input number for later use.
○ sum stores the sum of the digits, initialized to 0.
○ product stores the product of the digits, initialized to 1.
4. Calculate Sum and Product:
○ A while loop iterates through each digit of the number.
○ int digit = number % 10; extracts the last digit of the number.
○ sum += digit; adds the digit to the sum.
○ product *= digit; multiplies the digit with the product.
○ number /= 10; removes the last digit from the number.
5. Check Spy Number: The program compares sum and product. If they are equal, it prints
that the original number is a spy number; otherwise, it's not.
Question 4:
Problem: Write a Java program that outputs all possible strings formed by using the characters
'c', 'a', 'r', 'b', 'o', and 'n' exactly once.
Solution:
public class StringPermutations {
public static void main(String args) {
String str = "carbon";
permute(str, 0, str.length() - 1);
}
public static void permute(String str, int l, int r) {
if (l == r) {
System.out.println(str);
} else {
for (int i = l; i <= r; i++) {
str = swap(str, l, i);
permute(str, l + 1, r);
str = swap(str, l, i); // Backtrack to restore the
original string
}
}
}
public static String swap(String a, int i, int j) {
char temp;
char charArray = a.toCharArray();
temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
}
Explanation:
1. permute(str, l, r) Function:
○ Takes the string str, starting index l, and ending index r as input.
○ If l and r are equal, it means a permutation is complete, so it prints the str.
○ Otherwise, it iterates through the string from l to r.
○ In each iteration, it swaps the character at index l with the character at index i using
the swap() function.
○ Then, it recursively calls permute() with l+1 as the new starting index to generate
permutations for the remaining substring.
○ After the recursive call returns, it swaps the characters back to their original
positions to backtrack and explore other permutations.
2. swap(a, i, j) Function:
○ Takes a string a and two indices i and j as input.
○ Swaps the characters at indices i and j in the string.
○ Returns the modified string.
Question 5:
Problem: Write a Java method to calculate the sum of digits of a given number until the sum
becomes a single digit.
Solution:
public class SumOfDigits {
public static int sumOfDigits(int n) {
while (n > 9) { // Continue until n is a single digit
int sum = 0;
while (n > 0) {
sum += n % 10; // Add the last digit to sum
n /= 10; // Remove the last digit
}
n = sum; // Update n with the new sum
}
return n;
}
public static void main(String args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
int result = sumOfDigits(number);
System.out.println("Sum of digits of " + number + " until the
number is a single digit is " + result);
}
}
Explanation:
1. sumOfDigits(n) Function:
○ Takes an integer n as input.
○ The outer while loop continues until n becomes a single digit (less than 10).
○ The inner while loop calculates the sum of digits of the current n.
○ n is updated with the calculated sum.
○ Finally, the single-digit sum is returned.
2. main() Function:
○ Gets the input number from the user.
○ Calls the sumOfDigits() function to calculate the sum of digits.
○ Prints the result.
Question 6:
Problem: Write a Java method, isOdd(), that takes an integer i and returns true if and only if i is
odd. You cannot use the multiplication, modulus, or division operators.
Solution:
import java.util.Scanner;
public class OddChecker {
public static boolean isOdd(int n) {
return (n & 1) == 1;
}
public static void main(String args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
boolean odd = isOdd(number);
System.out.println(number + " is odd: " + odd);
}
}
Explanation:
1. isOdd(n) Function:
○ Takes an integer n as input.
○ Uses the bitwise AND operator (&) with 1 to check the least significant bit of n.
○ If the least significant bit is 1, the number is odd, and the function returns true;
otherwise, it returns false.
2. main() Function:
○ Gets the input number from the user.
○ Calls the isOdd() function to check if the number is odd.
○ Prints the result.
Question 7:
Problem: Write a Java program to find the maximum and minimum elements in an array of n
elements and count how many times each of them occurs in the array. Also, find the positions
where the maximum first occurs and the minimum last occurs.
Solution:
import java.util.Scanner;
public class ArrayMaxMin {
public static void main(String args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of elements in the array:
");
int n = input.nextInt();
int arr = new int[n];
System.out.print("Enter the elements of the array: ");
for (int i = 0; i < n; i++) {
arr[i] = input.nextInt();
}
int max = arr;
int min = arr;
int maxCount = 1;
int minCount = 1;
int maxFirstIndex = 0;
int minLastIndex = 0;
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
maxCount = 1;
maxFirstIndex = i;
} else if (arr[i] == max) {
maxCount++;
}
if (arr[i] < min) {
min = arr[i];
minCount = 1;
minLastIndex = i;
} else if (arr[i] == min) {
minCount++;
minLastIndex = i; // Update the last occurrence index
}
}
System.out.println("Maximum element of the array is " + max +
" and occurs " + maxCount + " times.");
System.out.println("Minimum element of the array is " + min +
" and occurs " + minCount + " times.");
System.out.println("First occurrence of maximum element is at
position " + (maxFirstIndex + 1));
System.out.println("Last occurrence of minimum element is at
position " + (minLastIndex + 1));
}
}
Explanation:
1. Get Input: The program prompts the user to enter the number of elements and the
elements of the array.
2. Initialize Variables:
○ max and min are initialized with the first element of the array.
○ maxCount and minCount are initialized to 1.
○ maxFirstIndex and minLastIndex are initialized to 0.
3. Find Max, Min, and Counts:
○ The program iterates through the array.
○ If it finds an element greater than max, it updates max, maxCount, and
maxFirstIndex.
○ If it finds an element equal to max, it increments maxCount.
○ If it finds an element smaller than min, it updates min, minCount, and minLastIndex.
○ If it finds an element equal to min, it increments minCount and updates
minLastIndex to store the last occurrence position.
4. Output: The program prints the maximum and minimum elements, their counts, and the
positions of their first and last occurrences.
Question 8:
Problem: Write a Java program to print an M-by-N array in tabular format and display the sum
of its elements.
Solution:
import java.util.Scanner;
public class ArrayTabularFormat {
public static void main(String args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of rows and columns of the
2D array: ");
int rows = input.nextInt();
int cols = input.nextInt();
int arr = new int[rows][cols];
System.out.println("Enter the elements of the 2D array: ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j] = input.nextInt();
}
}
System.out.println("The elements of the 2D array are: ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
int sum = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sum += arr[i][j];
}
}
System.out.println("The sum of the elements of the 2D array is
" + sum);
}
}
Explanation:
1. Get Input: The program prompts the user to enter the number of rows and columns and
the elements of the 2D array.
2. Print Array: The program uses nested loops to iterate through the array and print its
elements in tabular format.
3. Calculate Sum: The program uses nested loops to iterate through the array and calculate
the sum of all elements.
4. Output: The program prints the sum of the elements.
Question 9:
Problem: Write a Java method that sums all the numbers in the major diagonal of an n-by-n
matrix of double values. The method header is: public static double sumMajorDiagonal(double
m)
Solution:
import java.util.Scanner;
public class MajorDiagonalSum {
public static double sumMajor
Question 9:
Problem: Write a Java method that sums all the numbers in the major diagonal of an n-by-n
matrix of double values. The method header is: public static double sumMajorDiagonal(double
m)
Solution:
import java.util.Scanner;
public class MajorDiagonalSum {
public static double sumMajorDiagonal(double m) {
double sum = 0;
for (int i = 0; i < m.length; i++) {
sum += m[i][i];
}
return sum;
}
public static void main(String args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a 4-by-4 matrix row by row: ");
double matrix = new double;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
matrix[i][j] = input.nextDouble();
}
}
double sum = sumMajorDiagonal(matrix);
System.out.println("Sum of the elements in the major diagonal
is " + sum);
}
}
Explanation:
1. sumMajorDiagonal(m) Function:
○ Takes a 2D array m of double values as input.
○ Initializes a sum variable to 0.
○ Iterates through the major diagonal of the matrix (elements where row index equals
column index).
○ In each iteration, it adds the element at m[i][i] to the sum.
○ Returns the calculated sum.
2. main() Function:
○ Prompts the user to enter a 4-by-4 matrix.
○ Stores the input in the matrix 2D array.
○ Calls the sumMajorDiagonal() function to calculate the sum of the major diagonal
elements.
○ Prints the calculated sum.
Question 10:
Problem: Write a Java method that returns the sum of all the elements in a specified column in
a matrix using the following header: public static double sumColumn(double m, int columnIndex)
Solution:
import java.util.Scanner;
public class ColumnSum {
public static double sumColumn(double m, int columnIndex) {
double sum = 0;
for (int i = 0; i < m.length; i++) {
sum += m[i][columnIndex];
}
return sum;
}
public static void main(String args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a 3-by-4 matrix row by row: ");
double matrix = new double;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
matrix[i][j] = input.nextDouble();
}
}
for (int col = 0; col < 4; col++) {
double sum = sumColumn(matrix, col);
System.out.println("Sum of the elements at column " + col
+ " is " + sum);
}
}
}
Explanation:
1. sumColumn(m, columnIndex) Function:
○ Takes a 2D array m and an integer columnIndex as input.
○ Initializes a sum variable to 0.
○ Iterates through the rows of the matrix (m.length).
○ In each iteration, it adds the element at the specified columnIndex
(m[i][columnIndex]) to the sum.
○ Returns the calculated sum.
2. main() Function:
○ Prompts the user to enter a 3-by-4 matrix.
○ Stores the input in the matrix 2D array.
○ Iterates through each column (col) of the matrix.
○ For each column, it calls the sumColumn() function to calculate the sum of its
elements.
○ Prints the sum of each column.
Home Assignment:
Question 1:
Problem: Write a Java program that takes as input three integers, a, b, and c, from the Java
console and determines if they can be used in a correct arithmetic formula (in the given order),
like "a + b = c," "a = b - c," or "a * b = c."
Solution:
import java.util.Scanner;
public class ArithmeticFormula {
public static void main(String args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter three integers (a, b, c): ");
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
if (a + b == c) {
System.out.println(a + " + " + b + " = " + c);
} else if (a == b - c) {
System.out.println(a + " = " + b + " - " + c);
} else if (a * b == c) {
System.out.println(a + " * " + b + " = " + c);
} else {
System.out.println("No arithmetic formula found for the
given numbers.");
}
}
}
Explanation:
1. Get Input: The program prompts the user to enter three integers and stores them in
variables a, b, and c.
2. Check Formulas: The program checks if the input numbers satisfy any of the following
arithmetic formulas:
○ a + b = c
○ a = b - c
○ a * b = c
3. Output: If any of the formulas are true, the program prints the corresponding formula.
Otherwise, it prints a message indicating that no formula was found.
Question 2:
Problem: Write a Java program that takes all the lines input to standard input and writes them
to standard output in reverse order. That is, each line is output in the correct order, but the
ordering of the lines is reversed.
Solution:
import java.util.Scanner;
import java.util.ArrayList;
public class ReverseLines {
public static void main(String args) {
Scanner input = new Scanner(System.in);
ArrayList<String> lines = new ArrayList<>();
System.out.println("Enter lines of text (enter an empty line
to finish):");
String line;
while (!(line = input.nextLine()).isEmpty()) {
lines.add(line);
}
System.out.println("\nLines in reversed order:");
for (int i = lines.size() - 1; i >= 0; i--) {
System.out.println(lines.get(i));
}
}
}
Explanation:
1. Import ArrayList: import java.util.ArrayList; imports the ArrayList class to store the lines
of input.
2. Get Input:
○ The program prompts the user to enter lines of text.
○ It reads each line using input.nextLine() and stores it in an ArrayList called lines.
○ The loop continues until the user enters an empty line.
3. Reverse Output:
○ The program iterates through the lines ArrayList in reverse order using a for loop.
○ It prints each line using System.out.println().
Question 3:
Problem: Write a Java program that takes two arrays a and b of length n storing int values, and
returns the dot product of a and b. That is, it returns an array c of length n such that c[i] = a[i] *
b[i], for i = 0,..., n-1
Solution:
import java.util.Scanner;
public class DotProduct {
public static void main(String args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the length of the arrays: ");
int n = input.nextInt();
int a = new int[n];
int b = new int[n];
int c = new int[n];
System.out.print("Enter the elements of array a: ");
for (int i = 0; i < n; i++) {
a[i] = input.nextInt();
}
System.out.print("Enter the elements of array b: ");
for (int i = 0; i < n; i++) {
b[i] = input.nextInt();
}
for (int i = 0; i < n; i++) {
c[i] = a[i] * b[i];
}
System.out.print("The dot product of a and b is: ");
for (int i = 0; i < n; i++) {
System.out.print(c[i] + " ");
}
System.out.println();
}
}
Explanation:
1. Get Input: The program prompts the user to enter the length of the arrays (n) and the
elements of arrays a and b.
2. Calculate Dot Product:
○ It creates a new array c of the same length (n).
○ It iterates through the arrays and calculates the dot product by multiplying
corresponding elements of a and b and storing the result in c.
3. Output: The program prints the elements of the resulting array c, which represents the
dot product of a and b.
Question 4:
Problem: Write a method to add two matrices. The header of the method is as follows: public
static double addMatrix(double a, double b)
Solution:
import java.util.Scanner;
public class MatrixAddition {
public static double addMatrix(double a, double b) {
int rows = a.length;
int cols = a.length;
double c = new double[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
return c;
}
public static void main(String args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of rows and columns of the
matrices: ");
int rows = input.nextInt();
int cols = input.nextInt();
double a = new double[rows][cols];
double b = new double[rows][cols];
System.out.println("Enter the elements of matrix a: ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
a[i][j] = input.nextDouble();
}
}
System.out.println("Enter the elements of matrix b: ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
b[i][j] = input.nextDouble();
}
}
double c = addMatrix(a, b);
System.out.println("The sum of the matrices is: ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}
Explanation:
1. addMatrix(a, b) Function:
○ Takes two 2D arrays a and b as input.
○ Gets the number of rows and columns from matrix a.
○ Creates a new 2D array c with the same dimensions.
○ Uses nested loops to iterate through the matrices and add corresponding elements
of a and b, storing the result in c.
○ Returns the resulting matrix c.
2. main() Function:
○ Prompts the user to enter the dimensions of the matrices and their elements.
○ Calls the addMatrix() function to add the matrices.
○ Prints the resulting sum matrix.
Question 5:
Problem: Write a Java program that randomly fills in 0s and 1s into a 4-by-4 matrix, prints the
matrix, and finds the first row and column with the most 1s.
Solution:
import java.util.Random;
public class MatrixFill {
public static void main(String args) {
Random random = new Random();
int matrix = new int;
// Fill the matrix with random 0s and 1s
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
matrix[i][j] = random.nextInt(2); // Generates 0 or 1
}
}
// Print the matrix
System.out.println("The matrix is: ");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
// Find the first row with the most 1s
int maxRowOnes = 0;
int maxRowIndex = 0;
for (int i = 0; i < 4; i++) {
int rowOnes = 0;
for (int j = 0; j < 4; j++) {
if (matrix[i][j] == 1) {
rowOnes++;
}
}
if (rowOnes > maxRowOnes) {
maxRowOnes = rowOnes;
maxRowIndex = i;
}
}
// Find the first column with the most 1s
int maxColOnes = 0;
int maxColIndex = 0;
for (int j = 0; j < 4; j++) {
int colOnes = 0;
for (int i = 0; i < 4; i++) {
if (matrix[i][j] == 1) {
colOnes++;
}
}
if (colOnes > maxColOnes) {
maxColOnes = colOnes;
maxColIndex = j;
}
}
System.out.println("The largest row index: " + maxRowIndex);
System.out.println("The largest column index: " +
maxColIndex);
}
}
Explanation:
1. Create Matrix: The program creates a 4-by-4 matrix (matrix) to store the 0s and 1s.
2. Fill Matrix: It uses a Random object to generate random 0s and 1s and fills the matrix.
3. Print Matrix: It prints the matrix in a readable format.
4. Find Row with Most 1s:
○ It iterates through each row of the matrix and counts the number of 1s in each row.
○ It keeps track of the maximum number of 1s found in a row (maxRowOnes) and the
index of that row (maxRowIndex).
5. Find Column with Most 1s:
○ It iterates through each column of the matrix and counts the number of 1s in each
column.
○ It keeps track of the maximum number of 1s found in a column (maxColOnes) and
the index of that column (maxColIndex).
6. Output: The program prints the index of the first row and the first column that have the
most 1s.