Programming 1 - Arrays in Java - Chapter 11 - PDF

Document Details

BlissfulSimile6171

Uploaded by BlissfulSimile6171

Universidad de Dagupan

JanNarvasa

Tags

arrays java programming programming computer science

Summary

This document provides a detailed explanation of one-dimensional and two-dimensional arrays in Java. It covers array declaration, initialization, element access, iteration techniques (like for loops and enhanced for loops), and operations like finding the sum and maximum value. It also includes examples to illustrate the concepts.

Full Transcript

UNIVERSIDAD DE DAGUPAN ITC02: PROGRAMMING 1 School of Information Technology Education FINALS Chapter 11: Array Management in Java: Handling One-Dimensional and Two-Dimensional Arrays An array is a collection of variables that share the sam...

UNIVERSIDAD DE DAGUPAN ITC02: PROGRAMMING 1 School of Information Technology Education FINALS Chapter 11: Array Management in Java: Handling One-Dimensional and Two-Dimensional Arrays An array is a collection of variables that share the same data type, stored in contiguous memory locations. Arrays are used to store multiple values in a single variable, making it easier to manage related data. Key Characteristics of Arrays:  Fixed size: Once an array is declared, its size cannot be changed.  Homogeneous: All elements in an array must be of the same data type.  Index-based: Array elements are accessed using their index, starting from 0. 1. One-Dimensional Arrays -A one-dimensional array is a simple list of elements. -These is the most common type of arrays, where elements are stored in a linear order. A) Declaration and Initialization 1. Syntax dataType[] arrayName; // Declaration arrayName = new dataType[size]; // Initialization 2. Example int[] numbers = new int; // Declaring and initializing an array of size 5 3. Shortcut for Declaration and Initialization int[] numbers = {10, 20, 30, 40, 50}; // Declares and initializes in one step B) Accessing Elements -Use the index to access elements. Example: System.out.println(numbers); // Accesses the first element (10) C) Iterating Through a One-Dimensional Array -Use Loops to traverse the array  For Loop: for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); }  Enhanced For Loop: for (int num : numbers) { System.out.println(num); } D) Operations on One-Dimensional Arrays 1) Finding the sum: int sum = 0; for (int num : numbers) { sum += num; } System.out.println("Sum: " + sum); JanNarvasa UNIVERSIDAD DE DAGUPAN ITC02: PROGRAMMING 1 School of Information Technology Education FINALS 2) Finding the Maximum Value: int max = numbers; for (int num : numbers) { if (num > max) { max = num; } } System.out.println("Max: " + max); 2. Two-Dimensional Arrays -A two-dimensional array is a collection of arrays, organized in rows and columns, resembling a matrix. A) Declaration and Initialization 1. Syntax dataType[][] arrayName; // Declaration arrayName = new dataType[rows][columns]; // Initialization 2. Example int[][] matrix = new int; // 3x3 matrix 3. Shortcut for Declaration and Initialization int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; B) Accessing Elements -Access elements using two indices: one for the row and one for the column. Example: System.out.println(matrix); // Accesses the element at row 0, column 0 (1) C) Iterating Through a Two-Dimensional Array -Use nested loops to traverse the array.  Nested For Loop: for (int i = 0; i < matrix.length; i++) { // Loop through rows for (int j = 0; j < matrix[i].length; j++) { // Loop through columns System.out.print(matrix[i][j] + " "); } System.out.println(); // New line after each row } D) Operations on Two-Dimensional Arrays 1) Sum of All Elements: int sum = 0; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { sum += matrix[i][j]; } } System.out.println("Sum: " + sum); JanNarvasa UNIVERSIDAD DE DAGUPAN ITC02: PROGRAMMING 1 School of Information Technology Education FINALS 2) Transpose of a Matrix: int[][] transpose = new int; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { transpose[j][i] = matrix[i][j]; } } 3. Common Errors and How to Avoid Them 1. ArrayIndexOutOfBoundsException:  Occurs when trying to access an index outside the array bounds.  Solution: Always ensure the index is within 0 to array.length - 1. 2. NullPointerException:  Happens when trying to access or modify an uninitialized array.  Solution: Ensure the array is initialized before use. 3. Incompatible Types:  Trying to store data of the wrong type.  Solution: Ensure the data type matches the array type. 4. Difference and Advantages of One-Dimensional and Two-Dimensional Arrays in Java Aspect One-Dimensional Array Two-Dimensional Array A linear array where elements are stored A matrix-like array where elements are stored in Definition in a single row. rows and columns. A list of elements represented as: [10, 20, Structure A grid of elements represented as: [[1, 2], [3, 4]] 30, 40] Declaration dataType[] arrayName; dataType[][] arrayName; Syntax Access elements using a single index: Access elements using two indices: Access Syntax arrayName[index] arrayName[row][column] Ideal for storing data in a single Useful for tabular data, like matrices, chess Usage sequence, like marks of students, boards, or spreadsheets. temperatures, etc. Contiguous block of memory in a single Contiguous memory blocks for each row, Memory Layout row. forming a structure of rows and columns. Simpler to manage and iterate over More complex to manage as it requires nested Complexity since it involves a single loop. loops for traversal and manipulation. Initialization Can be initialized as: int[] arr = {1, 2, 3}; Can be initialized as: int[][] matrix = {{1, 2}, {3, 4}}; - Can represent multidimensional relationships Advantages - Easy to declare and use. easily. - Requires less memory than - Suitable for visual representations and complex multidimensional arrays. datasets. JanNarvasa UNIVERSIDAD DE DAGUPAN ITC02: PROGRAMMING 1 School of Information Technology Education FINALS Aspect One-Dimensional Array Two-Dimensional Array - Easier for beginners to understand and - Helps in solving mathematical and scientific manipulate. problems involving grids and matrices. Better performance for smaller or linear Better suited for structured data but may require Performance datasets. more memory and computational overhead. Example - Representing a game board (e.g., chess or tic- - Storing marks of students in a class. Application tac-toe). Key Takeaways:  One-Dimensional Arrays: Simpler and more efficient for linear data.  Two-Dimensional Arrays: Essential for working with structured or relational data like tables or grids. JanNarvasa UNIVERSIDAD DE DAGUPAN ITC02: PROGRAMMING 1 School of Information Technology Education FINALS Activity: Answer the following items and write your answers on a 1/4 Sheet of Yellow pad paper. 1) What is the starting index of an array in Java? a) 0 c) -1 b) 1 d) 2 2) How do you declare an array in Java? a) int array[]; c) int[] array; b) array int[]; d) Both a and c 3) What does array.length return? a) Size of the array c) Elements of the array b) Last index of the array d) None of the above 4) What is the syntax to initialize a two-dimensional array? a) int[][] arr = new int; c) int arr = {2, 3}; b) int arr; d) int[][] arr = int; 5) What happens when you access an index outside the array bounds? a) ArrayIndexOutOfBoundsException c) Compilation Error b) NullPointerException d) Segmentation Fault 6) Which of the following is correct for initializing a one-dimensional array? a) int[] arr = {1, 2, 3}; c) int arr = new int[]; b) int arr[] = new int(3); d) int arr = new int{1, 2, 3}; 7) Which keyword is used to allocate memory for an array? a) allocate c) new b) memory d) create 8) What is a two-dimensional array often referred to as? a) Matrix c) Table b) Grid d) All of the above 9) In a one-dimensional array, the index of the last element is: a) array.length c) array.length + 1 b) array.length - 1 d) 0 10) Which of these is an example of a valid array declaration? a) int arr; c) int[] arr = new int; b) int arr = {1, 2, 3, 4, 5}; d) int arr = {1, 2, 3}; JanNarvasa

Use Quizgecko on...
Browser
Browser