KnowledgeBoat Logo
OPEN IN APP

Chapter 7

Arrays

Class 10 - Sumita Arora ICSE Computer Applications with BlueJ



Objective Type Questions

Question 1

In Java, for an array having N elements, legal subscripts are :

  1. 0 to N
  2. 0 to N-1
  3. 1 to N
  4. 1 to N - 1

Answer

0 to N-1

Reason — In Java, for an array having N elements, the subscripts start from 0 and go on till N - 1 (size - 1).

Question 2

Total size of array A having 25 elements of char type is ............... .

  1. 25 bytes
  2. 50 bytes
  3. 100 bytes
  4. None of these

Answer

50 bytes

Reason — The size of char data type is 2 bytes. Since A is an array of char type, the size of each element of the array will be 2 bytes. The size of 25 elements will be 25 X 2 = 50 bytes.

Question 3

Total size of array B[10][5] of int type is ............... .

  1. 50 bytes
  2. 15 bytes
  3. 100 bytes
  4. 200 bytes

Answer

200 bytes

Reason — The size of int data type is 4 bytes. Since B is an array of int type, the size of each element of the array will be 4 bytes. The array has 10 rows and 5 columns, thus total number of elements will be 10 X 5 = 50. The size of 50 elements will be 50 X 4 = 200 bytes.

Question 4

Total number of elements in array C[5][3][2] are ............... .

  1. 10
  2. 20
  3. 30
  4. 50

Answer

30

Reason — The total number of elements in array C will be 5 x 3 x 2 = 30.

Question 5

Which of the following statements are valid array declaration ?

  1. int number( );
  2. float average[ ];
  3. double[ ] marks;
  4. counter int[ ];

Answer

float average[ ];
double[ ] marks;

Reason — The statements float average[ ]; and double[ ] marks; are valid as they follow the syntax for declaration of an array.

int number( ); uses small brackets () instead of square brackets []. The correct statement will be int number[];.

counter int[ ]; has exchanged the place of data type and array variable. The correct statement will be int counter[];

Question 6

Consider the following code

int number[ ] = new int[5];

After execution of this statement, which of the following are True ?

  1. number[0] is undefined
  2. number[5] is undefined
  3. number[2] is 0
  4. number.length is 5

Answer

number[5] is undefined

Reason — The valid subscripts of an array of size N are from 0 to N - 1. Thus, subscripts of array number will be from 0 to 4 (5 - 1).

Question 7

Which of the following contain error ?

  1. int x[ ] = int[10];
  2. int[ ] y = new int[5];
  3. float d[ ] = {1, 2, 3};
  4. x = y = new int[10];
  5. int a[ ] = {1, 2}; int b[ ]; b = a;
  6. int i = new int(10);

Answer

int x[ ] = int[10];
x = y = new int[10];
int i = new int(10);

Reasonint x[] = int[10]; doesn't contain the 'new' keyword used to initialize an array. The correct statement will be int x[] = new int[10];

In the statement x = y = new int[10];, 'x' and 'y' are not declared as array variables. The correct statement will be :

int x[] = new int[10]; 
int y[] = new int[10];

In the statement int i = new int(10);, 'i' is not declared as array variable and small brackets () are used instead of square brackets []. The correct statement will be int i[] = new int[10];

The remaining statements follow the syntax used for declaring and initializing an array, thus they do not have any error.

Question 8

Given that int A[ ] = {35, 26, 19, 76, 58};
What will be value contained in A[3] ?

  1. 35
  2. 26
  3. 19
  4. 76
  5. 58

Answer

76

Reason — The valid subscripts of an array are from 0 to size - 1. Thus, A[0] = 35, A[1] = 26, A[2] = 19, A[3] = 76 and A[4] = 58.

Question 9

Given that int z[ ][ ] = {{2, 6, 5}, {8, 3, 9}}; What will be value of z[1][0] and z[0][2] ?

  1. 2 and 9
  2. 8 and 5
  3. 2 and 5
  4. 6 and 3

Answer

8 and 5

Reason — Two-dimensional arrays are stored in a row-column matrix, where the first index indicates the row and the second indicates the column.

The element stored at z[1][0] refers to the element stored in second row and first column, which is 8.

The element stored at z[0][2] refers to the element stored in first row and third column, which is 5.

Question 10

Given array 12, 3, 8, 5. What will be array like after two passes of selection sort ?

  1. 12, 3, 8, 5
  2. 3, 5, 8, 12
  3. 3, 8, 5, 12
  4. 3, 5, 12, 8

Answer

3, 5, 8, 12

Reason — Selection Sort is a sorting technique where next smallest (or next largest) element is found in the array and moved to its correct position in each pass.

In the first pass, smallest element 3 will be found and swapped with the first position element 12. The array elements after the first pass will be:

3, 12, 8, 5

In the second pass, the next smallest element 5 will be found and swapped with the second position element 12.The array elements after the second pass will be:

3, 5, 8, 12

Question 11

Given an array 12, 3, 8, 5. What will be array like after two passes of bubble sort?

  1. 12, 3, 8, 5
  2. 3, 8, 12, 5
  3. 3, 5, 8, 12
  4. 12, 3, 5, 8

Answer

3, 8, 12, 5

Reason — The basic idea of bubble sort is to move the largest element to the highest index position in the array. To attain this, two adjacent elements are compared repeatedly and exchanged if they are not in correct order.

In the first pass, adjacent elements (12,3) will be compared and swapped. The array will look like this after the first pass:

3, 12, 8, 5

In the second pass, adjacent elements (12,8) will be compared and swapped. The array will look like this after the second pass:

3, 8, 12, 5

Question 12

An array
18, 13, 2, 9, 5
is
13, 2, 9, 18, 5
after three passes. Which sorting technique is applied on it?

Answer

Bubble sort is applied on the array.

Explanation

In the first pass, adjacent elements (18, 13) will be compared and swapped. The array will look like this after the first pass:

13, 18, 2, 9, 5

In the second pass, adjacent elements (18, 2) will be compared and swapped. The array will look like this after the first pass:

13, 2, 18, 9, 5

