Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Java Arrays Level 1 Lab Practice

The document outlines best programming practices including the use of variables, proper naming conventions, and input validation. It provides sample Java programs demonstrating concepts such as summing digits, working with multi-dimensional arrays, and checking voting eligibility. Additionally, it includes exercises for creating multiplication tables, calculating mean heights, and separating odd and even numbers.

Uploaded by

thorodinsan82
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Arrays Level 1 Lab Practice

The document outlines best programming practices including the use of variables, proper naming conventions, and input validation. It provides sample Java programs demonstrating concepts such as summing digits, working with multi-dimensional arrays, and checking voting eligibility. Additionally, it includes exercises for creating multiplication tables, calculating mean heights, and separating odd and even numbers.

Uploaded by

thorodinsan82
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Best Programming Practice

1.​ All values as variables including Fixed, User Inputs, and Results
2.​ Avoid Hard Coding of variables wherever possible
3.​ Proper naming conventions for all variables
4.​ Proper Program Name and Class Name
5.​ Follow proper indentation
6.​ Give comments for every step or logical block like a variable declaration or conditional
and loop blocks
7.​ For every user input validate the user input, if invalid, state the error either exit the
program or ask user to enter again
8.​ Use Array length property while using for loop

1.​ Sample Program 1 - Create a program to find the sum of all the digits of a number given by
a user using an array and display the sum.
Hint =>
a.​ Take the input for a number and validate, if failed state and exit the program
b.​ Find the count of digits in the number
c.​ Find the digits in the number and save them in an array
d.​ Find the sum of the digits of the number and display the sum

Java
// Create SumOfDigit Class to compute the sum of all digits of a number using
// an array
import java.util.Scanner;

class SumOfDigits {
public static void main(String[] args) {
// Create a Scanner Object
Scanner input = new Scanner(System.in);

// Take input for a number


System.out.print("Enter a number: ");
int number = input.nextInt();

// Validate the user input number, if negative state invalid and exit
if (number < 0) {
System.err.println("Invalid Number.");
System.exit(0);
}

1
// Find the count of digits in the number
int count = 0;
int temp = number;
while (temp > 0) {
count++;
temp /= 10;
}

// Find the digits in the number and save them in an array


int[] digits = new int[count];
for (int i = 0; i < count; i++) {
digits[i] = number % 10;
number /= 10;
}

// Find the sum of the digits of the number


int sum = 0;
for (int i = 0; i < count; i++) {
sum += digits[i];
}

// Display the sum of the digits of the number


System.out.println("\nSum of Digits: " + sum);

// Close the Scanner Object


input.close();
}
}

2.​ Sample Program 2 - Working with Multi-Dimensional Arrays. Write a Java program to
create a 2 Dimensional (2D) array (matrix) of integers, initialize it with values, and print the
sum of all elements in the matrix
Hint =>
a.​ Take the input for a number of rows and columns
b.​ Create a 2D array (matrix) of integers
c.​ Take the input for the elements of the matrix
d.​ Calculate the sum of all elements in the matrix and display the sum
e.​ Also, Display the matrix

2
Java
// Program to create a 2D array, display the elements and calculate the sum of
// the elements of the array
import java.util.Scanner;

class 2DArray {
public static void main(String[] args) {
// Create a Scanner Object
Scanner input = new Scanner(System.in);

// Declare the 2D Array


int[][] arr = new int[3][3];

// Input the elements of the 2D Array


System.out.println("Enter the elements of the 2D Array: ");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
arr[i][j] = input.nextInt();
}
}

// Display the elements of the 2D Array and calculate the sum of the
// elements of the 2D Array
int sum = 0;
System.out.println("The elements of the 2D Array are: ");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(arr[i][j] + " ");
sum += arr[i][j];
}
System.out.println();
}

// Display the sum of the elements of the 2D Array


System.out.println("The sum of the elements of the 2D Array is: " + sum);

// Close the Scanner Object


input.close();
}
}

