Array Data Structure 4.2.1 Connecting Computational Thinking and Program Design 1
Array Data Structure 4.2.1 Connecting Computational Thinking and Program Design 1
We have learned, Variables, Data types, Arithmetic and logical operators, methods,
A real-world scenario:
"You are building a program to manage the scores of 10 students in a quiz. How
on.
Initialising an array
Array Data Structure:
An array is a linear data structure consisting of a collection of elements, each identified by an index or a key. Arrays
are widely used in computer science and real-life applications due to their simplicity, efficiency, and ability to store
Fixed Size: The size of an array is determined at the time of its creation and cannot be changed.
Indexing: Elements are stored in contiguous memory locations, accessible via indices (0-based or 1-based).
•
Applications of Arraysarrays:
Multi-dimensional in Real Life: containing
Arrays Data Storage ande.g.,
arrays, Organization:
2D arrays (matrices) and 3D arrays.
Benefit: Arrays help organize data in a compact, indexed structure, facilitating quick access and updates.
//Java Program to illustrate how to declare, instantiate, initialize
class Testarray
a [0]=10; //initialization
a [1]=20;
a [2]=70;
a [3]=40;
a [4]=50;
What could go wrong?
num [ 0 ] always OK
num [ 9 ] OK (given the above declaration)
num [ 10 ] illegal (no such cell from this declaration)
num [ -1 ] always NO! (illegal)
num [ 3.5 ] always NO! (illegal)
Array length
• When dealing with arrays, it is advantageous to
know the number of elements contained within the
array, or the array's "length". This length can be
obtained by using the array name followed
by .length. If an array named numbers contains 10
values, the code numbers.length will be 10.
http://mathbits.com/MathBits/Java/arrays/Declare.htm
Program Implementation using Java
Example 1:
System.out.println(cars.length);
Practice :1
Real-Life Example
To demonstrate a practical example of using arrays, let's create a program that calculates the average of
different ages:
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
create a program that finds the lowest age among different ages:
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
// Create a 'lowest age' variable and assign the first array element of ages to it
Nothing!
Output
Correct way: printing a 2D array
Ou
t pu
t
Common 2D array tasks