In the third pass, adjacent elements (18, 9) will be compared and swapped. The array will look like this after the third pass:

13, 2, 9, 18, 5

Assignment Questions

Question 1

What do you understand by an array ? What is the significance of arrays ?

Answer

An array is a collection of variables of the same type that are referenced by a common name. It is a reference data type which stores data values in contiguous memory locations. An array is declared and initialized as follows:

int arr[] = new int[10];

The significance of arrays are as follows:

  1. Easy to specify — The declaration, allocation of memory space, initialization can all be done in one line of code.
  2. Free from run-time overheads — There is no run-time overhead to allocate/free memory, apart from once at the start and end.
  3. Random access of elements — Arrays facilitate random (direct) access to any element via its index or subscript.
  4. Fast Sequential Access — It is usually faster to sequentially access elements due to contiguous storage and constant time computation of the address of a component.
  5. Simple code — As arrays facilitate access of multiple data items of same type through a common name, the code becomes much simpler and easy to understand.

Question 2

What is meant by index of an element ? How are indices numbered in JAVA ?

Answer

Each element in an array is referred to by their subscript or index. The index of an element refers to the position of an element in the array. In Java, the indices start from 0 and go on till size - 1.

For example,

int arr[] = {3, 6, 8};

In the array arr[], arr[0] = 3, arr[1] = 6 and arr[2] = 8.

Question 3

Determine the total bytes required to store B[17], a char array.

Answer

A char data type requires 2 bytes in memory. So, the memory required to store 17 char elements will be 17 X 2 = 34 bytes.

Question 4

What is the data type of elements of an array called ?

Answer

The data type of elements of an array is called base type of an array.

Question 5

Arrays do not prove to be useful where quite many elements of the same data types need to be stored and processed. (T/F)

Answer

False

Reason — Arrays store same type of data elements in contiguous memory locations and under a single variable name. This makes them very useful where quite many elements of the same data types need to be stored and processed as the user can refer to the elements using the same name and different index numbers.

Question 6

A subscript of an element designates its position in the array's ordering. (T/F)

Answer

True

Reason — The index of an element determines its position in an array.

Question 7

How is one-dimensional array represented in memory ?

Answer

Single-dimensional arrays are lists of information of the same type and their elements are stored in contiguous memory locations in their index order.

For example, an array grade of type char with 8 elements declared as

char grade[ ] = new char[8];

will have the element grade[0] at the first allocated memory location, grade[1] at the next contiguous memory location, grade[2] at the next, and so forth. Since grade is a char type array, each element size is 2 bytes and it will be represented in memory as shown in the figure given below:

How is one-dimensional array represented in memory? Arrays, Sumita Arora Computer Applications Solutions ICSE Class 10

Question 8

Determine the number of bytes required to store an int array namely A[23].

Answer

An int data type requires 4 bytes in memory. Therefore, the storage space required by array A[ ] will be 23 x 4 = 92 bytes.

Question 9

An array element is accessed using ............... .

  1. a first-in-first-out approach
  2. the dot operator
  3. an element name
  4. an index number

Answer

an index number

Reason — An array element is accessed using the array name along with an index number, which corresponds to the position of the element in an array.

Question 10

All the elements in an array must be of ............... data type.

Answer

All the elements in an array must be of same data type.

Question 11

Write a statement that defines a one-dimensional array called amount of type double that holds two elements.

Answer

double amount[] = new double[2];

Question 12

The elements of a seventy-element array are numbered from ............... to ............... .

Answer

The elements of a seventy-element array are numbered from 0 to 69.

Question 13

Element amount[9] is which element of the array ?

  1. the eighth
  2. the ninth
  3. the tenth
  4. impossible to tell.

Answer

the tenth

Reason — In Java arrays, element at position 1 has index/subscript 0, element at position 2 has index 1, element at position 3 has index 2 and so on. Thus, position of an element is [index + 1]. Hence, amount[9] (9 + 1 = 10) will be the tenth element of the array.

Question 14(i)

Declare following arrays: figures of 30 char element.

Answer

char figures[] = new char[30];

Question 14(ii)

Declare following arrays: check of 100 short element.

Answer

short check[] = new short[100];

Question 14(iii)

Declare following arrays: balance of 26 float element.

Answer

float balance[] = new float[26];

Question 14(iv)

Declare following arrays: budget of 58 double element.

Answer

double budget[] = new double[58];

Question 15

Declare an array of 5 ints and initialize it to the first five even numbers.

Answer

int even[] = {2, 4, 6, 8, 10};

Question 16

Write a statement that displays the value of the second element in the long array balance.

Answer

System.out.println(balance[1]);

Question 17

For a multidimensional short array X[5][24], find the number of bytes required.

Answer

The formula to calculate total number of bytes required by a two-dimensional array is as follows:

total bytes = number-of-rows x number-of-columns x size-of-base-type
                  = 5 x 24 x 2 (since short requires 2 bytes in memory)
                  = 240 bytes

Question 18

For a multidimensional array B[9][15] find the total number of elements in B.

Answer

The total number of elements in array B is as follows:

Total elements = number of rows x number of columns
                        = 9 x 15
                        = 135

Question 19

How are the 2-D arrays stored in the memory?

Answer

Two-dimensional arrays are stored in a row-column matrix, where the first index indicates the row and the second indicates the column.

For example, if we declare an array pay as follows:

short[][] pay = new short[5][7];

it will be having 5 x 7 = 35 elements which will be represented in memory as shown below:

How are the 2-D arrays stored in the memory? Arrays, Sumita Arora Computer Applications Solutions ICSE Class 10

Question 20

What are the preconditions for Binary Search to be performed on a single dimensional array ?

Answer

The preconditions for Binary Search to be performed on a single dimensional array are:

  1. The array should be sorted, either in ascending order or descending order.
  2. Lower bound, upper bound and the sort order of the array must be known.

Question 21(i)

A binary search of an ordered set of elements in an array is always faster than a sequential search of the elements. True or False ?

Answer

False

