0% found this document useful (0 votes)
23 views

Chapter 03 - Arrays & Strings Part 1

This document discusses arrays and strings in Java. It provides an overview of arrays, including basic terminology, advantages, features in Java, declaration, creation, initialization, accessing elements, and multidimensional arrays. It also discusses some common operations on arrays like traversing, searching, sorting, and finding minimum and maximum elements with examples of Java programs.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Chapter 03 - Arrays & Strings Part 1

This document discusses arrays and strings in Java. It provides an overview of arrays, including basic terminology, advantages, features in Java, declaration, creation, initialization, accessing elements, and multidimensional arrays. It also discusses some common operations on arrays like traversing, searching, sorting, and finding minimum and maximum elements with examples of Java programs.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Object Oriented Programming

19CSE (2nd Semester)


Chapter#03: Arrays & Strings

1
Part-01
Arrays

2
Outline
 Arrays basic terminology
 Advantages/uses of arrays
 Java array features
 Declaration, Creation, Initialization and accessing array
elements
 Multidimensional arrays
 Some operations on arrays and their JAVA programs
 Traversing
 Searching
 Sorting
 Finding minimum & maximum element

3
What are Arrays ?
 An array is a group of consecutive memory locations with
same name and data type.
 Simple variable is a single memory location with unique name
and a type. But an Array is collection of different adjacent
memory locations. All these memory locations have one
collective name and type.
 The memory locations in the array are known as elements of
array. The total number of elements in the array is called
length.
 The elements of array is accessed with reference to its position
in array, that is call index or subscript.
Basic terminology
 An array is collection of homogenous data elements

 List is composed of elements

 Elements in a list have a common name


 Example: a[3] = 5;
 The common name is ‘a’

 The list as a whole is referenced through the common name

 List elements are of the same type — the base type

 Elements of a list are referenced by subscripting (indexing) the


common name
Advantages / Uses of Arrays
 Arrays can store a large number of value with
single name.
 Arrays are used to process many values easily
and quickly.
 The values stored in an array can be sorted
easily.
 The search process can be applied on arrays
easily.
Java array features
 Subscripts are denoted as expressions within brackets: [ ]
 Base (element) type can be any type
 Size of array can be specified at run time
 This is different that pure C! (for the most part, at least)
 Index type is integer and the index range must be 0 ... n-1
 Where n is the number of elements
 Just like Strings indexing!
 Automatic bounds checking
 Ensures any reference to an array element is valid
 Data field length specifies the number of elements in the list
 Array is an object
 Has features common to all other objects…
 Arrays are:
1) declared
2) created
3) initialized
4) used
array Declaration
 Array declaration involves:
 declaring an array identifier
 declaring the number of dimensions
 declaring the data type of the array elements
Two styles of array declaration:
type array-variable[];
or
type [] array-variable;
Example:
int marks[];
 This will declare an array named ‘marks’ of type ‘int’.
 “marks” is declared, but there is no array actually existing. i.e. no
memory is allocated to the array.
 “marks” is set to NULL, i.e. an array with NO VALUE.
array Creation
 After declaration, no array actually exists.
 In order to create an array, we use the new operator:
type array-variable[];
array-variable = new type[size];
 This creates a new array to hold size elements of type type, which
reference will be kept in the variable array-variable.
 Example:
 marks = new int[5];
 This will allocate memory of 5 integers to the array ‘marks’ and
it can store upto 5 integers in it. ‘new’ is a special operator that
allocates memory.
Combined array Declaration &Creation

data-type variable-name[] = new data-type[size];


Example:
int marks[] = new int[5];
This will declare an int array ‘marks’ and will also allocate
memory of 5 integers to it.
Accessing elements in the array:
 Specific element in the array is accessed by specifying name
of the array followed the index of the element. All array
indexes in Java start at zero.
variable-name[index] = value;
eg. marks[0] = 10;
This will assign the value 10 to the 1st element in the array.
And
marks[2] = 863;
This will assign the value 863 to the 3rd element in the array.
Example

STEP 1 : (Declaration)
int marks[];
marks  null
STEP 2: (Memory Allocation)
marks = new int[5];
marks  0 0 0 0 0
marks[0] marks[1] marks[2] marks[3] marks[4]

STEP 3: (Accessing Elements)


marks[0] = 10;
marks 
10 0 0 0 0
marks[0] marks[1] marks[2] marks[3] marks[4]
Alternative Syntax

Combined declaration & memory allocation:


data-type variable-name[] = new data-type[size];
eg. int marks[] = new int[5];
This will declare an int array ‘marks’ and will also allocate
memory of 5 integers to it.
Combined declaration, allocation & assignment:
data-type variable-name[] = {comma-separated values};
eg. int marks[] = {10, 35, 84, 23, 5};
This will declare an int array ‘marks’, will allocate memory
of 5 integers to it and will also assign the values as-
marks  10 35 84 23 5
marks[0] marks[1] marks[2] marks[3] marks[4]
ARRAY
Giving values into the array created is known as
INITIALIZATION
INITIALIZATION.
The values are delimited by braces and separated by commas
Examples:
int[ ] units = {147, 323, 89, 933, 540, 269, 97, 114, 298,
476};
char[ ] letterGrades = {'A', 'B', 'C', 'D', ’F'};
Note that when an initializer list is used:

the new operator is not used

no size value is specified

The size of the array is determined by the number of items in the


initializer list. An initializer list can only be used only in the array
ACCESSING
ARRAY
A specific element in an array can be accessed
by specifying its index within square brackets.
All array indexes start at ZERO.

Example:- System.out.println(units[4]);

mean = (units[0] + units[1])/2;

0 1 2 3 4 5 6

7 8 9
PROCESSING ARRAY ELEMENTS
Often a for( ) loop is used to process each of the

elements of the array in turn.


The loop control variable, i, is used as the index to access
array
components
EXAMPLE:- int i;
score [0]
for(i=0;i<=2;i++)
{
System.out.println(+score[i]);
} 0 1 2 4 5 6
score 3
50 12 45 78 66 100 125
Multidimensional Arrays
Multidimensional arrays are arrays of arrays:

Each element of an array is to be accessed by multiple dimensions.

Examples: 2D, 3D arrays etc


1) declaration: int array[][];
2) Creation: array=new int[2][3];
3) Combined Declaration and Creation: int array = new int[2][3];
3) initialization
int array[][] = { {1, 2, 3}, {4, 5, 6} };
4) Accessing array elements: array[1][1]=34 or num=array[0][1]
5) Two For loops are used to process each of the elements of the
array in turn.
for(int i=0;i<2;i++)
for(int j=0;j<3;j++)
System.out.println(array[i][j]);
Bounds Checking
Once an array is created, it has a fixed size

An index used in an array reference must specify a


valid element
That is, the index value must be in bounds (0 to N-1)

The Java interpreter throws an


ArrayIndexOutOfBoundsException if an array index
is out of bounds
This is called automatic bounds checking

14
Bounds Checking
For example, if the array score can hold 100 values,
it can be indexed using only the numbers 0 to 99
If i has the value 100, then the following reference
will cause an exception to be thrown:

System.out.println (score[i]);

It’s common to introduce off-by-one errors when using


array problem
s
for (int i=0; i <= 100; i++)
score[i] = i*50;
15
Some operations on Arrays
 Traversing
 Accessing each element of an array is called
Traversing
 Finding minimum and maximum element
 Finding minimum and maximum element in an
array
 Searching
 Finding location of an element in an array is called
searching
 Sorting
 Arranging elements of an array in some logical
order (i.e. Ascending or Descending order)
Some operations on Arrays
 Traversing
 Accessing each element of an array is called
Traversing
 Normally we use FOR loop to enter all elements of
an array and to display all elements of an array
 Example program
 Write a Java program that calculates average of
elements in an array. Ask user to enter number
of elements in array and then calculates and
display average.
//program#01: Average of numbers
import java.util.Scanner;
public class AvgNumbers
{
public static void main(String[] args)
{
int N,numar[],i;
Scanner input=new Scanner(System.in);
System.out.print("Enter the value of N>>");
N=input.nextInt();
numar=new int[N];
System.out.println("Enter elements of array>>");
for(i=0;i<N;i++)
numar[i]=input.nextInt();
int total=0;
double avg;
for(i=0;i<N;i++)
total+=numar[i];
avg=(double)total/N;
System.out.println("The average of "+N+" numbers is "+avg);
}
}
Some operations on Arrays
 Finding minimum and maximum element
 Various Java programs
 Write java program to find the minimum element in an
array of elements.
 Write java program to find the maximum element in
an array of elements.
 Write java program to find the minimum and maximum
element in an array of elements.
 Write java program to find the minimum or maximum
element in an array of elements depend upon choice
entered by the user
//program#02: finding minimum number from array of numbers
import java.util.Scanner;
public class MaxArray
{
public static void main(String[] args)
{
int N,numar[],i;
Scanner input=new Scanner(System.in);
System.out.print("Enter the value of N>>");
N=input.nextInt();
numar=new int[N];
System.out.println("Enter elements of array>>");
for(i=0;i<N;i++)
numar[i]=input.nextInt();
int min=numar[0];
for(i=1;i<N;i++)
{
if(min>numar[i])
min=numar[i];
}
System.out.println("The maximum element in an array is "+min);
}
}
//program#03: finding maximum number from array of numbers
import java.util.Scanner;
public class MaxArray
{
public static void main(String[] args)
{
int N,numar[],i;
Scanner input=new Scanner(System.in);
System.out.print("Enter the value of N>>");
N=input.nextInt();
numar=new int[N];
System.out.println("Enter elements of array>>");
for(i=0;i<N;i++)
numar[i]=input.nextInt();
int max=numar[0];
for(i=1;i<N;i++)
{
if(max<numar[i])
max=numar[i];
}
System.out.println("The maximum element in an array is "+max);
}
}
//program#04: finding minimum & maximum numbers from array of numbers
import java.util.Scanner;
public class MinMax
{
public static void main(String[] args)
{
int N,numar[],i;
Scanner input=new Scanner(System.in);
System.out.print("Enter the value of N>>");
N=input.nextInt();
numar=new int[N];
System.out.println("Enter elements of array>>");
for(i=0;i<N;i++)
numar[i]=input.nextInt();
int min=numar[0];
int max=numar[0];
for(i=1;i<N;i++)
{
if(min>numar[i])
min=numar[i];
if(max<numar[i])
max=numar[i];
}
System.out.println("The minimum element in an array is "+min);
System.out.println("The maximum element in an array is "+max);
}
Some operations on Arrays
Searching
 Two Searching techniques
 Sequential or Linear Search
 Binary Search
 Sequential search is also known as linear or serial search.
It follows the following step to search a value in array.
 Visit the first element of array and compare its value
with required value.
 If the value of array matches with the desired value, the
search is complete.
 If the value of array does not match, move to next
element and repeat same process.
 JAVA program for Linear Search
//program#05: Linear Search program
import java.util.Scanner;
public class LinearSearch
{
public static void main(String[] args)
{
int numlist[]={2,3,65,76,34,23,10,20};
int num;
Scanner input=new Scanner(System.in);
System.out.print("Enter number you want to search>>");
num=input.nextInt();
int loc=-1;
for(int i=0;i<numlist.length;i++)
{
if(num==numlist[i])
{
loc=i;
break;
}
}
if(loc!=-1)
System.out.print("number fournd in the list and its location loc= "+loc);
else
System.out.print("number not found in the list");
}
}
Some operations on Arrays
Searching
Binary search is a quicker method of searching for value in the
array. Binary search is very quick but it can only search on
sorted array. It cannot be applied on an unsorted array.
 It locates the middle element of array and compare with desired
number.
 If they are equal, search is successful and the index of
middle element is returned.
 If they are not equal, it reduces the search to half of the
array.
 If the search number is less than the middle element, it searches
the first half of array.
 Otherwise it searches the second half of the array. The process
continues until the required number is found or loop completes
without successful search
Some operations on Arrays
Searching
Binary search Example. Write Java program for Binary
Search
//program#06: Binary Search program
import java.util.Scanner;
public class BinarySearch
{
public static void main(String[] args)
{
int num, first, last, middle;
int numlist[]={10,20,30,40,50,60,70,80,90,100};
Scanner input = new Scanner(System.in);
System.out.println("Enter number you want to search:");
num = input.nextInt();
first = 0;
int N=numlist.length;
last =N-1;
middle = (first + last)/2;
while( first <= last & num!=numlist[middle] )
{
if ( num<numlist[middle] )
last = middle - 1;
else
first=middle+1;
middle = (first + last)/2;
}
if(num==numlist[middle])
System.out.println("number found in the list and its loccation loc="+middle);
else
System.out.println("number not found in the list ");
}
}
Some operations on Arrays
Sorting
 Sorting is a process of arranging the value of array in a
particular order. An array can be sorted in two order.
 Ascending Order
 Descending Order
12 25 33 37 48

48 37 33 25 12
 Various sorting algorithms/techniques
 Bubble Sort
 Selection Sort
 Insertion Sort
 Quick Sort
 Merge Sort
Some operations on Arrays
Bubble Sorting
 Bubble Sort is also known as exchange sort. It
repeatedly visits the array and compares two items
at a time. It works as follows:
 Compare adjacent element. If the first is greater
than the second, swap them.
 Repeat this for each pair of adjacent element,
starting with the first two and ending with the last
two. (at this point last element should be
greatest).
 Repeat the step for all elements except the last
one.
 Keep repeating for one fewer element each time
until there are no pairs to compare
//program#07: Bubble Sort program
import java.util.Scanner;
public class BubbleSort
{
public static void main(String[] args)
{
int numlist[],N,i,j,temp;
Scanner input = new Scanner(System.in);
System.out.print("Enter number of elements in the list>>");
N=input.nextInt();
numlist= new int[N];
System.out.println("Enter " + N + " integer numbers");
for (i= 0; i <N; i++)
numlist[i] = input.nextInt();
System.out.println("Before sorting the numbers in the list are>>");
for(i=0;i<N;i++)
System.out.print(numlist[i]+" ");
for(i=0;i<N-1;i++)
for(j=0;j<N-1-i;j++)
if(numlist[j]>numlist[j+1])
{
temp=numlist[j];
numlist[j]=numlist[j+1];
numlist[j+1]=temp;
}
System.out.println("\nthe numbers in the list after sorting are");
for(i=0;i<N;i++)
System.out.print(numlist[i]+" ");
}
}
1) Write java program to find the minimum or maximum
element in an array of elements depend upon choice entered
by the user

2) Write java program to add two matrices entered by the


user

3) Write java program to perform subtraction between two


matrices entered by the user

4) Write java program to perform multiplication between


two matrices entered by the user

You might also like