3
Level 1 Practice Programs
1.​ Write a program to take user input for the age of all 10 students in a class and check
whether the student can vote depending on his/her age is greater or equal to 18.
Hint =>
a.​ Define an array of 10 integer elements and take user input for the student's age.
b.​ Loop through the array using the length property and for the element of the array check
If the age is a negative number print an invalid age and if 18 or above, print The student
with the age ___ can vote. Otherwise, print The student with the age ___ cannot vote.
import java.util.Scanner;

public class StudentVotingEligibility {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int[] ages = new int[10];

// Taking user input for the ages of 10 students

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

System.out.print("Enter the age of student " + (i + 1) +


": ");

ages[i] = scanner.nextInt();

// Checking voting eligibility

for (int age : ages) {

if (age < 0) {

System.out.println("Invalid age: " + age);

} else if (age >= 18) {

System.out.println("The student with the age " + age


+ " can vote.");

} else {

4
System.out.println("The student with the age " + age
+ " cannot vote.");

scanner.close();

2.​ Write a program to take user input for 5 numbers and check whether a number is positive,
negative, or zero. Further for positive numbers check if the number is even or odd. Finally
compare the first and last elements of the array and display if they equal, greater or less
Hint =>
a.​ Define an integer array of 5 elements and get user input to store in the array.
b.​ Loop through the array using the length If the number is positive, check for even or odd
numbers and print accordingly
c.​ If the number is negative, print negative. Else if the number is zero, print zero.
d.​ Finally compare the first and last element of the array and display if they equal, greater
or less
import java.util.Scanner;

public class NumberAnalysis {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int[] numbers = new int[5];

// Taking user input for 5 numbers

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

System.out.print("Enter number " + (i + 1) + ": ");

numbers[i] = scanner.nextInt();

5
}

// Analyzing the numbers

for (int number : numbers) {

if (number > 0) {

if (number % 2 == 0) {

System.out.println(number + " is positive and


even.");

} else {

System.out.println(number + " is positive and


odd.");

} else if (number < 0) {

System.out.println(number + " is negative.");

} else {

System.out.println("The number is zero.");

// Comparing the first and last elements

if (numbers[0] == numbers[numbers.length - 1]) {

System.out.println("The first and last elements are


equal.");

} else if (numbers[0] > numbers[numbers.length - 1]) {

System.out.println("The first element is greater than


the last element.");

} else {

System.out.println("The first element is less than the


last element.");

6
scanner.close();

3.​ Create a program to print a multiplication table of a number.


Hint =>
a.​ Get an integer input and store it in the number variable. Also, define a integer array to
store the results of multiplication from 1 to 10
b.​ Run a loop from 1 to 10 and store the results in the multiplication table array
c.​ Finally, display the result from the array in the format number * i = ___
import java.util.Scanner;

public class MultiplicationTable {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number to print its multiplication


table: ");

int number = scanner.nextInt();

int[] multiplicationTable = new int[10];

// Calculating the multiplication table

for (int i = 1; i <= 10; i++) {

multiplicationTable[i - 1] = number * i;

// Displaying the multiplication table

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

7
System.out.println(number + " * " + (i + 1) + " = " +
multiplicationTable[i]);

scanner.close();

4.​ Write a program to store multiple values in an array up to a maximum of 10 or until the user
enters a 0 or a negative number. Show all the numbers as well as the sum of all numbers
Hint =>
a.​ Create a variable to store an array of 10 elements of type double as well as a variable to
store the total of type double initializes to 0.0. Also, the index variable is initialized to 0
for the array
b.​ Use infinite while loop as in while (true)
c.​ Take the user entry and check if the user entered 0 or a negative number to break the
loop
d.​ Also, break from the loop if the index has a value of 10 as the array size is limited to 10.
e.​ If the user entered a number other than 0 or a negative number inside the while loop
then assign the number to the array element and increment the index value
f.​ Take another for loop to get the values of each element and add it to the total
g.​ Finally display the total value
import java.util.Scanner;

public class StoreValues {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

double[] values = new double[10];

double total = 0.0;

int index = 0;

// Infinite loop to take user input

8
while (true) {

System.out.print("Enter a number (0 or negative to


stop): ");

double input = scanner.nextDouble();

// Check for 0 or negative number to break the loop

if (input <= 0 || index >= 10) {

break;

// Store the number in the array and increment the index

values[index] = input;

index++;

// Calculate the total and display the values

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

total += values[i];

System.out.println("Value " + (i + 1) + ": " +


values[i]);

System.out.println("Total: " + total);

scanner.close();

9
5.​ Create a program to find the multiplication table of a number entered by the user from 6 to 9
and display the result
Hint =>
a.​ Take integer input and store it in the variable number as well as define an integer array
to store the multiplication result in the variable multiplicationResult
b.​ Using a for loop, find the multiplication table of numbers from 6 to 9 and save the result
in the array
c.​ Finally, display the result from the array in the format number * i = ___
import java.util.Scanner;

public class MultiplicationTableRange {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number to find its multiplication


table from 6 to 9: ");

int number = scanner.nextInt();

int[] multiplicationResult = new int[4]; // For multipliers


6, 7, 8, 9

// Calculating the multiplication table from 6 to 9

for (int i = 6; i <= 9; i++) {

multiplicationResult[i - 6] = number * i;

// Displaying the multiplication table

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

System.out.println(number + " * " + (i + 6) + " = " +


multiplicationResult[i]);

scanner.close();

10
}

6.​ Create a program to find the mean height of players present in a football team.
Hint =>
a.​ The formula to calculate the mean is: mean = sum of all elements / number of elements
b.​ Create a double array named heights of size 11 and get input values from the user.
c.​ Find the sum of all the elements present in the array.
d.​ Divide the sum by 11 to find the mean height and print the mean height of the football
team
import java.util.Scanner;

public class MeanHeightCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

double[] heights = new double[11];

double total = 0.0;

// Loop to get heights from the user

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

System.out.print("Enter the height of player " + (i + 1)


+ ": ");

heights[i] = scanner.nextDouble();

total += heights[i];

// Calculate the mean height

double meanHeight = total / heights.length;

11
// Print the mean height

System.out.println("Mean height of the football team: " +


meanHeight);

scanner.close();

7.​ Create a program to save odd and even numbers into odd and even arrays between 1 to the
number entered by the user. Finally, print the odd and even numbers array
Hint =>
a.​ Get an integer input from the user, assign it to a variable number, and check for Natural
Number. If not a natural number then print an error and exit the program
b.​ Create an integer array for even and odd numbers with size = number / 2 + 1
c.​ Create index variables for odd and even numbers and initialize them to zero
d.​ Using a for loop, iterate from 1 to the number, and in each iteration of the loop, save the
odd or even number into the corresponding array
e.​ Finally, print the odd and even numbers array using the odd and even index
import java.util.Scanner;

public class OddEvenSeparator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

int number = scanner.nextInt();

// Check for natural number

if (number <= 0) {

System.out.println("Error: Please enter a natural number


greater than 0.");

return;

12
}

// Create arrays for odd and even numbers

int[] oddNumbers = new int[number / 2 + 1];

int[] evenNumbers = new int[number / 2 + 1];

int oddIndex = 0, evenIndex = 0;

// Iterate from 1 to the number

for (int i = 1; i <= number; i++) {

if (i % 2 == 0) {

evenNumbers[evenIndex++] = i; // Store even number

} else {

oddNumbers[oddIndex++] = i; // Store odd number

// Print odd numbers

System.out.print("Odd Numbers: ");

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

System.out.print(oddNumbers[i] + " ");

System.out.println();

// Print even numbers

System.out.print("Even Numbers: ");

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

System.out.print(evenNumbers[i] + " ");

13
System.out.println();

scanner.close();

8.​ Create a program to find the factors of a number taken as user input, store the factors in an
array, and display the factors
Hint =>
a.​ Take the input for a number
b.​ Find the factors of the number and save them in an array. For this create integer variable
maxFactor and initialize to 10, factors array of size maxFactor and index variable to
reflect the index of the array.
c.​ To find factors loop through the numbers from 1 to the number, find the factors, and add
them to the array element by incrementing the index. If the index is equal to maxIndex,
then need factors array to store more elements
d.​ To store more elements, reset the maxIndex to twice its size, use the temp array to store
the elements from the factors array, and eventually assign the factors array to the temp
array
e.​ Finally, Display the factors of the number
import java.util.Scanner;

public class FactorFinder {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Take input for a number

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

int number = scanner.nextInt();

// Initialize variables

14
int maxFactor = 10;

int[] factors = new int[maxFactor];

int index = 0;

// Find factors

for (int i = 1; i <= number; i++) {

if (number % i == 0) {

// Add factor to the array

if (index == maxFactor) {

// Resize the array if needed

maxFactor *= 2;

int[] temp = new int[maxFactor];

System.arraycopy(factors, 0, temp, 0,
factors.length);

factors = temp;

factors[index++] = i;

// Display the factors

System.out.println("Factors of " + number + ":");

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

System.out.print(factors[i] + " ");

scanner.close();

15
9.​ Working with Multi-Dimensional Arrays. Write a Java program to create a 2D Array and
Copy the 2D Array into a single dimension array
Hint =>
a.​ Take user input for rows and columns, create a 2D array (Matrix), and take the user input
b.​ Copy the elements of the matrix to a 1D array. For this create a 1D array of size
rows*columns as in int[] array = new int[rows * columns];
c.​ Define the index variable and Loop through the 2D array. Copy every element of the 2D
array into the 1D array and increment the index
d.​ Note: For looping through the 2D array, you will need Nested for loop, Outer for loop for
rows, and the inner for loops to access each element
import java.util.Scanner;

public class MatrixToArrayConverter {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Take user input for rows and columns

System.out.print("Enter number of rows: ");

int rows = scanner.nextInt();

System.out.print("Enter number of columns: ");

int columns = scanner.nextInt();

// Create a 2D array (matrix)

int[][] matrix = new int[rows][columns];

// Take user input to fill the 2D array

System.out.println("Enter elements of the matrix:");

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

for (int j = 0; j < columns; j++) {

16
matrix[i][j] = scanner.nextInt();

// Create a 1D array to copy elements from the 2D array

int[] array = new int[rows * columns];

int index = 0;

// Copy elements from the 2D array to the 1D array

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

for (int j = 0; j < columns; j++) {

array[index++] = matrix[i][j];

// Display the 1D array

System.out.println("Elements in the 1D array:");

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

System.out.print(array[i] + " ");

scanner.close();

10.​Write a program FizzBuzz, take a number as user input and if it is a positive integer loop
from 0 to the number and save the number, but for multiples of 3 save "Fizz" instead of the
number, for multiples of 5 save "Buzz", and for multiples of both save "FizzBuzz". Finally,

17
print the array results for each index position in the format Position 1 = 1, …, Position 3 =
Fizz,...
Hint =>
a.​ Create a String Array to save the results and
b.​ Finally, loop again to show the results of the array based on the index position
import java.util.Scanner;

public class FizzBuzz {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Take user input for a positive integer

System.out.print("Enter a positive integer: ");

int number = scanner.nextInt();

// Create a String array to save the results

String[] results = new String[number + 1];

// Loop from 0 to the number and apply FizzBuzz logic

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

if (i % 3 == 0 && i % 5 == 0) {

results[i] = "FizzBuzz";

} else if (i % 3 == 0) {

results[i] = "Fizz";

} else if (i % 5 == 0) {

results[i] = "Buzz";

} else {

results[i] = String.valueOf(i);

18
}

// Print the results in the specified format

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

System.out.println("Position " + i + " = " +


results[i]);

scanner.close();

19

You might also like