Reason — In a case where the search item is at the first place in a sorted array, sequential search becomes faster than binary search as the first comparison yields the desired value. In case of binary search, the search value is found after some passes are finished.

For example, let us consider an array arr[] = {2, 5, 8, 12} and the search value = 2. In this case, sequential search will find the search value in the first comparison while binary search will first compare the search value with the mid value i.e. 5 and continue its passes.

Question 21(ii)

A binary search of elements in an array requires that the elements be sorted from smallest to largest. True or False ?

Answer

False

Reason — A binary search requires a sorted array. It may be in ascending order or descending order.

Question 21(iii)

The performance of linear search remains unaffected if an unordered array is sorted in ascending order. True or False ?

Answer

True

Reason — Linear search is not affected if an unordered array is sorted in ascending order.

Question 21(iv)

For inserting of an element in a sorted array, the elements are always shifted to make room for the new entrant. True or False ?

Answer

True

Reason — For inserting of an element in a sorted array, the elements are always shifted to make room for the new entrant, the only exception being when the element is inserted at the end of the array.

Question 22

Name some commonly used sorting techniques.

Answer

Some commonly used sorting techniques are:

  1. Selection sort
  2. Bubble sort
  3. Shell sort
  4. Shuttle sort
  5. Quick sort
  6. Heap sort

Question 23

Show the contents of the array after the second iteration of Selection Sort.

1207122433114195163735869\underset{0}{\boxed{12}}\underset{1}{\boxed{7}}\underset{2}{\boxed{2}}\underset{3}{\boxed{43}}\underset{4}{\boxed{11}}\underset{5}{\boxed{19}}\underset{6}{\boxed{1}}\underset{7}{\boxed{3}}\underset{8}{\boxed{35}}\underset{9}{\boxed{6}}

Answer

In the first iteration, the smallest element 1 will be swapped with the element at first index 12. The contents of the array after the first iteration of Selection Sort will be:

1071224331141951263735869\underset{0}{\boxed{1}}\underset{1}{\boxed{7}}\underset{2}{\boxed{2}}\underset{3}{\boxed{43}}\underset{4}{\boxed{11}}\underset{5}{\boxed{19}}\underset{6}{\boxed{12}}\underset{7}{\boxed{3}}\underset{8}{\boxed{35}}\underset{9}{\boxed{6}}

In the second iteration, the second smallest element 2 will be swapped with the element at second index 7. The contents of the array after the second iteration of Selection Sort will be:

1021724331141951263735869\underset{0}{\boxed{1}}\underset{1}{\boxed{2}}\underset{2}{\boxed{7}}\underset{3}{\boxed{43}}\underset{4}{\boxed{11}}\underset{5}{\boxed{19}}\underset{6}{\boxed{12}}\underset{7}{\boxed{3}}\underset{8}{\boxed{35}}\underset{9}{\boxed{6}}

Question 24

Show the contents of the array after the second iteration of Bubble Sort.

35061821131549576227418659\underset{0}{\boxed{35}}\underset{1}{\boxed{6}}\underset{2}{\boxed{8}}\underset{3}{\boxed{11}}\underset{4}{\boxed{15}}\underset{5}{\boxed{9}}\underset{6}{\boxed{7}}\underset{7}{\boxed{22}}\underset{8}{\boxed{41}}\underset{9}{\boxed{65}}

Answer

In the first iteration, (35,6) will be compared and swapped. The array after the first iteration will look like:

60351821131549576227418659\underset{0}{\boxed{6}}\underset{1}{\boxed{35}}\underset{2}{\boxed{8}}\underset{3}{\boxed{11}}\underset{4}{\boxed{15}}\underset{5}{\boxed{9}}\underset{6}{\boxed{7}}\underset{7}{\boxed{22}}\underset{8}{\boxed{41}}\underset{9}{\boxed{65}}

In the second iteration, (35,8) will be compared and swapped. After the second iteration, the array will look like:

60813521131549576227418659\underset{0}{\boxed{6}}\underset{1}{\boxed{8}}\underset{2}{\boxed{35}}\underset{3}{\boxed{11}}\underset{4}{\boxed{15}}\underset{5}{\boxed{9}}\underset{6}{\boxed{7}}\underset{7}{\boxed{22}}\underset{8}{\boxed{41}}\underset{9}{\boxed{65}}

Question 25

What is the difference between linear search and binary search ?

Answer

Linear SearchBinary Search
Linear search works on sorted and unsorted arrays.Binary search works only on sorted arrays (both ascending and descending).
Each element of the array is checked against the target value until the element is found or end of the array is reached.Array is successively divided into 2 halves and the target element is searched either in the first half or in the second half.
Linear Search is slower.Binary Search is faster.

Question 26

Given the following array :

270231321832441512660747859\underset{0}{\boxed{27}}\underset{1}{\boxed{23}}\underset{2}{\boxed{3}}\underset{3}{\boxed{18}}\underset{4}{\boxed{24}}\underset{5}{\boxed{1}}\underset{6}{\boxed{12}}\underset{7}{\boxed{60}}\underset{8}{\boxed{47}}\underset{9}{\boxed{5}}

Which sorting algorithm would produce the following result after three iterations

103152183244275126607478239\underset{0}{\boxed{1}}\underset{1}{\boxed{3}}\underset{2}{\boxed{5}}\underset{3}{\boxed{18}}\underset{4}{\boxed{24}}\underset{5}{\boxed{27}}\underset{6}{\boxed{12}}\underset{7}{\boxed{60}}\underset{8}{\boxed{47}}\underset{9}{\boxed{23}}

Answer

Selection sort algorithm

Reason — We can see that after three iterations the first three elements of the array are in their correct positions. This happens in Selection sort. In Bubble sort, the heaviest element settles at its appropriate position in the bottom i.e., the array is sorted from the end to the start.

Details of each iteration are captured below:

Array after the first iteration:

102313218324427512660747859\underset{0}{\boxed{1}}\underset{1}{\boxed{23}}\underset{2}{\boxed{3}}\underset{3}{\boxed{18}}\underset{4}{\boxed{24}}\underset{5}{\boxed{27}}\underset{6}{\boxed{12}}\underset{7}{\boxed{60}}\underset{8}{\boxed{47}}\underset{9}{\boxed{5}}

