Java Arrays Level 2 Lab Practice
Java Arrays Level 2 Lab Practice
1. Create a program to find the bonus of 10 employees based on their years of service and
the total bonus amount the company Zara has to pay, along with the old and new salary.
Code:
import java.util.Scanner;
public class EmployeeBonus {
public static void main(String[] args) {
final int NUM_EMPLOYEES = 10;
double[] salary = new double[NUM_EMPLOYEES];
double[] yearsOfService = new double[NUM_EMPLOYEES];
double[] bonus = new double[NUM_EMPLOYEES];
double[] newSalary = new double[NUM_EMPLOYEES];
double totalBonus = 0, totalOldSalary = 0, totalNewSalary = 0;
Scanner scanner = new Scanner(System.in);
// Input salaries and years of service
for (int i = 0; i < NUM_EMPLOYEES; i++) {
while (true) {
System.out.print("Enter salary for employee " + (i + 1)
+ ": ");
salary[i] = scanner.nextDouble();
if (salary[i] > 0) break;
System.out.println("Invalid salary. Please enter
again.");
}
while (true) {
System.out.print("Enter years of service for employee "
+ (i + 1) + ": ");
yearsOfService[i] = scanner.nextDouble();
if (yearsOfService[i] >= 0) break;
System.out.println("Invalid years of service. Please
enter again.");
}
}
// Calculate bonus, new salary and total amounts
for (int i = 0; i < NUM_EMPLOYEES; i++) {
if (yearsOfService[i] > 5) {
bonus[i] = salary[i] * 0.05; // 5% bonus
} else {
bonus[i] = salary[i] * 0.02; // 2% bonus
}
newSalary[i] = salary[i] + bonus[i];
totalBonus += bonus[i];
totalOldSalary += salary[i];
totalNewSalary += newSalary[i];
}
// Display results
System.out.println("\nEmployee Details:");
System.out.println("-------------------------------------------------");
System.out.println("Emp# Salary Years Bonus New
Salary");
System.out.println("-------------------------------------------------");
for (int i = 0; i < NUM_EMPLOYEES; i++) {
System.out.printf("%d\t%.2f\t%.2f\t%.2f\t%.2f\n", (i + 1),
salary[i], yearsOfService[i], bonus[i], newSalary[i]);
}
System.out.println("-------------------------------------------------");
System.out.printf("Total Old Salary: %.2f\n", totalOldSalary);
System.out.printf("Total Bonus Payout: %.2f\n", totalBonus);
System.out.printf("Total New Salary: %.2f\n", totalNewSalary);
scanner.close();
}
}
2. Create a program to find the youngest friends among 3 Amar, Akbar, and Anthony
based on their ages and the tallest among the friends based on their heights
Code:
import java.util.Scanner;
public class FriendComparison {
public static void main(String[] args) {
String[] friends = {"Amar", "Akbar", "Anthony"};
int[] ages = new int[3];
double[] heights = new double[3];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
System.out.print("Enter age of " + friends[i] + ": ");
ages[i] = scanner.nextInt();
System.out.print("Enter height (in cm) of " + friends[i] +
": ");
heights[i] = scanner.nextDouble();
}
// Finding the youngest friend
int minAgeIndex = 0;
for (int i = 1; i < 3; i++) {
if (ages[i] < ages[minAgeIndex]) {
minAgeIndex = i;
}
}
// Finding the tallest friend
int maxHeightIndex = 0;
for (int i = 1; i < 3; i++) {
if (heights[i] > heights[maxHeightIndex]) {
maxHeightIndex = i;
}
}
System.out.println("\nThe youngest friend is " +
friends[minAgeIndex] + " with age " + ages[minAgeIndex] + ".");
System.out.println("The tallest friend is " +
friends[maxHeightIndex] + " with height " + heights[maxHeightIndex] + "
cm.");
scanner.close();
}
}
3. Create a program to store the digits of the number in an array and find the largest
and second largest element of the array.
Code:
import java.util.Scanner;
public class DigitAnalysis {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
final int maxDigit = 10;
int[] digits = new int[maxDigit];
int index = 0;
// Extract digits and store them in the array
while (number != 0 && index < maxDigit) {
digits[index++] = number % 10;
number /= 10;
}
// Initialize largest and second largest
int largest = -1, secondLargest = -1;
// Find the largest and second largest digits
for (int i = 0; i < index; i++) {
if (digits[i] > largest) {
secondLargest = largest;
largest = digits[i];
} else if (digits[i] > secondLargest && digits[i] !=
largest) {
secondLargest = digits[i];
}
}
System.out.println("Largest digit: " + largest);
System.out.println("Second largest digit: " + (secondLargest ==
-1 ? "Not available" : secondLargest));
scanner.close();
}
}
4. Rework the program 2, especially the Hint f where if index equals maxDigit, we break
from the loop. Here we want to modify to Increase the size of the array i,e maxDigit
by 10 if the index is equal to maxDigit. This is done to consider all digits to find the
largest and second-largest number
Code:
import java.util.Scanner;
public class DigitAnalysis2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int maxDigit = 10;
int[] digits = new int[maxDigit];
int index = 0;
// Extract digits and store them in the array, dynamically
increasing size if needed
while (number != 0) {
if (index == maxDigit) {
maxDigit += 10; // Increase size by 10
int[] temp = new int[maxDigit];
System.arraycopy(digits, 0, temp, 0, digits.length);
digits = temp;
}
digits[index++] = number % 10;
number /= 10;
}
// Initialize largest and second largest
int largest = -1, secondLargest = -1;
// Find the largest and second largest digits
for (int i = 0; i < index; i++) {
if (digits[i] > largest) {
secondLargest = largest;
largest = digits[i];
} else if (digits[i] > secondLargest && digits[i] !=
largest) {
secondLargest = digits[i];
}
}
// Display results
System.out.println("Largest digit: " + largest);
System.out.println("Second largest digit: " + (secondLargest ==
-1 ? "Not available" : secondLargest));
scanner.close();
}
}
5. Create a program to take a number as input and reverse the number. To do this,
store the digits of the number in an array and display the array in reverse order
Code:
import java.util.Scanner;
public class ReverseNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int temp = number;
int digitCount = 0;
// Count the number of digits
while (temp != 0) {
digitCount++;
temp /= 10;
}
int[] digits = new int[digitCount];
// Store digits in an array
temp = number;
for (int i = 0; i < digitCount; i++) {
digits[i] = temp % 10;
temp /= 10;
}
// Display digits in reverse order
System.out.print("Reversed number: ");
for (int i = 0; i < digitCount; i++) {
System.out.print(digits[i]);
}
System.out.println();
scanner.close();
}
}
6. An organization took up an exercise to find the Body Mass Index (BMI) of all the
persons in the team. For this create a program to find the BMI and display the height,
weight, BMI and status of each individual
Code:
import java.util.Scanner;
public class BMICalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of persons: ");
int numPersons = scanner.nextInt();
double[] heights = new double[numPersons];
double[] weights = new double[numPersons];
double[] bmiValues = new double[numPersons];
String[] weightStatus = new String[numPersons];
for (int i = 0; i < numPersons; i++) {
System.out.print("Enter height (in meters) for person " + (i
+ 1) + ": ");
heights[i] = scanner.nextDouble();
System.out.print("Enter weight (in kg) for person " + (i +
1) + ": ");
weights[i] = scanner.nextDouble();
bmiValues[i] = weights[i] / (heights[i] * heights[i]);
if (bmiValues[i] < 18.5) {
weightStatus[i] = "Underweight";
} else if (bmiValues[i] < 24.9) {
weightStatus[i] = "Normal weight";
} else if (bmiValues[i] < 29.9) {
weightStatus[i] = "Overweight";
} else {
weightStatus[i] = "Obese";
}
}
System.out.println("\nPerson Height(m) Weight(kg) BMI
Status");
System.out.println("------------------------------------------------");
for (int i = 0; i < numPersons; i++) {
System.out.printf("%d %.2f %.2f %.2f
%s\n",
(i + 1), heights[i], weights[i],
bmiValues[i], weightStatus[i]);
}
scanner.close();
}
}
7. Rewrite the above program using multi-dimensional array to store height, weight, and
BMI in 2D array for all the persons
Code:
import java.util.Scanner;
public class BMICalculator2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of persons: ");
int numPersons = scanner.nextInt();
double[][] personData = new double[numPersons][3]; // [height, weight, BMI]
String[] weightStatus = new String[numPersons];
// Input height and weight
for (int i = 0; i < numPersons; i++) {
do {
System.out.print("Enter height (in meters) for person " + (i + 1) + ": ");
personData[i][0] = scanner.nextDouble();
if (personData[i][0] <= 0) {
System.out.println("Height must be a positive value. Please enter again.");
}
} while (personData[i][0] <= 0);
do {
System.out.print("Enter weight (in kg) for person " + (i + 1) + ": ");
personData[i][1] = scanner.nextDouble();
if (personData[i][1] <= 0) {
System.out.println("Weight must be a positive value. Please enter again.");
}
} while (personData[i][1] <= 0);
// Calculate BMI
personData[i][2] = personData[i][1] / (personData[i][0] * personData[i][0]);
// Determine weight status
if (personData[i][2] < 18.5) {
weightStatus[i] = "Underweight";
} else if (personData[i][2] < 24.9) {
weightStatus[i] = "Normal weight";
} else if (personData[i][2] < 29.9) {
weightStatus[i] = "Overweight";
} else {
weightStatus[i] = "Obese";
}
}
// Display results
System.out.println("\nPerson Height(m) Weight(kg) BMI Status");
System.out.println("------------------------------------------------");
for (int i = 0; i < numPersons; i++) {
System.out.printf("%d %.2f %.2f %.2f %s\n",
(i + 1), personData[i][0], personData[i][1], personData[i][2],
weightStatus[i]);
}
scanner.close();
}
}
8. Create a program to take input marks of students in 3 subjects physics, chemistry,
and maths. Compute the percentage and then calculate the grade as per the
following guidelines
Code:
import java.util.Scanner;
public class StudentGradesCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int numStudents = scanner.nextInt();
double[][] marks = new double[numStudents][3]; // [physics, chemistry,
maths]
double[] percentages = new double[numStudents];
String[] grades = new String[numStudents];
// Input marks for students
for (int i = 0; i < numStudents; i++) {
System.out.println("\nEnter marks for Student " + (i + 1) + ":");
for (int j = 0; j < 3; j++) {
String subject = (j == 0) ? "Physics" : (j == 1) ? "Chemistry" :
"Maths";
do {
System.out.print(subject + ": ");
marks[i][j] = scanner.nextDouble();
if (marks[i][j] < 0) {
System.out.println("Marks cannot be negative. Please enter
again.");
}
} while (marks[i][j] < 0);
}
percentages[i] = (marks[i][0] + marks[i][1] + marks[i][2]) / 3;
if (percentages[i] >= 90) {
grades[i] = "A+";
} else if (percentages[i] >= 80) {
grades[i] = "A";
} else if (percentages[i] >= 70) {
grades[i] = "B";
} else if (percentages[i] >= 60) {
grades[i] = "C";
} else if (percentages[i] >= 50) {
grades[i] = "D";
} else {
grades[i] = "F";
}
}
System.out.println("\nStudent Physics Chemistry Maths Percentage
Grade");
System.out.println("----------------------------------------------------------");
for (int i = 0; i < numStudents; i++) {
System.out.printf("%d %.2f %.2f %.2f %.2f%%
%s\n",
(i + 1), marks[i][0], marks[i][1], marks[i][2],
percentages[i], grades[i]);
}
scanner.close();
}
}
9. Rewrite the above program to store the marks of the students in physics, chemistry,
and maths in a 2D array and then compute the percentage and grade
Code:
import java.util.Scanner;
public class StudentGradesCalculator2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int numStudents = scanner.nextInt();
double[][] marks = new double[numStudents][3]; // [physics, chemistry,
maths]
double[] percentages = new double[numStudents];
String[] grades = new String[numStudents];
for (int i = 0; i < numStudents; i++) {
System.out.println("\nEnter marks for Student " + (i + 1) + ":");
for (int j = 0; j < 3; j++) {
String subject = (j == 0) ? "Physics" : (j == 1) ? "Chemistry" :
"Maths";
do {
System.out.print(subject + ": ");
marks[i][j] = scanner.nextDouble();
if (marks[i][j] < 0) {
System.out.println("Marks cannot be negative. Please enter
again.");
}
} while (marks[i][j] < 0);
}
percentages[i] = (marks[i][0] + marks[i][1] + marks[i][2]) / 3;
if (percentages[i] >= 90) {
grades[i] = "A+";
} else if (percentages[i] >= 80) {
grades[i] = "A";
} else if (percentages[i] >= 70) {
grades[i] = "B";
} else if (percentages[i] >= 60) {
grades[i] = "C";
} else if (percentages[i] >= 50) {
grades[i] = "D";
} else {
grades[i] = "F";
}
}
System.out.println("\nStudent Physics Chemistry Maths Percentage
Grade");
System.out.println("----------------------------------------------------------");
for (int i = 0; i < numStudents; i++) {
System.out.printf("%d %.2f %.2f %.2f %.2f%%
%s\n",
(i + 1), marks[i][0], marks[i][1], marks[i][2],
percentages[i], grades[i]);
}
scanner.close();
}
}
10.Create a program to take a number as input find the frequency of each digit in the
number using an array and display the frequency of each digit
Code:
import java.util.Scanner;
public class DigitFrequency {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int[] frequency = new int[10]; // Array to store frequency of
digits 0-9
int tempNumber = Math.abs(number); // Take absolute value to
handle negative numbers
// Count frequency of each digit
while (tempNumber > 0) {
int digit = tempNumber % 10; // Extract last digit
frequency[digit]++;
tempNumber /= 10; // Remove last digit
}
System.out.println("Digit Frequency in the given number:");
for (int i = 0; i < 10; i++) {
if (frequency[i] > 0) {
System.out.println("Digit " + i + ": " + frequency[i] +
" times");
}
}
scanner.close();
}
}