0% found this document useful (0 votes)
3 views64 pages

Chapter 7 - Array - Revision - Java

The document provides a comprehensive overview of Java arrays, including definitions, types, declaration, initialization, accessing elements, and common operations such as traversing and searching. It also covers two-dimensional arrays, sorting algorithms like bubble sort and selection sort, and practical examples for inputting and processing array data. Key concepts such as indexing, array bounds, and error handling are highlighted throughout.

Uploaded by

dnynadaacademy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views64 pages

Chapter 7 - Array - Revision - Java

The document provides a comprehensive overview of Java arrays, including definitions, types, declaration, initialization, accessing elements, and common operations such as traversing and searching. It also covers two-dimensional arrays, sorting algorithms like bubble sort and selection sort, and practical examples for inputting and processing array data. Key concepts such as indexing, array bounds, and error handling are highlighted throughout.

Uploaded by

dnynadaacademy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Arrays

1. What is an Array?
• An array is a collection of similar data types stored in
contiguous memory locations.
• It allows storing multiple values under a single variable
name.
2. Why Use Arrays? 3. Types of Arrays in Java
• Efficient way to handle large amounts of data.
• Reduces the need for multiple variables.
• Enables loop-based processing of data.
• Any value can be accessed using index number

4. Declaring and Initializing Arrays


Declaration:
int[] arr; // Declares an array
Int arr[];
Initialization:
int[] arr = new int[5]; // Allocates memory for 5 integers
With Values:
int[] arr = {10, 20, 30, 40, 50};
5. Accessing Array Elements
• Use indexing (starts from 0): 7. Common Array Programs
[Link](arr[2]); // Outputs 30
• Modify an element:
arr[1] = 25; // Changes second element to 25
6. Traversing Arrays with Loops
Using for loop:
for(int i = 0; i < [Link]; i++) {
[Link](arr[i]); }
Using for-each loop:
for(int num : arr) { [Link](num); }
8. Key Points to Remember
• Arrays are fixed-size once declared.
• Accessing an index outside bounds causes
ArrayIndexOutOfBoundsException.
• Use .length to get array size.
A[0,0] A[0,1] A[0,2]
A[1,0] A[1,1] A[1,2]
A[2,0] A[2,1] A[2,2]
9. Sample MCQ Practice
[Link] is the index of the first element in an array?
1.0
2.1
3.-1
[Link] on array size
[Link] loop is best for traversing arrays?
[Link]
[Link]-while
[Link]
[Link]
Accepting Data in an Array Objective
To input values into an array using a loop and store them for further
processing.
1. Import Scanner Class
import [Link];
2. Declare and Create the Array
int[] arr = new int[5]; // Array to store 5 integers
3. Create Scanner Object
Scanner sc = new Scanner([Link]);
4. Accept Data Using a Loop
[Link]("Enter 5 numbers:");
for(int i = 0; i < [Link]; i++)
{ arr[i] = [Link]();}
5. Display the Array (Optional)
[Link]("You entered:"); for(int i = 0; i < [Link]; i++) {
[Link](arr[i]); }
Accessing Data in an Array
What Does It Mean?
Accessing data means retrieving or using the values stored in specific positions
(called indices) of an array.
Key Concept: Indexing
• Array indices start from 0.
• So, for an array of size 5:
arr[0], arr[1], arr[2], arr[3], arr[4]

Example: Accessing Elements


int[] arr = {10, 20, 30, 40, 50}; [Link](arr[0]); // Outputs 10
[Link](arr[3]); // Outputs 40
Accessing All Elements Using a Loop
for(int i = 0; i < [Link]; i++)
{ [Link]("Element at index " + i + " = " + arr[i]); }
Common Mistake

Trying to access an index outside the array bounds:

[Link](arr[5]); // Error: ArrayIndexOutOfBoundsException

Quick Quiz

[Link] is the index of the last element in an array of size 7?

2. Which loop is commonly used to access array elements?


Exercise

1) Accept 10 integers in an array

2) Display the values