Array after the second iteration:

103123218324427512660747859\underset{0}{\boxed{1}}\underset{1}{\boxed{3}}\underset{2}{\boxed{23}}\underset{3}{\boxed{18}}\underset{4}{\boxed{24}}\underset{5}{\boxed{27}}\underset{6}{\boxed{12}}\underset{7}{\boxed{60}}\underset{8}{\boxed{47}}\underset{9}{\boxed{5}}

Array after the third iteration:

103152183244275126607478239\underset{0}{\boxed{1}}\underset{1}{\boxed{3}}\underset{2}{\boxed{5}}\underset{3}{\boxed{18}}\underset{4}{\boxed{24}}\underset{5}{\boxed{27}}\underset{6}{\boxed{12}}\underset{7}{\boxed{60}}\underset{8}{\boxed{47}}\underset{9}{\boxed{23}}

Question 27

Given the following array :

130191622335428551616765849\underset{0}{\boxed{13}}\underset{1}{\boxed{19}}\underset{2}{\boxed{6}}\underset{3}{\boxed{2}}\underset{4}{\boxed{35}}\underset{5}{\boxed{28}}\underset{6}{\boxed{51}}\underset{7}{\boxed{16}}\underset{8}{\boxed{65}}\underset{9}{\boxed{4}}

Which sorting algorithm would produce the following result after three iterations.

130612219335428551616765849\underset{0}{\boxed{13}}\underset{1}{\boxed{6}}\underset{2}{\boxed{2}}\underset{3}{\boxed{19}}\underset{4}{\boxed{35}}\underset{5}{\boxed{28}}\underset{6}{\boxed{51}}\underset{7}{\boxed{16}}\underset{8}{\boxed{65}}\underset{9}{\boxed{4}}

Answer

Bubble sort algorithm

Reason — In bubble sort, the adjoining values are compared and exchanged if they are not in proper order. This process is repeated until the entire array is sorted.

In the first pass, (13,19) will be compared but not swapped. The array after the first pass will be:

130191622335428551616765849\underset{0}{\boxed{13}}\underset{1}{\boxed{19}}\underset{2}{\boxed{6}}\underset{3}{\boxed{2}}\underset{4}{\boxed{35}}\underset{5}{\boxed{28}}\underset{6}{\boxed{51}}\underset{7}{\boxed{16}}\underset{8}{\boxed{65}}\underset{9}{\boxed{4}}

In the second pass, (19, 6) will be compared and swapped. The array after the second pass will be:

130611922335428551616765849\underset{0}{\boxed{13}}\underset{1}{\boxed{6}}\underset{2}{\boxed{19}}\underset{3}{\boxed{2}}\underset{4}{\boxed{35}}\underset{5}{\boxed{28}}\underset{6}{\boxed{51}}\underset{7}{\boxed{16}}\underset{8}{\boxed{65}}\underset{9}{\boxed{4}}

In the third pass, (19, 2) will be compared and swapped. The array after the third pass will be:

130612219335428551616765849\underset{0}{\boxed{13}}\underset{1}{\boxed{6}}\underset{2}{\boxed{2}}\underset{3}{\boxed{19}}\underset{4}{\boxed{35}}\underset{5}{\boxed{28}}\underset{6}{\boxed{51}}\underset{7}{\boxed{16}}\underset{8}{\boxed{65}}\underset{9}{\boxed{4}}

Question 28

What is an array ? What is the need for arrays ?

Answer

An array is a collection of variables of the same type that are referenced by a common name. It is a reference data type which stores data values in contiguous memory locations. An array is declared and initialized as follows:

int arr[] = new int[10];

The use of arrays have the following benefits:

  1. Easy to specify — The declaration, allocation of memory space, initialization can all be done in one line of code.
  2. Free from run-time overheads — There is no run-time overhead to allocate/free memory, apart from once at the start and end.
  3. Random access of elements — Arrays facilitate random (direct) access to any element via its index or subscript.
  4. Fast Sequential Access — It is usually faster to sequentially access elements due to contiguous storage and constant time computation of the address of a component.
  5. Simple code — As arrays facilitate access of multiple data items of same type through a common name, the code becomes much simpler and easy to understand.

Question 29

What are different types of arrays? Give examples of each array type.

Answer

Arrays are of different types :

  1. One-dimensional array — It comprises of finite homogeneous elements.
  2. Multi-dimensional arrays — It comprises of elements, each of which is itself an array. A two-dimensional array is the simplest of multidimensional arrays, having two indices (rows and columns).

Question 30

Write a note on how single-dimension arrays are represented in memory.

Answer

Single-dimensional arrays are lists of information of the same type and their elements are stored in contiguous memory locations in their index order.

Internally, arrays are stored as a special object containing :

  1. A group of contiguous memory locations that all have the same name and same datatype.
  2. A reference that stores the beginning address of the array elements.
  3. A separate instance variable containing the number of elements in the array.

For example, an array grade of type char with 8 elements declared as

char grade[ ] = new char[8];

will have the element grade[0] at the first allocated memory location, grade[1] at the next contiguous memory location, grade[2] at the next, and so forth. Since grade is a char type array, each element size is 2 bytes and it will be represented in memory as shown in the figure given below:

Write a note on how single-dimension arrays are represented in memory. Arrays, Sumita Arora Computer Applications Solutions ICSE Class 10

Question 31

How does the amount of storage (in bytes) depend upon type and size of an array? Explain with the help of an example.

Answer

The amount of storage depends upon the type and size of an array as every data type requires different storage space in memory and the number of elements (size) of an array determines how many memory blocks of same size are required.

To calculate the amount of storage required by an array we use the formula:
Size = size of data type x number of elements in an array

For example, int arr[] = new int[10]; will require 4 x 10 = 40 bytes space in memory.

Question 32

What do you understand by two-dimensional arrays ? State some situations that can be easily represented by two-dimensional arrays.

Answer

