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

Computer Arrays

Class 10th icse computer application chapter arrays

Uploaded by

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

Computer Arrays

Class 10th icse computer application chapter arrays

Uploaded by

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

S.J.B.S.

S PUBLIC SCHOOL
2nd Block, Rajajinagar,Bangalore-560010

An Internal Assessment based on computer applications

In the partial fulfillment of the requirement for The Indian Certificate Of


Secondary Examination.

Topic: Arrays

Under the guidance of


Mrs. Roopashree Mam
Submitted by : - Abhay.S.J
Class: - 10th standard
Roll no: - 01
Contents
1.Array.
2.The length of an array.
3.Types of Array.
4.Single Dimensional Array.
5.Multidimensional Array.
6.Advantage of an Array.
7.Disadvantages of an Array.
8.Searching.
 Linear search.
 Binary search.
9.Sorting.
 Bubble Sort.
 Selection Sort.
1.Arrays in Java

Arrays are fundamental structures in Java that allow us to store multiple


values of the same type in a single variable. They are useful for managing
collections of data efficiently. Arrays in Java work differently than they do in
C/C++. This article covers the basics and in-depth explanations with examples
of array declaration, creation, and manipulation in Java.
Arrays are fundamental to Java programming. They allow you to store and
manipulate collections of data efficiently. If you’re looking to get hands-on
with more complex array operations and learn advanced techniques, the Java
Programming Course offers a structured approach to mastering arrays in Java.
Basics of Arrays in Java
Array Declaration
To declare an array in Java, use the following syntax:
type[] arrayName;
 type: The data type of the array elements (e.g., int, String).
 arrayName: The name of the array.
Array Declaration Example:
Here’s an example of declaring an integer array:
int[] numbers; // Declaring an integer array
 This statement declares an array named numbers that will hold
integers. Note: The array is not yet initialized.
Create an Array
To create an array, you need to allocate memory for it using
the new keyword:
numbers = new int[5]; // Creating an array of 5 integers
 This statement initializes the numbers array to hold 5 integers. The
default value for each element is 0.
Access an Element of an Array
We can access array elements using their index, which starts from 0:
numbers[0] = 10; // Setting the first element of the array
int firstElement = numbers[0]; // Accessing the first element
 The first line sets the value of the first element to 10. The second line
retrieves the value of the first element.
Change an Array Element
To change an element, assign a new value to a specific index:
numbers[0] = 20; // Changing the first element to 20
 This statement updates the value of the first element from 10 to 20.
2.Array Length
We can get the length of an array using the length property:
int length = numbers.length; // Getting the length of the array
This retrieves the number of elements in the numbers array, which is 5 in this
case.
The above are the basic details of Arrays in Java. Now, if you want to go
through the in-depth concepts of Java Arrays, then scroll down below and go
through the diagrams, examples, and explanations.
In-depth Concepts of Java Array
Following are some important points about Java arrays.
Arrays in Java
 In Java, all arrays are dynamically allocated.
 Arrays may be stored in contiguous memory [consecutive memory
locations].
 Since arrays are objects in Java, we can find their length using the
object property length. This is different from C/C++, where we find
length using size of.
 A Java array variable can also be declared like other variables with []
after the data type.
 The variables in the array are ordered, and each has an index beginning
with 0.
 Java array can also be used as a static field, a local variable, or a
method parameter.
An array can contain primitives (int, char, etc.) and object (or non-primitive)
references of a class, depending on the definition of the array. In the case of
primitive data types, the actual values might be stored in contiguous memory
locations (JVM does not guarantee this behavior). In the case of class
objects, the actual objects are stored in a heap segment. To learn more about
Java Array, go through Java programming course here.

Note: This storage of arrays helps us randomly access the elements of an


array [Support Random Access].
Creating, Initializing, and Accessing an Arrays in Java
The general form of array declaration is
-- type var-name[];
-- type[] var-name;
 An array declaration has two components: the type and the name.
 type declares the element type of the array.
 The element type determines the data type of each element that
comprises the array.
 Like an array of integers, we can also create an array of other primitive
