sample SLM (1)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

Array

Table of Contents

1.1. Introduction
1.2. Type of Arrays
1.2.1 One-dimensional Array
1.2.2 Multi-dimensional Array
1.3. Application of Array
1.4. Advantages
1.5. Disadvantages
1.6. Summary
1.7. Case Study
1.8. Terminal Questions
1.9. Answer
1.10. References

2
Learning Objectives

Understanding the concept of an array: Gain a clear understanding of what an


array is, its purpose, and its role in programming.

Declaring and initializing arrays: Learn how to declare an array, specify its size,
and initialize it with values.

Accessing array elements: Understand how to access individual elements within


an array using index notation and comprehend the concept of zero-based
indexing.

Performing operations on arrays: Learn various operations that can be performed


on arrays, such as adding or removing elements, sorting, searching, and
traversing the array.

3
1.1 Introduction

The array is a collection of elements of homogeneous data element elements.

Java array is an object which contains elements of a similar data type.


Additionally, the elements of an array are stored in a contiguous memory
location. It is a data structure where we store similar elements. We can store only
a fixed set of elements in a Java array.

• Array in Java is index-based, the first element of the array is stored at the 0th
index, and 2nd element is stored on the 1st index, and so on.

• At the time of array creation, it is necessary to specify the size of the array
otherwise we will get compile time error.

• It is legal to have an array with size “0”.

• If we take array size with a negative value then we will get a run time exception
that is a negative value exception.

• If we are trying to access an array element with out of range index we will get an
exception that is an array index out-of-bound exception.

• Length is a final variable that is applicable only to the array. Length represents
the size of the array.

Creating an Array:

1. Declaring the array.

2. Creating memory location for the array elements.

3. Putting the value of array elements into the memory locations.

4
1.2 Types of Arrays

There are two types of arrays.

1.2.1 Single Dimensional Array

You create a single-dimensional array using the new operator specifying the array
element type and the number of elements. The following example declares an array
of five integers.

Syntax:

DataType Array_Name [] =new DataType[Size_Of_Array];

Graphical Presentation:

int A = new int[5];

A[0] = 5;

A[1] = 6;

A[2] = 7;

A[3] = 8;

A[4] = 9;

Index 0 1 2 3 4

Value 5 6 7 8 9

CHECK YOUR PROGRESS

1. The index of the first element in a one-dimensional array is ___________.


2. The length of a one-dimensional array is obtained using the ________ property.
3. In Java, a one-dimensional array is a data structure that allows storing a fixed-size
________ of elements of the same data type.
4. The index of the last element in a one-dimensional array is ________.
5. . It is necessary to specify the size of array otherwise you will get __________ exception .

5
Example:

import java.util.Scanner;
public class One_D_Array
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the array size");


int size = sc.nextInt();

//Array syntax implementation


int A[]=new int[size];

System.out.println("Enter the array values");


for(int i=0;i<size;i++)
{
A[i]=sc.nextInt();
}
for(int i=0;i<size;i++)
{
System.out.print(A[i]+" ");
}
}
}

Input:

Enter the array size.


5
Enter the array values.
45678

Output:

45678

6
1.2.2 Multidimensional Array

Java, a multidimensional array is a data structure that allows you to store elements
in multiple dimensions, forming a matrix-like structure. It is essentially an array of
arrays, where each element of the outer array can itself be an array. This allows for
the creation of arrays with more than one dimension, such as two-dimensional
arrays (matrices), three-dimensional arrays.
Syntax:

DataType Array_Name[ ][ ] =new DataType[Row_Size][Col_Size];

Graphical Presentation:

int A [ ][ ] = new int[3][3];

A[0][0] = 5; A[0][1] = 5; A[0][2] = 5;

A[1][0] = 6; A[1][1] = 6; A[1][2] = 6;

A[2][0] = 7; A[2][1] = 7; A[2][2] = 7;

Column Column Column


