Lab2: One-Dimensional Arrays in Java
Course: Computer Programming
Level: First Year – IT & AIDS
Topic: One-Dimensional Arrays in Java
Eng. Mohammed Ali
Lecture Objectives
• Understand the concept of one-dimensional arrays in Java.
• Declare and initialize arrays.
• Input and retrieve values from an array.
• Use loops to process array data.
• Solve practical problems using arrays.
Introduction to Arrays
▪ An array is a data structure that holds multiple values of the same type under a
single variable name.
▪ Importance of arrays:
• Organizes and manages data efficiently.
• Reduces the need for multiple separate variables.
• Enhances code readability and performance.
Array definition syntax in Java:
datatype [] arrayName;
OR
datatype arrayName[];
Declaring and Initializing One-Dimensional Arrays
A) Declaring an Array
int[] numbers; // Declaring an array
B) Allocating Memory for the Array
numbers = new int[5]; // Allocating memory for 5 elements
C) Declaring and Initializing in One Step
int[] numbers = {10, 20, 30, 40, 50};
D) Working with Different Data Types
double[] prices = {5.99, 10.49, 20.89};
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
String[] names = {"Ali", "Sara", "Omar"};
Accessing and Modifying Array Elements
int[] numbers = new int[3];
numbers[0] = 10; // Assigning a value
numbers[1] = 20;
numbers[2] = 30;
System.out.println(numbers[0]); // Output: 10
User-Defined Array Size
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
int[] numbers = new int[size];
Input and Output Operations
import java.util.Scanner;
public class ArrayInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] numbers = new int[5];
// Input values
for (int i = 0; i < numbers.length; i++) {
numbers[i] = scanner.nextInt();
}
// Output values
for (int num : numbers) {
System.out.println(num);
}
}
}
Processing Arrays with Loops
Using a for Loop
int[] numbers = {5, 10, 15, 20, 25};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Using an Enhanced for Loop
for (int num : numbers) {
System.out.println(num);
}
Common Mistakes When Using Arrays
A) Accessing an Index Out of Bounds
int[] numbers = new int[3];
numbers[3] = 10; // Error: Index 3 is out of bounds
B) Forgetting to Initialize an Array
int[] numbers;
numbers[0] = 5; // Error: numbers is not initialized
C) Using the Wrong Data Type
int[] numbers = {1, 2, 3};
numbers[0] = "Hello"; // Error: Incompatible data type
D) Incorrect Loop Condition
for (int i = 0; i <= numbers.length; i++) {
// Error: Should be i < numbers.length
System.out.println(numbers[i]);
}
Exercises
Exercise 1: Find the Maximum and Minimum Values
public class MinMaxArray {
public static void main(String[] args) {
int[] numbers = {34, 12, 56, 78, 1, 99};
int max = numbers[0], min = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) max = numbers[i];
if (numbers[i] < min) min = numbers[i];
}
System.out.println("Max: " + max);
System.out.println("Min: " + min);
}
}
Exercise 2: Calculate Sum and Average
public class SumAverage {
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25};
int sum = 0;
for (int num : numbers) {
sum += num;
}
double average = (double) sum / numbers.length;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
}
}
Exercise 3: Reverse an Array
public class ReverseArray {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(numbers[i] + " ");
}
}
}
Exercise 4: Search for an Element in an Array
Exercise 5: Count Even and Odd Numbers
Exercise 6: Rotate Array Elements to the Right
Exercise 7: Find Duplicate Elements in an Array
Exercise 8: Find the Missing Number in a Sequence
Exercise 9: Sort an Array in Ascending Order
Exercise 10: Find the Second Largest Number in an Array
Exercise 11: Find Common Elements Between Two Arrays
Exercise 12: Find the Most Repeated Number
Exercise 13: Sum of Two Arrays
Exercise 14: Merge Two Arrays
Exercise 15: Find Unique Elements in Two Arrays
Exercise 16: Multiply Corresponding Elements in Two Arrays
Exercise 17: Interleave Two Arrays
ن
، ثم العنرص األول من الثانية،مصفوفتي بطريقة متبادلة (العنرص األول من األوىل دمج
)وهكذا.
Exercise 18: Check If Two Arrays Are Equal
Exercise 19: Reverse Two Arrays and Store in a New One
package lab3arrays;
import java.util.Scanner;
public class Lab3Arrays {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//Input the size of Array from user
System.out.print("Enter the number of
subjects: ");
int size = sc.nextInt();
//Declaring and Allocating Memory for the
Array
int[] arr = new int[size];
// //Declaring and Initializing in One Step
// int arr2[] = {29, 38 , 49, 89};
// int sum = 0; //variable to sum elements of
array
// int max, min; //variables to store max and
min elements in array
//Loop to input elements of array from user
for (int i = 0; i < arr.length; i++) {
System.out.print("Enter the subject " +
(i + 1) + ": ");
arr[i] = sc.nextInt();
}
//Exercise 6: Rotate Array Elements to the
Right
int last = arr[arr.length-1];
for(int i = arr.length-1; i > 0;i--){
arr[i]= arr[i-1];
}
arr[0] = last;
// //Exercise 4: Search for an Element
in an Array (And Delete)
// System.out.println("Enter x : ");
// int x = sc.nextInt();
// boolean found = false;
// int index = -1;
// int c =0;
// for (int i = 0; i < arr.length; i++) {
// if (x == arr[i]) {
//// found = true;
//// System.out.println("x is found in
"+ i);
//// index = i;
//// c++;
//// arr[i] =0;
// for(int j = i; j < arr.length-1;
j++){
// arr[j] = arr[j+1];
// }
// arr[arr.length-1]= 0;
// break;
// }
// }
// if (c > 0) {
// System.out.println("x is found "+ c + "
times");
// } else {
// System.out.println("x is not found");
// }
// //Exercise 2: Calculate Sum and Average
// //Sum elements of Array Using Enhanced for
loop
// for( int num : arr){
// sum+= num;
// }
//
// double avg = (double)sum/size;
// System.out.println("max = "+ max+ " \nmin =
"+ min+" \nsum = "+ sum+"\n avg = "+avg);
// //Exercise 1: Find the Maximum and
Minimum Values
// min = max = arr[0];
//
// for(int i = 0; i <arr.length; i++){
//// if(arr[i]> max ) max= arr[i];
// max = arr[i]> max ? arr[i] : max;
// min = arr[i] < min? arr[i]: min;
//
// }
//
// //Exercise 7: Find Duplicate Elements in an
Array
// for(int i =0; i <arr.length; i++){
// int c =0;
// for(int j = i+1; j <arr.length; j++){
// if(arr[i]== arr[j]){
// c++;
// }
// }
// if(c > 0){
// System.out.println(arr[i]+" is
duplicated "+ (c+1) + " times");
// }
// }
// //Exercise 9: Sort an Array in Ascending
Order
// int arr2 []= new int [5];
// for(int i =0; i < arr2.length; i++){
// arr2[i] = sc.nextInt();
// }
// for(int i = 0; i < arr.length;i++){
// for(int j = i; j < arr.length; j++){
// if(arr[i] < arr[j]){
// int temp = arr[i];
// arr[i] = arr[j];
// arr[j] = temp;
// }
// }
// }
// //Print Elements of Array
for(int num: arr){
System.out.println(num);
}
// //Exercise 3: Reverse an Array
// for(int i = arr.length-1; i >=0; i--){
// System.out.println(arr[i]);
// }