3) Find an average
Question 2(viii)
Consider the given array and answer the questions given below:
int x[ ] = {4, 7, 9, 66, 72, 0, 16};
(a) What is the length of the array?
(b) What is the value in x[4]?
Linear search(Sequential Search) used to find a specific value in an array
by checking each element one by one from start to end.
It's like flipping through pages of a book until you find the one you're looking
for—no shortcuts, just a direct scan.
How It Works
• Start at index 0.
• Compare each element with the target value.
• If a match is found, return the index.
• If no match is found by the end, return -1.
When to Use
• Arrays are small or unsorted.
• Simplicity is more important than speed.
• You don’t want to sort or use extra memory.
class Linearseacrh
{
public static void main(String[] args)
{
int[] a = { 3, 4, 1, 7, 5 };
int n = [Link];
int x = 4;
boolean found = false;
for (int i = 0; i < n; i++)
{
if (a[i] == x)
{
[Link]("Element found at index: " +i);
found = true;
break;

}
}
if (found == false)
[Link]("Element is not present in the array");

}
}
What Is a 2D Array?
A 2D array is essentially an array of arrays—like a matrix or grid.
to store data in rows and columns.

Declaration & Initialization


int[][] arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

You can also declare it first and assign values later


int[][] arr = new int[3][3]; // 3 rows, 3 columnsarr[0][0] = 1;
arr[0][1] = 2;
// and so on...