5 5 5
0 1 2
0,0 index 0,1 index 0,2 index
Row
0 6 6 6
Row 1,0 index 1,1 index 1,2
1 index
Row 2,0 index 2,1 index 2,2 index
2 7 7 7

CHECK YOUR PROGRESS

1. In a two-dimensional array, the first index represents the ________ and the second index
represents the ________.
2. To assign initial values to the elements of a multidimensional array, you can use nested
________ statements.
3. To assign initial values to the elements of a multidimensional array, you can use nested
________ statements.
4. The row and column index always start from ________.
5. complete the loop to print 1, 2, 3 4, 5 (code = for(int I =____; i<_____;i++))
7
Example:
import java.util.Scanner;
public class One_D_Array
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the Row & Column size of 2D array");


int Row_size = sc.nextInt();
int Col_size = sc.nextInt();

//Array syntax implementation


int A[][]=new int[Row_size][Col_size];

System.out.println("Enter the array values");

for(int i=0;i<Row_size;i++)
{
for(int j=0;j<Col_size;j++)
{
A[i][j]=sc.nextInt();
}
}
for(int i=0;i<Row_size;i++)
{
for(int j=0;j<Col_size;j++)
{
System.out.print(A[i][j]+" ");
}
System.out.println();
}
}
}

Input:
Enter the Row & Column size of 2D array.
33
Enter the array values.
555
666
777
Output:
555
666
777

8
1.3 Applications of array

 Managing data collections: Arrays serve as a convenient means of managing


collections of data items that share a common type. For instance, an array of
integers can effectively store a series of numerical values.

 Handling matrices and tables: Arrays provide a practical approach to


handling matrices and tables. For instance, a two-dimensional array can be
utilized to store a matrix containing numerical values.

 Facilitating sorting and searching: Arrays are frequently employed for


sorting and searching data. For instance, in Java, the Arrays class offers
methods such as sort () and binary Search () that allow for sorting and searching
elements within an array.

 Supporting data structure implementations: Arrays serve as the


foundational data structure for various other data structures, including stacks,
queues, and heaps. For example, an array-based implementation of a stack can
be used to store elements within the stack.

 Enabling image processing: Arrays are commonly employed for storing pixel
values in image processing applications. For instance, a two-dimensional array
can be employed to store the RGB values of an image.

9
1.4 Advantages

1. Efficient memory usage: Arrays in Java offer efficient memory utilization since
they store elements of the same type in a contiguous block of memory, without
requiring additional memory for pointers or node structures.

2. Direct element access: Arrays allow for direct random access to elements
based on their index, enabling fast retrieval and modification of specific elements
without the need to traverse the entire data structure.

3. Efficient iteration: Arrays support efficient iteration over elements using simple
for loops, allowing for quick processing of each element in the array

4. Cache locality: Due to their contiguous memory layout, arrays benefit from
cache locality, which improves data access speed by leveraging hardware
caching mechanisms.

5. Simplified implementation of algorithms: Many algorithms, such as sorting


and searching, are designed to work efficiently with arrays. Utilizing arrays in Java
simplifies the implementation of such algorithms, as they can directly operate on
the array elements without the need for complex data structures.

10
1.5 Disadvantages

1. Fixed size: Arrays in Java have a fixed size and cannot be dynamically resized,
requiring manual management or the creation of new arrays when the size needs
to change.

2. Inefficient insertions and deletions: Inserting or deleting elements in the


middle of an array requires shifting the existing elements, resulting in inefficiency
and potentially slower performance.

3. Wasted memory: If an array is initialized with a larger size than necessary,


there may be unused memory space, leading to inefficient memory usage.

4. Limited data type flexibility: Arrays in Java can only store elements of the
same type, making them less flexible for scenarios that require storing different
data types within a single data structure.

5. Lack of built-in methods: Arrays do not have built-in methods for common
operations like sorting or searching, requiring manual implementation or relying
on external libraries for such functionalities.

11
1.6 Summary

 Arrays in Java are a fundamental data structure that offer several advantages