A two-dimensional array is an array in which each element is itself an array. For instance, an array A[M][N] is an M by N table with M rows and N columns containing M x N elements.

The general form of a two-dimensional array declaration in Java is as follows:
type array-name[ ][ ] = new type[rows][columns];

Some situations that can be easily represented by two-dimensional arrays are as follows:

  1. In a school, marks obtained by a student in various subjects can be stored in a two-dimensional array, where rows can be used for successive tests (mid term, quarterly, half yearly etc.) and columns can be used for subjects (maths, english, science, hindi, computer etc.).
  2. In a business, the sales for a month can easily be represented using a two-dimensional array, where rows can represent weeks and columns can represent the individual days in a week.

Question 33

How are two-dimensional arrays represented in memory ?

Answer

Two-dimensional arrays are stored in a row-column matrix, where the first index indicates the row and the second indicates the column.

For example, if we have declared an array pay as follows:
short[][] pay = new short[5][7];

it will be having 5 x 7 = 35 elements which will be represented in memory as shown below :

How are two-dimensional arrays represented in memory? Arrays, Sumita Arora Computer Applications Solutions ICSE Class 10

The amount of storage required to hold a two-dimensional array is also dependent upon its base type, number of rows and number of columns. The formula to calculate total number of bytes required by a two-dimensional array is given below :

total bytes = number-of-rows x number-of-columns x size-of-base-type

Here, the array pay[][] will require 5 x 7 x 2 = 70 bytes of memory space, as the size of a byte type element is 2 bytes.

Question 34

Suppose A, B, C are arrays of integers of sizes m, n, m + n respectively. Give a program to produce a third array C, containing all the data of array A and B.

import java.util.Scanner;

public class KboatArrayMerge
{
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        System.out.print("Enter size m : ");
        int m = in.nextInt();
        int A[] = new int[m];
        
        System.out.print("Enter size n : ");
        int n = in.nextInt();
        int B[] = new int[n];
        
        int C[] = new int[m + n];
        
        System.out.println("Enter elements of array A:");
        for(int i = 0; i < m; i++)  {
            A[i] = in.nextInt();
        }
        
        System.out.println("Enter elements of array B:");
        for(int i = 0; i < n; i++)  {
            B[i] = in.nextInt();
        }
        
        int idx = 0;
        while(idx < A.length) {
            C[idx] = A[idx];
            idx++;
        }
        
        int j = 0;
        while(j < B.length) {
            C[idx++] = B[j++];
        }
        
        System.out.println("Elements of Array C :");
        for(int i = 0; i < C.length; i++)  {
            System.out.print(C[i] + " ");
        }  
    }
}
Output
BlueJ output of KboatArrayMerge.java

Question 35

Write a short program that doubles every element of an array A[4][4].

import java.util.Scanner;

public class KboatDDADouble
{
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);

        int A[][] = new int[4][4];
        System.out.println("Enter elements of 4 x 4 array");
        
        for(int i = 0; i < 4; i++)  
        {
            System.out.println("Enter elements of row " + (i+1));
            for(int j = 0; j < 4; j++)
            {
                A[i][j] = in.nextInt();
            }
        }  
        
        System.out.println("Original array :");
        for(int i = 0; i < 4; i++)  
        {
            for(int j = 0; j < 4; j++)  
            {
                System.out.print(A[i][j] + "\t");
            }   
            System.out.println();
        }
        
        for(int i = 0; i < 4; i++)  
        {
            for(int j = 0; j < 4; j++)  
            {
                A[i][j] = A[i][j] * 2;
            }   
        }  
        
        
        System.out.println("Doubled Array");
        for(int i = 0; i < 4; i++)  
        {
            for(int j = 0; j < 4; j++)  
            {
                System.out.print(A[i][j] + "\t");
            }   
            System.out.println();
        }  
    }
}
Output
BlueJ output of KboatDDADouble.java

Question 36

Let A(n x n) that are not diagonal array. Write a program to find the sum of all the elements which lie on either diagonal. For example, for the matrix shown below, your program should output 68 = (1 + 6 + 11 + 16 + 4 + 7 + 10 + 13):

[12345678910111213141516]\begin{bmatrix} 1 & 2 & 3 & 4 \\ 5 & 6 & 7 & 8 \\ 9 & 10 & 11 & 12 \\ 13 & 14 & 15 & 16 \end{bmatrix}

import java.util.Scanner;

public class KboatDDADiagonalSum
{
    public static void main(String args[]){
        
        int A[][] = {{1, 2, 3, 4} , 
                    {5, 6, 7, 8} , 
                    {9, 10, 11, 12} , 
                    {13, 14, 15, 16}};
        
        int sum = 0;
        for(int i = 0; i < 4; i++) {
            for(int j = 0; j < 4; j++) {
                if (i == j || (i + j) == 3) {
                    sum += A[i][j];
                }
            }
        }
        
        System.out.println("Sum of diagonal elements = " + sum);
        
    }
}
Output
BlueJ output of KboatDDADiagonalSum.java

Question 37

From a two-dimensional array A[4][4], write a program to prepare a one-dimensional array B[16] that will have all the elements of A if they are stored in row-major form. For example, for the following array

[12345678910111213141516]\begin{bmatrix} 1 & 2 & 3 & 4 \\ 5 & 6 & 7 & 8 \\ 9 & 10 & 11 & 12 \\ 13 & 14 & 15 & 16 \end{bmatrix}

the resultant array should be : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

import java.util.Scanner;

public class Kboat2Dto1DArray
{
    public static void main(String args[]){
        
        int A[][] = {{1, 2, 3, 4} , 
                    {5, 6, 7, 8} , 
                    {9, 10, 11, 12} , 
                    {13, 14, 15, 16}};
        
        int B[] = new int[16];
        int index = 0;
        
        for(int i = 0; i < 4; i++)  
        {
            for(int j = 0; j < 4; j++)  
            {
                B[index++] = A[i][j];
            } 
        }  
        
        System.out.println("Array B :");
        for(int i = 0; i < 16; i++)  
        {
            System.out.print(B[i] + " ");
        }
        
    }
}
Output
BlueJ output of Kboat2Dto1DArray.java