Traversing a 2D Array (Nested Loops


for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < arr[i].length; j++) {
[Link](arr[i][j] + " ");
}
Order of an array is same as dimensions of the
[Link]();
array
}
for (int m = 0; m<4;m++)
import [Link];
{
public class arrayex1_rowsum
for (int n = 0; n<4;n++)
{
[Link](arr[m][n]+" ");
public static void main(String[] args)
[Link]();
{
}
//int arr[][] =
{{1,2,3,4},{5,6,7,8},{9,10,11,12},{21,20,20,30}};
for (int i=0; i<[Link];i++)
{
int arr[][] = new int[4][4];
//Sum of rows
Scanner sc = new Scanner([Link]);
int sum_row=0;
for (int j=0;j<arr[i].length;j++)
for (int k = 0; k<4;k++)
{
{
sum_row = sum_row +arr[i][j];
for (int l = 0; l<4;l++)
}
arr[k][l] = [Link]();
[Link]("Row number"+ i +"Sum
:"+sum_row);
}
[Link]("row"+ [Link]);
[Link]("column"+ arr[0].length);
}
}
}
Question 6
Define a class to accept values into an integer array of order 4 x 4 and check whether
it is a DIAGONAL array or not. An array is DIAGONAL if the sum of the left diagonal
elements equals the sum of the right diagonal elements. Print the appropriate
message.
Example:
3425
2523
5327
1371
Sum of the left diagonal element = 3 + 5 + 2 + 1 = 11
Sum of the right diagonal element = 5 + 2 + 3 + 1 = 11
for (int k = 0; k<4;k++)
{
lsum= lsum+arr[k][k];
rsum = rsum+arr[k][3-k];
}
Int lSum = 0;
public class DiagonalDDA int rSum = 0;
{
public static void main(String args[]) { for (int i = 0; i < 4; i++) {
Scanner in = new Scanner([Link]); lSum += arr[i][i];
int[][] arr = new int[4][4]; rSum += arr[i][3 - i];
}
[Link]("Enter elements for 4x4
DDA:");
if (lSum == rSum) {
for (int i = 0; i < 4; i++) {
[Link]("The array is a DIAGONAL array.");
for (int j = 0; j < 4; j++) {
} else {
arr[i][j] = [Link]();
[Link]("The array is NOT a DIAGONAL
} array.");
} }
}
}
Question 9

Write a program in Java to store 20 numbers (even and odd numbers) in a Single
Dimensional Array (SDA). Calculate and display the sum of all even numbers and all odd
numbers separately.
import [Link];

for (int i = 0; i < l; i++)


public class KboatDigitSum
{
{

public static void main(String args[])


if(arr[i] >= 0 && arr[i] < 10 )
{ oneSum += arr[i];
Scanner in = new Scanner([Link]);
else if(arr[i] >= 10 && arr[i] < 100 )
int oneSum = 0, twoSum = 0, d = 0;

int arr[] = new int[10];


twoSum += arr[i];
[Link]("Enter 10 numbers"); }
int l = [Link];

for (int i = 0; i < l; i++)


[Link]("Sum of 1 digit
{
numbers = "+ oneSum);
arr[i] = [Link](); [Link]("Sum of 2 digit
} numbers = "+ twoSum);

}
import [Link];

public class KboatSDAOddEvenSum


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

Scanner in = new Scanner([Link]);


int arr[] = new int[20];

[Link]("Enter 20 numbers");
for (int i = 0; i < [Link]; i++) {
arr[i] = [Link]();
}

int oddSum = 0, evenSum = 0;

for (int i = 0; i < [Link]; i++) {


if (arr[i] % 2 == 0)
evenSum += arr[i];
else
oddSum += arr[i];
}
[Link]("Sum of Odd numbers = " + oddSum);
[Link]("Sum of Even numbers = " + evenSum);
}
}
import [Link];
public class linearearch_ex1
for (int i=0;i<20;i++)
{ {
public static void main(String[] args)
if (arr[i]==value)
{ {
Scanner sc = new Scanner([Link]);
double[] arr = new double[20];
[Link]("Value is found at
boolean found = false; location: "+i);
for (int i=0;i<20;i++)
found = true;
{ break;
arr[i]= [Link]();
}
}
//Enter the value to be searched }
[Link]("Enter the value to be searched");
double value = [Link]();
if (found == false)
}
[Link]("value not found");
}
// Binary search method
import [Link]; int start = 0;
int end = [Link] - 1;
int mid = 0;
public class BinarySearchDemo
{ while (start <= end)
{
public static void main(String[] args) mid = (start + end) / 2;
{
boolean found = false; if (arr[mid] == key)
Scanner sc = new Scanner([Link]); {
found = true;
break;
double[] arr = }
{5.6,11.5,20.8,35.4,43.1,52.4,66.6,78.9,80.0,95.5 else if ( key< arr[mid])
{
}; end = mid - 1; // Search left half
}
// Input key to search else
[Link]("Enter element to search: {
start = mid + 1; // Search right half
");
double key = [Link](); }
}
// Output result
if (found == false)
} {
} [Link]("Element not found.");
} else
{
[Link]("Element found at index: " + mid);
}
Question 1
Write a program to initialise the given data in an array and find the minimum and
maximum values along with the sum of the given elements.
Numbers: 2, 5, 4, 1, 3
Output:
Minimum value: 1
Maximum value: 5
Sum of the elements: 15
public class MinMaxSum
{
public static void main(String args[]) {
int arr[] = {2, 5, 4, 1, 3};
int max = arr[0]; [Link]("Minimum value: " +
min);
int min = arr[0];
[Link]("Maximum value: " +
int sum = 0;
max);
for (int i = 0; i < [Link]; i++) {
[Link]("Sum of the elements: " +
if (arr[i] > max) sum);
max = arr[i]; }
}
if (arr[i] < min)
min = arr[i];

sum += arr[i];
}
Question 18
Write a program that reads ten integers and displays
them in the reverse order in which they were read.
import [Link];
public class KboatSDAReverse
{
public static void main(String args[]) {

Scanner in = new Scanner([Link]);


int arr[] = new int[10];

[Link]("Enter 10 integers:");
for (int i = 0; i < 10; i++) {
arr[i] = [Link]();
}

[Link]("Integers in reverse order:");


for (int i = 9; i >= 0; i--) {
[Link](arr[i] + " ");
}
}
}
Day 3 - Sorting
Bubble sort public class BubbleSort
{
public static void main(String args[]) {
int arr[] = {67,76,55,89,78};
int n = [Link];

//Bubble Sort
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int t = arr[j];
arr[j] = arr[j+1];
arr[j+1] = t;
}
}
}

[Link]("Sorted Array:");
for (int i = 0; i < n; i++) {
[Link](arr[i] + " ");
}
}
}
Selection Sort

What Is Selection Sort?


Selection Sort is a simple comparison-based
sorting algorithm. It works by repeatedly finding
the minimum element from the unsorted part and
placing it at the beginning

How It Works (Step-by-Step)

[Link] from the first element.

[Link] the smallest element in the unsorted part.

[Link] it with the first unsorted element.

[Link] the boundary of the sorted part one step forward.

[Link] until the entire array is sorted.


public class SelectionSort
{
public static void main(String args[]) {
int arr[] = {9, 5, 2, 3};
int n = [Link];

//outer loop tells which position array list[] to fill next


for (int i = 0; i < n - 1; i++)
{
//find the minimum element in an unsorted array
int minIdx = i;
for (int j = i + 1; j < n; j++)
{
if (arr[j] < arr[minIdx])
minIdx = j;
}

int t = arr[i];
arr[i] = arr[minIdx];
arr[minIdx] = t;
}
[Link]("Sorted Array:");
for (int i = 0; i < n; i++) {
[Link](arr[i] + " ");
}
}
}
Question 6
Define a class to initialise the following data in an array. Search for a given
character input by the user, using the Binary Search technique. Print "Search
Successful" if the character is found otherwise print "Search is not Successful".
[Link]: Returns 3 because there are 3 rows.

x[0].length: Refers to the length of the first row


(x[0]), which has 50 elements (columns).

You might also like