and disadvantages. One of the main advantages of arrays is their efficient
memory usage.

 They store elements of the same type in contiguous memory locations,


eliminating the need for additional memory allocations for pointers or node
structures. This results in efficient memory utilization and faster access to
elements.

 Another advantage of arrays is their ability to provide direct and fast access to
elements through indexing. This allows for quick retrieval and modification of
specific elements without the need to traverse the entire data structure.

 Arrays also support simple iteration using standard loops, making it easy to
process each element sequentially.
 Arrays have some limitations as well. One significant disadvantage is their
fixed size. Once an array is created, its length cannot be changed, requiring
manual management or the creation of new arrays when the size needs to be
adjusted.

 This can lead to inefficient memory usage or the need for frequent resizing in
dynamic scenarios.

 Additionally, inserting or deleting elements in the middle of an array can be


inefficient. It requires shifting existing elements, resulting in slower
performance .

 Time complexity of O(n), where n is the number of elements in the array.


Arrays also have limited flexibility in terms of storing different data types, as
they can only store elements of the same type.

 Arrays in Java do not provide built-in methods for common operations like
sorting or searching, requiring manual implementation or relying on external
libraries for such functionalities.

 Arrays in Java are a powerful data structure with efficient memory usage and
fast element access, but their fixed size and limitations in dynamic scenarios
can be a drawback.

12
1.7 Case Study

A company wants to develop a sales analytics dashboard to track the performance


of its products across different regions. The dashboard should display key metrics,
such as total sales, average sales, and highest-selling products, for each region. The
company aims to gain insights into product popularity and identify regions that
require more attention.

Solution:
To implement the sales analytics dashboard, we can utilize arrays to store and
analyze the sales data efficiently.
1.Define the Array Structure:
We can create an array to represent each region and store sales data for each
product. Each element of the array would correspond to a specific region.

2. Initialize the Array:


Create an array to represent different regions and initialize it with the relevant sales
data.

Region Sales (in thousands)


---------------------------------
Region 1 150
Region 2 220
Region 3 180
Region 4 300

3. Perform Analysis: Using the sales data stored in the array, we can perform
various analyses to gain insights into product performance.
 Total Sales: Sum up the sales values for each region to determine the overall
sales performance.
 Average Sales: Calculate the average sales across regions by dividing the
total sales by the number of regions.
 Highest-Selling Product: Identify the region with the highest sales value to
determine the highest-selling product.
For example, using the array above, we can perform the following
calculations:
Total Sales: 150 + 220 + 180 + 300 = 850 thousand
Average Sales: 850 thousand / 4 regions = 212.5 thousand
Highest-Selling Product: Region 4 with 300 thousand sales
These analyses provide valuable insights into the sales performance across
different regions, helping the company make informed decisions and
prioritize efforts for specific products or regions.

13
Visualization:
To present the sales data in an easily understandable format, the company
can create visualizations such as bar charts, line graphs, or pie charts. These
visualizations can display the total sales, average sales, and highest-selling
products for each region, enabling stakeholders to quickly interpret the data
and identify trends or areas of improvement.
By utilizing arrays to store and analyses sales data, the company can
effectively monitor product performance across regions and make data-
driven decisions to optimize sales strategies and resource allocation.

14
1.8 Terminal Questions

SHORT ANSWER QUESTIONS

1. Can an array in Java store elements of different data types?


2. What is the default value of an element in an integer array if it is not explicitly
initialized?
3. How do you find the minimum value in an array in Java?
4. How do you find the average value of elements in an array in Java?
5. How do you reverse the order of elements in an array in Java?

LONG ANSWER QUESTIONS

1. Explain the process of declaring an array in Java, including the syntax, data type,
and the various ways to initialize an array. Provide examples to illustrate your
explanations.

2. Explain whether it is possible to change the size of an array once it is declared


and initialized. If not, provide a detailed explanation of why it is not allowed.
Additionally, discuss any alternative approaches or data structures that can be
used if dynamic resizing of arrays is required in a program.