data types like char, float, double, etc., or user-defined data types
(objects of a class).
 Thus, the element type for the array determines what type of data the
array will hold.
4.Single dimensional arrays

5. Multi-Dimensional Arrays
Arrays with more than one dimension, such as two-dimensional arrays
(matrices).
int[][] multiDimArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}; // A 2D array (matrix)
You can also access java arrays using for each loops.
Arrays of Objects in Java
An array of objects is created like an array of primitive-type data items in the
following way.
Student[] arr = new Student[5]; //Student is a user-defined class
Syntax:
-- data type[] arrName;
-- datatype arrName[];
-- datatype [] arrName;
Example of Arrays of Objects
Example 1:
Below is the implementation of the above mentioned topic:
Java
import java.io.*;

class GFG {
public static void main (String[] args) {

int [] arr=new int [4];


// 4 is the size of arr

System.out.println("Array Size:"+arr.length);
}
}

Output
Array Size:4
 The Student Array contains five memory spaces each of the size of
Student class in which the address of five Student objects can be
stored.
 The Student objects have to be instantiated using the constructor of
the Student class, and their references should be assigned to the array
elements in the following way.
Example 2:
Below is the implementation of the above mentioned topic:
Java
// Java program to illustrate creating
// an array of objects
class Student {
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
this.name = name;
}
}

// Elements of the array are objects of a class Student.


public class GFG {
public static void main(String[] args)
{
// declares an Array of Student
Student[] arr;

// allocating memory for 5 objects of type Student.


arr = new Student[5];

// initialize the first elements of the array


arr[0] = new Student(1, "aman");

// initialize the second elements of the array


arr[1] = new Student(2, "vaibhav");
// so on...
arr[2] = new Student(3, "shikar");
arr[3] = new Student(4, "dharmesh");
arr[4] = new Student(5, "mohit");

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at " + i + " : "
+ arr[i].roll_no + " "
+ arr[i].name);
}
}

Output
Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space : O(1)
Example 3:
An array of objects is also created like :
Java
// Java program to illustrate creating
// an array of objects
class Student
{

public String name;


Student(String name)
{
this.name = name;
}
@Override
public String toString(){
return name;
}
}

// Elements of the array are objects of a class Student.


public class GFG
{
public static void main (String[] args)
{
// declares an Array and initializing the elements of the array
Student[] myStudents = new Student[]{new Student("Dharma"),new
Student("sanvi"),new Student("Rupa"),new Student("Ajay")};

// accessing the elements of the specified array


for(Student m:myStudents){
System.out.println(m);
}
}
}

Output
Dharma
sanvi
Rupa
Ajay
What happens if we try to access elements outside the array size?
JVM throws ArrayIndexOutOfBoundsException to indicate that the array has
been accessed with an illegal index. The index is either negative or greater
than or equal to the size of an array.
Below code shows what happens if we try to access elements outside the
array size:
Java
// Code for showing error "ArrayIndexOutOfBoundsException"

public class GFG {


public static void main(String[] args)
{
int[] arr = new int[4];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
System.out.println(
"Trying to access element outside the size of array");
System.out.println(arr[5]);
}
}
Output
Trying to access element outside the size of array
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 5 out of bounds for length 4
at GFG.main(GFG.java:13)
Example (Iterating the array):
Java
public class GFG {
public static void main(String[] args)
{
int[] arr = new int[2];
arr[0] = 10;
arr[1] = 20;

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


System.out.println(arr[i]);
}
}

Output
10
20
Complexity of the above method:
Time Complexity: O(n),here n is size of array.
Auxiliary Space: O(1), since no extra space required.
Multidimensional Arrays in Java
Multidimensional arrays are arrays of arrays with each element of the array
holding the reference of other arrays. These are also known as Jagged Arrays.
A multidimensional array is created by appending one set of square brackets
([]) per dimension.
Syntax:
There are 2 methods to declare Java Multidimensional Arrays as mentioned
below:
datatype [][] arrayrefvariable;
datatype arrayrefvariable[][];

Declaration:
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
Java Multidimensional Arrays Examples
Example 1:
6.Advantages of Java Arrays
 Efficient Access: Accessing an element by its index is fast and has