Question 38

Write a function that checks whether or not two arrays (of characters) are identical, that is, whether they have same characters and all characters in corresponding positions are equal.

public class KboatArrCompare
{
    public void arrCompare (char A[], char B[])
    {
        int l1 = A.length;
        int l2 = B.length;
        boolean flag = true;
        if (l1 == l2)   {
            for(int i = 0; i < l1; i++)  {
                if(A[i] != B[i]) {
                    flag = false;
                    break;
                } 
            }
        }
        else {
            flag = false;
        }
        
        if (flag) {
            System.out.println("Arrays are equal");
        }
        else {
            System.out.println("Arrays are not equal");
        }
    }
}
Output
BlueJ output of KboatArrCompare.java
BlueJ output of KboatArrCompare.java
BlueJ output of KboatArrCompare.java
BlueJ output of KboatArrCompare.java

Question 39

The marks obtained by 50 students in a subject are tabulated as follows :

NameMarks
..
..
..

Write a program to input the names and marks of the students in the subject. Calculate and display:

(i) The subject average marks (subject average marks = subject total / 50 )

(ii) The highest marks in the subject and the name of the student. (The maximum marks in the subject are 100)

import java.util.Scanner;

public class KboatSDAMarks
{
    public static void main(String args[]) {
        final int TOTAL_STUDENTS = 50;
        Scanner in = new Scanner(System.in);
        
        String name[] = new String[TOTAL_STUDENTS];
        int marks[] = new int[TOTAL_STUDENTS];
        int total = 0;
        
        for (int i = 0; i < name.length; i++) {
            System.out.print("Enter name of student " + (i+1) + ": ");
            name[i] = in.nextLine();
            System.out.print("Enter marks of student " + (i+1) + ": ");
            marks[i] = in.nextInt();
            total += marks[i];
            in.nextLine();
        }
        
        double avg = (double)total / TOTAL_STUDENTS;
        System.out.println("Subject Average Marks = " + avg);
        int hIdx = 0;
        
        for (int i = 1; i < marks.length; i++) {
            if (marks[i] > marks[hIdx])
                hIdx = i;
        }
        
        System.out.println("Highest Marks = " + marks[hIdx]);
        System.out.println("Name = " + name[hIdx]);
    }
}
Output
BlueJ output of KboatSDAMarks.java

Question 40

Differentiate between one-dimensional and two-dimensional arrays.

Answer

One-dimensional arrayTwo-dimensional array
One-dimensional array stores data in a single row or column.Two-dimensional array stores data in a grid or table, with rows and columns.
It uses one index to access array elements.It uses two indices to access array elements.
For example,
int arr[] = new int[10];
It creates a one dimensional array arr which stores 10 elements of int type.
For example,
int arr[][] = new int [3][3];
It creates a two dimensional array which has three rows and three columns to store 3 x 3 = 9 elements of int type.

Question 41

Explain

(i) Linear search method,

(ii) Binary search method.

Which of the two is more efficient for sorted data ?

Answer

(i) 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.

For example, consider an array

int arr[] = {5, 8, 11, 2, 9};

and the search item 2. Linear search will compare each element of the array to 2 sequentially until either the search value 2 is found or all the elements have been compared.

(ii) Binary search — Binary Search is a search-technique that works for sorted arrays. Here search-item is com­pared with the middle element of array. If the search-item matches with the element, search finishes. If search-item is less than middle (in ascending array), we perform binary-search in the first half of the array, other­ wise we perform binary search in the second half of the array.

For example, consider an array

int arr[] = {2, 5, 8, 11, 14};

and the search item 11. First, the search value will be compared with the middle value 8. Since the values are not equal, binary search will be performed in the latter half of the array, i.e., {11, 14}. The search value will be compared with the mid value, which will be 11. Since search value is found, binary search will stop.

Binary search is more efficient than linear search as it searches the given item in minimum possible comparisons.

Question 42

Write a program Lower-left-half which takes a two dimensional array A, with size N rows and N columns as argument and prints the lower left-half.

                    2 3 1 5 0
                    7 1 5 3 1
e.g.,If A is        2 5 7 8 1
                    0 1 5 0 1
                    3 4 9 1 5

                    2
                    7 1
The output will be  2 5 7
                    0 1 5 0
                    3 4 9 1 5
import java.util.Scanner;

public class KboatLowerLeftHalf
{
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        
        System.out.print("Enter size of 2D array :" );
        int n = in.nextInt();
        int A[][] = new int[n][n];
        
        System.out.println("Enter array elements : ");
        for(int i = 0; i < n; i++)  
        {   
            for(int j = 0; j < n; j++) 
            {
                A[i][j] = in.nextInt();
            }       
        } 
        
        System.out.println("Original array :" );
        for(int i = 0; i < n; i++)  
        {   
            for(int j = 0; j < n; j++) 
            {
                System.out.print(A[i][j] + " ");
            }
            System.out.println();          
        }  
        
        System.out.println("Lower Left Half array :" );
        
        for(int i = 0; i < n; i++)  
        {   
            for(int j = 0; j <= i; j++)
            {
                System.out.print(A[i][j] + " ");
            }
            
            System.out.println();          
        }  
        
    }
}
Output
BlueJ output of KboatLowerLeftHalf.java

Question 43

Write a program to search for an ITEM linearly in array X[10].

Answer

import java.util.Scanner;

public class KboatLinearSearch
{
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
    
        int X[] = new int[10];
        int i = 0;
        
        System.out.println("Enter array elements : ");
        for(i = 0; i < 10; i++)  
        {   
            X[i] = in.nextInt();      
        } 

        System.out.println("Input Array is:");
        for (i = 0; i < 10; i++) {
            System.out.print(X[i] + " ");
        }
        System.out.println();
        
        System.out.print("Enter ITEM to search : ");
        int item = in.nextInt();
        
        for (i = 0; i < 10; i++) {
            if (X[i] == item) {
                break;
            }
        }
        
        if (i == 10) {
            System.out.println("Search Unsuccessful");
        }
        else {
            System.out.println("Search Successful");
            System.out.println(item + " is present at index " + i);
        }
        
    }
}
Output
BlueJ output of KboatLinearSearch.java

Question 44

Write a program to search for an ITEM using binary search in array X[10].

import java.util.Scanner;

public class KboatBinarySearch
{
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
    
        int X[] = new int[10];
        
        System.out.println("Enter array in ascending order : ");
        for(int i = 0; i < 10; i++)  
        {   
            X[i] = in.nextInt();      
        }
        
        System.out.println("Input Array is:");
        for (int i = 0; i < 10; i++) {
            System.out.print(X[i] + " ");
        }
        System.out.println();
        
        System.out.println("Enter search item :" );
        int item = in.nextInt();
        
        int l = 0, h = 9, index = -1;
        while (l <= h) {
            int m = (l + h) / 2;
            if (X[m] < item)
                l = m + 1;
            else if (X[m] > item)
                h = m - 1;
            else {
                index = m;
                break;
            }
                
        }
        
        if (index == -1) {
            System.out.println("Search item not found");
        }
        else {
            System.out.println(item + " found at index " + index);
        }
    }
}
Output
BlueJ output of KboatBinarySearch.java

Question 45

The following array of integers is to be arranged in ascending order using the bubble sort technique:

26 21 20 23 29 17

Give the contents of the array at the end of each iteration. Do not write the algorithm.

Answer

The contents of the array at the end of each iteration are as follows:

Itr 126, 21, 20, 23, 29, 17
Itr 2 — 21, 26, 20, 23, 29, 17
Itr 3 — 21, 20, 26, 23, 29, 17
Itr 4 — 21, 20, 23, 26, 29, 17
Itr 5 — 21, 20, 23, 26, 29, 17
Itr 621, 20, 23, 26, 17, 29
Itr 7 — 20, 21, 23, 26, 17, 29
Itr 8 — 20, 21, 23, 26, 17, 29
Itr 9 — 20, 21, 23, 26, 17, 29
Itr 1020, 21, 23, 17, 26, 29
Itr 11 — 20, 21, 23, 17, 26, 29
Itr 12 — 20, 21, 23, 17, 26, 29
Itr 1320, 21, 17, 23, 26, 29
Itr 14 — 20, 21, 17, 23, 26, 29
Itr 1520, 17, 21, 23, 26, 29
Itr 16 — 17, 20, 21, 23, 26, 29

Question 46

Write a program to search for a given ITEM in a given array X[n] using linear search technique. If the ITEM is found, move it at the top of the array. If the ITEM is not found, insert it at the end of the array.

import java.util.Scanner;

public class KboatLinearSearch
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter size of array : ");
        int n = in.nextInt();
        
        int X[] = new int[n];
        int B[];
        
        System.out.println("Enter array elements : ");
        for(int i = 0; i < n; i++) {
            X[i] = in.nextInt();
        }

        System.out.println("Enter search item :" );
        int item = in.nextInt();
        
        int i = 0;
        
        // linear search
        for (i = 0; i < n; i++) {
            if (X[i] == item) {
                System.out.println("Search item found at index " 
                                    + i);
                break;
            }
        }
        
        // item not found
        if (i == n) {
            System.out.println("Search item not found");
            B = new int[n + 1];
            for(int j = 0; j < n; j++)  {
                B[j] = X[j];
            }
            B[n] = item;
            
            System.out.println("Array after inserting "
                                + item + " at end:");
            for(int j = 0; j <= n; j++)  {
                System.out.print(B[j] + " ");
            }
        }
        // item found
        else {
            for(int j = i; j >= 1; j--) {
                X[j] = X[j - 1];
            }
            X[0] = item;
                     
            System.out.println("Array after moving " 
                                + item + " to top :");
            for(int j = 0; j < n; j++)  {
                System.out.print(X[j] + " ");
            }
        }   
    }
}
Output
BlueJ output of KboatLinearSearch.java
BlueJ output of KboatLinearSearch.java

Question 47

Write a program to search for 66 and 71 in the following array :

304172113184295456717878899931096119912\underset{0}{\boxed{3}}\underset{1}{\boxed{4}}\underset{2}{\boxed{7}}\underset{3}{\boxed{11}}\underset{4}{\boxed{18}}\underset{5}{\boxed{29}}\underset{6}{\boxed{45}}\underset{7}{\boxed{71}}\underset{8}{\boxed{87}}\underset{9}{\boxed{89}}\underset{10}{\boxed{93}}\underset{11}{\boxed{96}}\underset{12}{\boxed{99}}

Make use of binary search technique. Also give the intermediate results while executing this algorithm.

public class KboatBinarySearch
{
    public int binSearch(int arr[], int item)    {
        int l = 0, index = -1;
        int h = arr.length - 1;

        System.out.println("Searching for " + item);
        while (l <= h) {
            int m = (l + h) / 2;
            System.out.println("Searching in sub-array :");
            for(int i = l; i < h; i++)
                System.out.print(arr[i] + " ");
            
            System.out.println();
            
            System.out.println("Comparing " + item + " with "
                                + arr[m] + " at index " + m);
            
            if (arr[m] < item)
                l = m + 1;
            else if (arr[m] > item)
                h = m - 1;
            else {
                index = m;
                break;
            }
        }
        return index;
    }
    
    public static void main(String args[]) {
        KboatBinarySearch obj = new KboatBinarySearch();
        
        int X[] = {3, 4, 7, 11, 18, 29, 45, 71, 87, 89, 93, 96, 99};
        
        int index = obj.binSearch(X, 66);
        if (index == -1) {
            System.out.println("66 not found");
        }
        else {
            System.out.println("66 found at index " + index);
        }
        
        index = obj.binSearch(X, 71);
        if (index == -1) {
            System.out.println("71 not found");
        }
        else {
            System.out.println("71 found at index " + index);
        }
        
    }
}
Output
BlueJ output of KboatBinarySearch.java

Question 48

Given the following array :