3. Describe the method or operator used to obtain the length of an array, including
its syntax and return value.

4. How would you sort an array of integers in ascending order in Java? Provide the
code snippet for your solution.

5. Imagine you are working on a game development project. How would you employ
arrays in Java to represent and manage the game board, such as storing the
positions of game characters or recording the state of different game tiles?

15
MCQ QUESTIONS

1. Which of the following statements is true about a one-dimensional array?


a) It can store elements of different data types.
b) It is a collection of elements arranged in multiple rows and columns.
c) It can only store a single element at a time.
d) It is a collection of elements arranged in a single row.

2. How do you declare a one-dimensional array in most programming languages?


a) array<datatype> arrayName[];
b) arrayName[datatype];
c) datatype[] arrayName;
d) arrayName = new array[datatype];

3. How do you access an element in a multidimensional array?


a) arrayName[element];
b) arrayName[row, column];
c) arrayName(element);
d) arrayName(element, index);

4. Which of the following represents a valid declaration of a two-dimensional array in


most programming languages?
a) array<datatype, rows, columns> arrayName;
b) datatype[][] arrayName;
c) arrayName[rows, columns];
d) arrayName = new array[rows][columns];

5. Which of the following operations is NOT typically supported on arrays?


a) Inserting an element at a specific position
b) Removing an element from a specific position
c) Sorting the elements in ascending order
d) Finding the length or size of the array

6. What is the time complexity for accessing an element in an array?


a) O(1)
b) O(log n)
c) O(n)
d) It depends on the size of the array.

7. How do you find the length of an array in Java?


a) By calling the length() method on the array object.
b) By calling the count() method on the array object.
c) By using the length property of the array.
d) By using the size() method on the array.

16
8. How do you access the third element in an array named numbers?
a) numbers[2]
b) numbers[3]
c) numbers(3)
d) numbers.Get(2)

9. Can an array in Java store elements of different data types?


a) Yes, arrays can store elements of different data types.
b) No, arrays can only store elements of the same data type.
c) It depends on the size of the array.
d) Arrays can only store objects, not primitive types.

10. How do you find the maximum value in an array in Java?


a) By using the max() method of the Arrays class.
b) By iterating over the array and comparing elements.
c) By calling the maximum () method on the array.
d) By sorting the array and retrieving the last element.

1.9 Answers

SHORT ANSWER QUESTIONS

1. To solve by student
2. In Java, the default value of an element in an integer array is 0 if it is not explicitly
initialized. When an array of integers is created, each element in the array is assigned a
default value based on its data type. For integers, the default value is 0. This means
that if you do not provide a specific value for an element in an integer array during
initialization, it will automatically be set to 0. It's important to note that other types of
arrays, such as boolean arrays, will have different default values (e.g., false for
booleans) if not explicitly initialized.
3. To solve by student
4. To find the average value of elements in an array in Java, you can follow these
steps:
1. Initialize a variable to hold the sum of all the elements in the array. Let's call it
sum and set it to 0.
2. Iterate over each element in the array using a loop.
3. Add each element to the sum variable.
4. After the loop completes, calculate the average by dividing the sum by the total
number of elements in the array.
5. Optionally, round the average to the desired decimal places if needed.
Here's an example code snippet to demonstrate this:

In this example, we calculate the average of the numbers array by summing up


all the elements and dividing it by the length of the array. The (double) casting
is done to ensure floating-point division and obtain an accurate average value.
17
18
public class Average
{
public static void main(String [] args)
{
int[] numbers = {5, 10, 15, 20, 25};
int sum = 0;

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


sum += numbers[i];
}
double average = (double) sum / numbers.length;

System.out.println("Average: " + average);

}
}

Output:
Average: 15.0