constant time complexity, O(1).
 Memory Management: Arrays have fixed size, which makes memory
management straightforward and predictable.
 Data Organization: Arrays help organize data in a structured manner,
making it easier to manage related elements.
7.Disadvantages of Java Arrays
 Fixed Size: Once an array is created, its size cannot be changed, which
can lead to memory waste if the size is overestimated or insufficient
storage if underestimated.
 Type Homogeneity: Arrays can only store elements of the same data
type, which may require additional handling for mixed types of data.
 Insertion and Deletion: Inserting or deleting elements, especially in the
middle of an array, can be costly as it may require shifting elements.

8. Searching in Arrays
8.1 Linear Search
Linear search is the simplest searching algorithm. It works by checking each
element of the array sequentially until the desired element is found or the
end of the array is reached.
Steps:
Start from the first element of the array.
Compare each element with the target element.
If the target element is found, return its index.
If the target element is not found after checking all elements, return -1.
Time Complexity: O(n), where n is the number of elements in the array.
Example:
java
Copy code
public class LinearSearch {
public static int linearSearch(int[] array, int target) {
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
return i; // Element found
}
}
return -1; // Element not found
}
public static void main(String[] args) {
int[] numbers = {5, 8, 12, 14, 17, 20};
int target = 14;
int result = linearSearch(numbers, target);
if (result != -1) {
System.out.println("Element found at index: " + result);
} else {
System.out.println("Element not found.");
}
}
}
8.2 Binary Search
Binary search is a more efficient search algorithm than linear search.
However, it requires the array to be sorted. Binary search works by
repeatedly dividing the array in half and determining which half contains the
target element.
Steps:
Find the middle element of the array.
If the target element is equal to the middle element, return its index.
If the target element is smaller than the middle element, repeat the search in
the left half of the array.
If the target element is larger than the middle element, repeat the search in
the right half of the array.
Time Complexity: O(log n), where n is the number of elements in the array.
Example:
java
Copy code
public class BinarySearch {
public static int binarySearch(int[] array, int target) {
int left = 0;
int right = array.length - 1;
while (left <= right) {
int middle = left + (right - left) / 2;
if (array[middle] == target) {
return middle; // Element found
}
if (array[middle] < target) {
left = middle + 1;
} else {
right = middle - 1;
}
}
return -1; // Element not found
}
public static void main(String[] args) {
int[] numbers = {5, 8, 12, 14, 17, 20};
int target = 17;
int result = binarySearch(numbers, target);
if (result != -1) {
System.out.println("Element found at index: " + result);
} else {
System.out.println("Element not found.");
}
}
}
9. Sorting in Arrays
9.1 Bubble Sort
Bubble sort is a simple sorting algorithm that repeatedly steps through the
array, compares adjacent elements, and swaps them if they are in the wrong
order. The pass through the array is repeated until the array is sorted.
Steps:
Start at the beginning of the array.
Compare the first two elements. If the first is greater than the second, swap
them.
Move to the next pair of elements and repeat the process.
Repeat this process for multiple passes until no more swaps are needed.
Time Complexity: O(n^2), where n is the number of elements in the array.
Example:
java
Copy code
public class BubbleSort {
public static void bubbleSort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
// Swap array[j] and array[j+1]
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] numbers = {64, 25, 12, 22, 11};
bubbleSort(numbers);
System.out.println("Sorted array: ");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
9.2 Selection Sort
Selection sort works by dividing the array into two parts: the sorted part and
the unsorted part. The algorithm repeatedly selects the smallest (or largest)
element from the unsorted part and moves it to the sorted part.
Steps:
Start from the first element and find the smallest element in the unsorted
part.
Swap the smallest element with the first element of the unsorted part.
Repeat the process with the next element in the unsorted part.
Time Complexity: O(n^2), where n is the number of elements in the array.
Example:
java
Copy code
public class SelectionSort {
public static void selectionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the first element
int temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
}
public static void main(String[] args) {
int[] numbers = {64, 25, 12, 22, 11};
selectionSort(numbers);
System.out.println("Sorted array: ");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}

You might also like