13071622133542528664745839510111\underset{0}{\boxed{13}}\underset{1}{\boxed{7}}\underset{2}{\boxed{6}}\underset{3}{\boxed{21}}\underset{4}{\boxed{35}}\underset{5}{\boxed{2}}\underset{6}{\boxed{28}}\underset{7}{\boxed{64}}\underset{8}{\boxed{45}}\underset{9}{\boxed{3}}\underset{10}{\boxed{5}}\underset{11}{\boxed{1}}

Write a program to sort the above array using exchange selection sort. Give the array status after every iteration.

public class KboatSelectionSort
{
    public static void main(String args[]) {
        int X[] = {13, 7, 6, 21, 35, 2, 28, 64, 45, 3, 5, 1};
        int n = X.length;
        
        for (int i = 0; i < n - 1; i++) {
            int idx = i;
            for (int j = i + 1; j < n; j++) {
                if (X[j] < X[idx])
                    idx = j;
            }
            
            int t = X[i];
            X[i] = X[idx];
            X[idx] = t; 
            
            System.out.println("Pass : " + (i + 1));
            for(int k = 0; k < n; k++) {
                System.out.print(X[k] + " ");
            }
            System.out.println();
        }
        
        System.out.println("Sorted Array:");
        for (int i = 0; i < n; i++) {
            System.out.print(X[i] + " ");
        }
    }
}
Output
BlueJ output of KboatSelectionSort.java

Question 49

For the same array mentioned above in previous question, write a program to sort the above array using bubble sort technique. Give the array-status after every iteration.

public class KboatBubbleSort
{
    public static void main(String args[]) {
        int X[] = {13, 7, 6, 21, 35, 2, 28, 64, 45, 3, 5, 1};
        int n = X.length;
        
         //Bubble Sort
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (X[j] > X[j + 1]) {
                    int t = X[j];
                    X[j] = X[j+1];
                    X[j+1] = t;
                }
            } 
            System.out.println("Pass :" + (i + 1));
            for(int k = 0; k < n; k++) {
                System.out.print(X[k] + " ");
            }
            System.out.println();
        }    
        
        System.out.println("Sorted Array:");
        for (int i = 0; i < n; i++) {
            System.out.print(X[i] + " ");
        }
    }
}
Output
BlueJ output of KboatBubbleSort.java

Question 50

Write a program to input integer elements into an array of size 20 and perform the following operations :

(i) Display largest number from the array.

(ii) Display smallest number from the array.

(iii) Display sum of all the elements of the array.

import java.util.Scanner;

public class KboatSDAMinMaxSum
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int arr[] = new int[20];
        System.out.println("Enter 20 numbers:");
        for (int i = 0; i < 20; i++) {
            arr[i] = in.nextInt();
        }
        int min = arr[0], max = arr[0], sum = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] < min)
                min = arr[i];
                
            if (arr[i] > max)
                max = arr[i];
                
            sum += arr[i];
        }
        
        System.out.println("Largest Number = " + max);
        System.out.println("Smallest Number = " + min);
        System.out.println("Sum = " + sum);
    }
}
Output
BlueJ output of KboatSDAMinMaxSum.java

Question 51

Write a program to input forty words in an array. Arrange these words in descending order of alphabets, using selection sort technique. Print the sorted array.

import java.util.Scanner;

public class KboatSelectionSort
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        String a[] = new String[40];
        int n = a.length;
        
        System.out.println("Enter 40 Names: ");
        for (int i = 0; i < n; i++) {
            a[i] = in.nextLine();
        }
        
        for (int i = 0; i < n - 1; i++) {
            int idx = i;
            for (int j = i + 1; j < n; j++) {
                if (a[j].compareToIgnoreCase(a[idx]) < 0) {
                    idx = j;
                }
            }
            String t = a[idx];
            a[idx] = a[i];
            a[i] = t;
        }
        
        System.out.println("Sorted Names");
        for (int i = 0; i < n; i++) {
            System.out.println(a[i]);
        }
    }
}
Output
BlueJ output of KboatSelectionSort.java

Question 52

Write a program that reads a 4 x 5 two dimensional array and then prints the column sums of the array along with the array printed in matrix form.

import java.util.Scanner;

public class KboatDDAColSum
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        
        int arr[][] = new int[4][5];
        
        System.out.println("Enter the 2D array:");
        for (int i = 0; i < 4; i++) {
            System.out.println("Enter elements of row " + (i + 1));
            for (int j = 0; j < 5; j++) {
                arr[i][j] = in.nextInt();
            }
        }
        
        System.out.println("Input array :");
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 5; j++) {
                System.out.print(arr[i][j] + "\t");
            }
            System.out.println();
        }
        
        //Compute column-wise sum
        for (int i = 0; i < 5; i++) {
            int cSum = 0;
            for (int j = 0; j < 4; j++) {
                cSum += arr[j][i];
            }
            System.out.println("Column " + (i + 1) 
                                + " sum = " + cSum);
        }
        
    }
}
Output
BlueJ output of KboatDDAColSum.java

Question 53

Write a program that inputs a 2D array and displays how the array elements will look in row major form and column major form.

import java.util.Scanner;

public class KboatDDARowColMajor
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        
        System.out.print("Enter number of rows: ");
        int rows = in.nextInt();
        System.out.print("Enter number of columns: ");
        int cols = in.nextInt();
        int arr[][] = new int[rows][cols];
        
        System.out.println("Enter the 2D array:");
        for (int i = 0; i < rows; i++) {
            System.out.println("Enter elements of row " + (i + 1));
            for (int j = 0; j < cols; j++) {
                arr[i][j] = in.nextInt();
            }
        }
        
        System.out.println("Input array :");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print(arr[i][j] + "\t");
            }
            System.out.println();
        }
        
        System.out.println("Array in row major form:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print(arr[i][j] + " ");
            }
        }
        
        System.out.println();
        
        System.out.println("Array in column major form:");
        for (int i = 0; i < cols; i++) {
            for (int j = 0; j < rows; j++) {
                System.out.print(arr[j][i] + " ");
            }
        }

    }
}
Output
BlueJ output of KboatDDARowColMajor.java

Video Explanations

PrevNext