Explanation:
The program calculates the average value of the elements in the numbers array.
• The array numbers contains the values: 5, 10, 15, 20, and 25.
• The variable sum is initialized to 0.
• The for loop iterates over each element in the numbers array.
• In each iteration, the current element is added to the sum variable.
• After the loop completes, the average is calculated by dividing the sum by
the length of the numbers array.
• The resulting average, 15.0, is then printed to the console using
System.out.println().
Therefore, the output will be "Average: 15.0".

5. To reverse the order of elements in an array in Java, you can use the following
approach:

1. Determine the midpoint of the array by dividing the length of the array by 2.
2. Iterate over the array from the start index (0) to the midpoint.
3. Swap the elements at the current index with the corresponding element
from the end of the array.
4. Continue swapping elements until you reach the midpoint.
5. The array will be reversed once the swapping is complete.
6. Here's an example code snippet that demonstrates this approach:

19
public class reverse
{
public static void main(String [] args)
{
int[] numbers = {1, 2, 3, 4, 5};
int length = numbers.length;
int midpoint = length / 2;

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


int temp = numbers[i];
numbers[i] = numbers[length - 1 - i];
numbers[length - 1 - i] = temp;
}

// Print the reversed array


for (int i = 0; i < length; i++) {
System.out.print(numbers[i] + " ");
}
}
}

Output :
54321

Explanation:
The program reverses the order of elements in the numbers array using a loop and
swapping the elements.

The array numbers contain the values: 1, 2, 3, 4, and 5.


The length of the array is stored in the variable length.
The midpoint of the array is calculated by dividing the length by 2 and stored in the
variable midpoint.
The for loop iterates over the array from index 0 to the midpoint.
In each iteration, the current element at index i is swapped with the corresponding
element from the end of the array using a temporary variable temp.
After the loop completes, the reversed array is printed using a separate loop that goes
from index 0 to the length of the array.
The elements are printed separated by spaces using System.out.print().
Therefore, the output will be "5 4 3 2 1", which represents the reversed order of the
elements in the numbers array.

20
LONG ANSWER QUESTIONS

1. Specify the size and initialize the elements later:

dataType arrayName []= new dataType[arraySize];

In this method, you declare the array with a specific size, and the elements are
initialized to default values based on their data type. For example:

Int numbers []= new int[5];

This declares an integer array named numbers with a size of 5. The elements of
the array are initialized to the default value for integers, which is 0.
2 . To solve by student

3. In Java, to obtain the length of an array, you can use the length property of
the array. The length property provides the number of elements present in the
array. Here's the syntax and details regarding its usage:
Syntax:
arrayName.length
Here, arrayName refers to the name of the array for which you want to
determine the length.
Return Value: The length property returns an integer value representing the
number of elements in the array. The length is always a non-negative value.

int[] numbers = {1, 2, 3, 4, 5};


int arrayLength = numbers.length;
System.out.println("Length of the array: " + arrayLength);

4. In Java, you can sort an array of integers in ascending order using the
Arrays.sort() method from the java.util package. Here's the code snippet to
accomplish this:

import java.util.Arrays;

public class Main {


public static void main(String[] args) {
int[] numbers = {5, 2, 8, 1, 4};

// Sort the array in ascending order


Arrays.sort(numbers);

// Print the sorted array


for (int number : numbers) {
System.out.print(number + " ");
}
}
}
Output:
12458

21
MCQ QUESTIONS ANSWER

1. d) It is a collection of elements arranged in a single row.


2. c) datatype [] arrayName;
3. b) arrayName[row, column];
4. b) datatype [] [] arrayName;
5. a) Inserting an element at a specific position
6. a) O (1)
7. c) By using the length property of the array.
8. a) numbers [2]
9. b) No, arrays can only store elements of the same data type.
10. b) By iterating over the array and comparing elements.

22
1.9 References

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
https://www.baeldung.com/java-arrays-guide#:~:text=According%20to%20the
%20Java%20documentation,a%20variable%20holding%20a%20value
https://jenkov.com/tutorials/java/arrays.html#:~:text=A%20Java%20Array%20is
%20a,array%20later%20in%20this%20text.

23

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy