Arrays& Library Classes - Address Calculation
Arrays& Library Classes - Address Calculation
String &
Library
Functions
2020
Array programs and the use of String and Math Library functions in
programs. By Dulu Dutta
ARRAYS
Q1. What is an Array? What is the need of an array? What are the advantages of using Arrays?
Give the general form of an array.
Answer: An array is a container object that holds a fixed number of values of a single type. The
length of an array is established when the array is created. After creation, its length is fixed.
Answer: When elements are stored in an array, individual elements are selected by an index
which is usually a non-negative scalar integer. Indices are also called subscripts.
Answer:
Bubble Sort: Bubble Sorting is an algorithm in which we are comparing first two values and put
the larger one at higher index. Then we take next two values compare these values and place larger
value at higher index. This process do iteratively until the largest value is not reached at last index.
2|Pag e
Then start again from zero index up to n-1 index. The algorithm follows the same steps iteratively
until elements are not sorted.
Selection Sort: In selection sorting algorithm, find the minimum value in the array then swap it
first position. In next step leave the first value and find the minimum value within remaining
values. Then swap it with the value of minimum index position. Sort the remaining values by using
same steps. Selection sort is probably the most intuitive sorting algorithm to invent.
Insertion sort : - It is a simple sorting method in which the sorted array is built by taking one
entry at a time. It is very efficient on small lists but not as effective on larger ones. It is popular
because of its simplicity.
Example:
Q4: Describe Linear Search and Binary Search technique with an example.
Answer:
3|Pag e
Linear Search: Linear Search refers to the searching technique in which each element of an array
is compared with the search item, one by one, until the search item is found or all elements have
been compared. This method, which traverses the array sequentially to locate the given item, is
called Linear Search or Sequential Search.
public class linsearch
{ int a[ ]={5, 1, 12, -5, 16, 2, 12, 14};
public void linse (int n)
{ int i, flag=0;
for(i=0; i<a.length; i++)
{
if(n==a[i])
{
flag = 1;
break;
}
}
if(flag==1)
System.out.print("Element Present in position"+ (i+1));
else
System.out.print("Element not present.");
}}
Binary Search: A fast way to search a sorted array is to use a binary search. The idea is to look
at the element in the middle. If the key is equal to that, the search is finished. If the key is less
than the middle element, do a binary search on the first half. If it's greater, do a binary search of
the second half.
The advantage of a binary search over a linear search is astounding for large numbers. For an
array of a million elements, binary search, will find the target element with a worst case of only
20 comparisons. Linear search, O(N), on average will take 500,000 comparisons to find the
element. This performance comes at a price - the array must be sorted first.
Example:
4|Pag e
mid= (low+upper)/2;
if(n>a[mid])
low = mid + 1;
else if(n<a[mid])
upper = mid - 1;
else
{
flag = 1;
break;
}}
if(flag ==1)
System.out.println("Element present at position: " + (mid+1));
else
System.out.println("Element not present");
}}
The length property: The length property is used to find the length of an array.
arrayName.length
where, length is a property provided by java for all arrays.
Example:
for( int i=0; i<myArray.length; i++)
{System.out.print(myArray[i]);}
Array Programs:
{ public void sort(int a[]) // function with passing the array as argument
{ int l=a.length, temp;
for (int i=0; i<l;i++)
{ for(int j=0; j<l-i-1;j++)
{
if(a[j]>a[j+1]) // comparing first two values
{ temp= a[j]; // swapping the higher value to higher index
a[j]=a[j+1];
a[j+1]=temp; }}
}
System.out.print("Value after sorting");
for(int i=0;i<l;i++) // printing the array elements
System.out.print(a[i]+ ",");
}}
Q2. Write a program to sort an array using Selection Sort.
5|Pag e
class selection{
int a[ ]={5, 1, 12, -5, 16, 2, 12, 14}; // array declaration and initialization
public void selsort() //function
{ int i, j, small, temp, pos=0;
for(i=0; i<a.length; i++)
{small =a[i]; //assigning first element to variable small
pos = i;
for(j=i+1;j<a.length;j++)
{
if(a[j]< small)
//comparing variable small with other elements of the array
{
small= a[j];
pos =j;
}}
temp= a[i]; //swapping
a[i] = a[pos];
a[pos] = temp;
}
System.out.println("Array in ascending order is:");
for(i=0;i<a.length;i++) // printing the array elements
System.out.print(a[i]+ "\t");
}}
Q3. Write a program to find the maximum value, minimum value and sum of the elements of an
array.
6|Pag e
System.out.println("Maximum Value is:" + max); //output
System.out.println("Minimum Value is:"+ min); //output
System.out.println("Sum is:"+ sum); //output
}}
Q4: Write a program to store name, address and marks in 3 different arrays and display it.
import java.io.*;
public class nameaddoercentage
{ String[] name=new String [5]; // declaring String array
String[] address=new String[5]; // declaring String array
int[] num=new int[5]; // declaring integer array
int sum=0;
BufferedReader a= new BufferedReader(new InputStreamReader(System.in));
public void display()throws IOException
{
for(int i=0;i<5;i++)
{
System.out.println("Enter Name:"); //console base input
name[i]= a.readLine();
System.out.println("Enter address:");
address[i]= a.readLine();
System.out.println("Enter Amount:");
num[i]=Integer.parseInt(a.readLine());
}
for(int i=0;i<5;i++)
{
System.out.println("Name is:"+ name[i]); //output
System.out.println("Address is:"+address[i]);
System.out.println("Number is:"+num[i]);
}}}
Q5: The marks obtained by 5 students in a subject are tabulated as follows:-
Name Marks
-- --
-- --
-- --
Write a program to input the names and marks of the students in the subject.
Calculate and display
i) The subject average marks (Subjects average marks = subject total / 5)
ii) The highest marks in the subject
(The maximum marks in the subject are 100)
import java.io.*;
7|Pag e
public class subaverage
{ String[] name=new String [5]; // declaring String array
double[] marks=new double[5]; // declaring integer array
double sum=0, average=0; //variable declaration
double max;
BufferedReader a= new BufferedReader(new InputStreamReader(System.in));
public void display()throws IOException
{
for(int i=0;i<5;i++) //console base input
{
System.out.println("Enter Name:");
name[i]= a.readLine();
System.out.println("Enter Marks");
marks[i]=Double.parseDouble(a.readLine());
sum+=marks[i]; //sum of the elements of marks[] array
}
max=marks[0];
for(int i=0;i<5;i++)
{
if(max<marks[i]) // finding the maximum value
max=marks[i];
}
System.out.println("Highest marks is:"+max); //output
System.out.println("The subject average marks:"+sum/5); //output
}}
Q6: Write a program to print the names and percentage in tabular form.
class arraynamenum {
public static void main()
{
String[] name={"Harry", "Supandi", "Ramesh","Kabya","Ishaan"};
// declares an array of Strings
int[] percentage={10,12,45,20,21}; // declares an array of integers
for(int i=0;i<name.length;i++)
{
System.out.println(name[i]+"--------"+percentage[i]); //output
}
} }
Q7: Write a program to bubble sort the following set of values in ascending order
9, 34, 20, 4, 98, 2, 76, 6, 90, 8
Output: 2
8|Pag e
4
6
8
9
20
34
76
90
98
{
int a[] = {9, 34, 20, 4, 98, 2, 76, 6, 90, 8 };
public void sort() // function with passing the array as argument
{ int l=a.length, temp;
for (int i=0; i<l;i++)
{ for(int j=0; j<l-i-1;j++)
{
if(a[j]>a[j+1]) // comparing first two values
{ temp= a[j]; // swapping the higher value to higher index
a[j]=a[j+1];
a[j+1]=temp; }}
}
System.out.print("Value after sorting");
for(int i=0;i<l;i++) // printing the array elements
System.out.println(a[i]);
}}
Q8: Write a program to store 6 elements in an array P and 4 elements in an array Q and produce
a third array R, containing all the elements of P and Q. Display the resultant array.
Example:
INPUT INPUT OUTPUT
P [] Q[] R[]
4 19 4
6 23 6
1 7 1
2 8 2
3 3
10 10
19
23
7
8
9|Pag e
import java.io.*;
public class arraymerge
{
int[] P=new int [6]; // Array declaration
int[] Q=new int [4];
int[] R=new int [10];
BufferedReader a= new BufferedReader(new InputStreamReader(System.in));
public void merge()throws IOException
{ int i, j;
for(i=0;i<6;i++)
{
System.out.println("Enter element:"+ (i+1)+ "of array P:");
P[i]= Integer.parseInt(a.readLine()); //Input for array P
}
for(j=0;j<4;j++)
{
System.out.println("Enter element:"+ (j+1)+ "of array Q:");
Q[j]= Integer.parseInt(a.readLine()); //Input for array Q
}
for(i=0;i<6;i++)
{
R[i]=P[i]; //Copying array P[] to R[]
}
for(j=0;j<4;j++)
{
R[j+6]=Q[j]; ////Copying array Q[] to R[]
}
System.out.println("Elements of the merged array are:");
for(i=0;i<10;i++)
System.out.println(R[i]); // Output
}}
11 | P a g e
= 1000 + (1350 – 1200) * 2
= 1000 + 150*2
= 1000 + 300
= 1300
2. A two-dimensional array T is created in the row-major format with 10 rows and 12 columns.
Each element occupies 4 bytes of storage space. The base address of the array is 2000. Find the
address of element T[5][6].
Solution: B = 2000, Lr = 0, Lc = 0, W = 4, C = 12, X = 5, Y = 6
Address of A[X][Y] = B + [(X – Lr) * C + (Y – Lc)] * W
= 2000 + [(5 – 0) * 12 + (6 – 0)] * 4
= 2000 + (5*12 + 6)*4
= 2000 + 66 * 4
= 2000 + 264
= 2264
3. A two-dimensional array T is created in the column-major format with 10 rows and 12
columns. Each element occupies 4 bytes of storage space. The base address of the array is 2000.
Find the address of element T[5][6].
Solution: B = 2000, Lr = 0, Lc = 0, W = 4, R= 10, X = 5, Y = 6
Address of A[X][Y] = B + [(Y – Lc) * R + (X – Lr)] * W
= 2000 + [(6 – 0) * 10 + (5 – 0)] * 4
= 2000 + (6*10 + 5)*4
= 2000 + 65 *4
= 2000 + 260
= 2260
4. An array X[-10…..10, -12…..10] requires two bytes for each element. The base address of the
array is 1200. Find out the location of X[6][4] if the array is arranged in the row-major format.
Solution: Number of rows (R) = (Ur – Lr) + 1 = 10 - (-10) + 1 = 21
Number of columns (C) = (Uc – Lc) +1 = 10 – (-12) + 1 = 23
B = 1200, Lr = -10, Lc = -12, W = 2, C = 23, X = 6, Y = 4
12 | P a g e
Address of A[X][Y] = B + [(X – Lr) * C + (Y – Lc)] * W
= 1200 + [(6-(-10) * 23 + (4-(-12)] * 2
= 1200 + (16*23 + 16) * 2
= 1200 + (368 + 16) * 2
= 1200 + 384 * 2
= 1200 + 768
= 1968
Library Classes
STRING Library Function
Return
Type
Method Description
boolean equals(String anotherString) When the calling string and the within
argument are same, then the function
returns true else returns false
13 | P a g e
character starting from the index
number specified as second parameter.
14 | P a g e
Boolean endsWith(String str) Checks for starting from the end of the
string
Sample Program 1
15 | P a g e
my name is rajufrom Balipara
The length of the String a assigned to variable x:
16
Printing the character array after converting:
My name is raju
Sample Program 2
17 | P a g e
public class stringexamplelib3
{ String a="Hello";//Declaring String
String b= "Hello World";// Declaring String
String c="hello";
int x=18;
void main()
{ System.out.println("compareTo(String anotherString) is comparing String a with String b");
System.out.println(a.compareTo(b));
System.out.println("Function equals(String anotherString)returns true when the calling string
and the String within argument are same, else returns false:");
System.out.println(a.equals(c));
System.out.println("Function equalsIgnoreCase(String anotherString) Compares this String to
another String, ignoring case considerations.:");
System.out.println(a.equalsIgnoreCase(c));
System.out.println("Function endsWith(String str) Checks for starting from the end of the string
:");
System.out.println(b.endsWith(a));
System.out.println("Function startsWith(String str), checks the given string that begins with a
specified string returns either true or false.:");
System.out.println(b.startsWith(a));
System.out.println("Function valueOf(int x), returns the string representation of the int
argument.:");
System.out.println(String.valueOf(x));
} }
Output:
compareTo(String anotherString) is comparing String a with String b
-6
Function equals(String anotherString)returns true when the calling string and the String within argument
are same, else returns false:
false
Function equalsIgnoreCase(String anotherString) Compares this String to another String, ignoring case
considerations.:
true
Function endsWith(String str) Checks for starting from the end of the string :
false
Function startsWith(String str), checks the given string that begins with a specified string returns either
true or false.:
true
Function valueOf(int x), returns the string representation of the int argument.:
18
NOTE: In the sample programs the use of String library functions in a program are demonstrated and the
output is given.
18 | P a g e
Math Library Function
Math Constants
Two common constants are defined in the Math class.
double Math.E() Value of e, 2.718282..., base of the natural logarithms.
double Math.PI() Value of pi, 3.14159265 ....
Math Methods
Trigonometric Methods
Exponential Methods
The two basic functions for logarithms and power are available. These both use the base e
(Math.E) as is the usual case in mathematics.
Misc Methods
double Math.sqrt(d) Returns the square root of d.
t Math.abs(x) Returns absolute value of x with same type as the parameter: int,
long, float, or double.
t Math.max(x, y) Returns maximum of x and y with same type as the parameter:
int, long, float, or double.
t Math.min(x, y) Returns minimum of x and y with same type as the parameter: int,
long, float, or double.
Integer Related Methods
The following methods translate floating point values to integer values, altho these values may
still be stored in a double.
double Math.floor(d) Returns the closest integer-valued double which is equal to or less
than d.
double Math.ceil(d) Returns the closest integer-valued double which is equal to or
greater than d.
double Math.rint(d) Returns the closest integer-valued double to d.
19 | P a g e
Random Numbers
double Math.random() Returns a number x in the range, 0.0 <= x < 1.0.
int i = 7;
int j = -9;
double x = 72.3;
double y = 0.34;
// Comparison operators
20 | P a g e
System.out.println("min(" + i + "," + x + ") is " + Math.min(i,x));
System.out.println("min(" + y + "," + j + ") is " + Math.min(y,j));
// Trigonometric methods
// All arguments are given in radians
Note: In the example above the different data types are used in the Math Library Function and
their output is discussed. You can copy and paste the program and you can check the output. If
21 | P a g e
you study this program and output carefully, any question or output of program segments
(normally given in section A of the question paper) related to Math class can be answered.
22 | P a g e