0% found this document useful (0 votes)
7 views14 pages

Array Basics: Questions & Examples

The document contains multiple-choice and assignment questions related to arrays in programming, covering topics such as array declaration, initialization, searching algorithms (linear and binary), and sorting techniques (bubble and selection sort). It includes code examples for various operations on arrays, such as finding minimum and maximum values, computing sums, and handling user input. Additionally, it explains concepts like array bounds and runtime errors in Java.
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)
7 views14 pages

Array Basics: Questions & Examples

The document contains multiple-choice and assignment questions related to arrays in programming, covering topics such as array declaration, initialization, searching algorithms (linear and binary), and sorting techniques (bubble and selection sort). It includes code examples for various operations on arrays, such as finding minimum and maximum values, computing sums, and handling user input. Additionally, it explains concepts like array bounds and runtime errors in Java.
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

Chapter 14

Arrays

Multiple Choice Questions


Question 1
The size of an array that signifies the number of elements it can store is given using ...........
brackets.
1. {}
2. [] ✓
3. ()
4. All of these
Question 2
Given array int x[] = {11, 22, 33, 44}; the value of x[1] is ........... .
1. 11
2. 22 ✓
3. 33
4. Invalid value
Question 3
Given array int x[] = {11, 22, 33, 44}; the value of x[1+2] is ........... .
1. 11
2. 22
3. 33
4. 44 ✓
Question 4
If int arr[] = {3, 5, 7, 9}; what is the value of [Link]?
1. 3
2. 5
3. 4 ✓
4. Cannot be determined
Question 5
Given array int z[] = {15, 16, 17}; It will occupy ........... bytes in memory.
1. 3
2. 12 ✓
3. 24
4. 64
Question 6
A linear search ...........
1. can be used with sorted arrays only
2. can be used with unsorted arrays only
3. can be used with both sorted and unsorted arrays ✓
4. cannot be used with arrays
Question 7
A binary search
1. can be used with sorted arrays only ✓
2. can be used with unsorted arrays only
3. can be used with both sorted and unsorted arrays
4. cannot be used with arrays
Question 8
Which of the following statements is true?
1. Binary search is less efficient than the sequential search.
2. Binary search is less efficient than the linear search.
3. Binary search is more efficient than the sequential search. ✓
4. Binary search is as efficient as the sequential search.

Question 9
In ........... search, the algorithm uses the middle value of the array for the search operation.
1. Binary ✓
2. Linear
3. Bubble
4. Selection
Question 10
Which element is num[9] of the array num?
1. 8th
2. 9th
3. 10th ✓
4. 11th
Assignment Questions
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
Answer
public class MinMaxSum
{
public static void main(String args[]) {
int arr[] = {2, 5, 4, 1, 3};

int max = arr[0];


int min = arr[0];
int sum = 0;

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


if (arr[i] > max)
max = arr[i];

if (arr[i] < min)


min = arr[i];

sum += arr[i];
}

[Link]("Minimum value: " + min);


[Link]("Maximum value: " + max);
[Link]("Sum of the elements: " + sum);
}
}

Question 2
Differentiate between the following.
i. Array Declaration and Initialisation
Answer
Array declaration tells the compiler about the size and data type of the array so that the compiler
can reserve the required memory for the array. This reserved memory is still empty. Array
Initialisation assigns values to the array elements i.e. it stores values in the memory reserved for
the array elements.
ii. int a[10] and char a[10]
Answer
int a[10] is an array of int data type that can hold 10 integer values whereas char a[10] is an array
of char data type that can hold 10 characters.

iii. Sorting and Searching


Answer
Sorting Searching
Sorting means to arrange the elements of the array Searching means to search for a term or
in ascending or descending order. value in an array.
Bubble sort and Selection sort are examples of Linear search and Binary search are
sorting techniques. examples of search techniques.

iv. Linear search and Binary search


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

v. Selection sort and Bubble sort


Answer
Selection sort Bubble sort
Selection Sort selects the smallest element from Bubble Sort compares adjacent
unsorted sub-array and swaps it with the leftmost elements and swaps them if they are in
unsorted element. wrong order.
Performs lesser number of swaps to sort the same Performs more number of swaps to sort
array relative to Bubble Sort the array
Selection Sort is faster Bubble Sort is slower

Question 3
How does the linear search find an element in the array? Explain your answer with a suitable
example.
Answer
In linear search, we start at the first element of the array and sequentially check each element of
the list for the search value until a match is found or all the elements have been searched. As
soon as the search value is found, the algorithm quits and returns the position (index) of the target
value in the array.
For example, consider the following array:
int arr[] = {1, 8, 4, 7, 5};
We want to check if 7 is present in the array or not. Linear search will first check if 1 is equal to 7,
then it will move on to the next element which is 8. It will keep doing this in a linear progression
and when it reaches the element at index 3, it finds a match so it will give us this index 3 which
means that 7 is present at index 3 of array arr.
Question 4
Explain the technique of Bubble Sort with an example.
Answer
Bubble Sort is a sorting algorithm that works by repeatedly iterating through the array, comparing
each pair of adjoining elements and swapping them if they are in wrong order.
For example, consider the following unsorted array:
9 5 2 3
Pass 1
First 9 is compared with 5 and as 9 is greater than 5 the elements are swapped:
5 9 2 3
Next, 9 is compared with 2 and as 9 is greater than 2 the elements are swapped:
5 2 9 3
Next, 9 is compared with 3 and as 9 is greater than 3 the elements are swapped:
5 2 3 9
At the end of first pass, the highest element of the array is at the last position.
Pass 2
5 is compared with 2 and as 5 is greater than 2 the elements are swapped:
2 5 3 9
Next, 5 is compared with 3 and as 5 is greater than 3 the elements are swapped:
2 3 5 9
At the end of first pass, the second highest element of the array is in its correct position.
Pass 3
2 is compared with 3 and as 2 is less then 3 no swapping takes place.
2 3 5 9
With this, the third and final pass ends and the elements of the array are in sorted order.

Question 5
Explain the technique of Selection Sort with an example.
Answer
Selection Sort divides the array into two parts — sorted sub-array and unsorted sub-array. In each
pass, it finds the minimum element of the unsorted sub-array and swaps it with the leftmost
unsorted element moving the sorted sub-array one element to the right.
For example, consider the following unsorted array:
9 5 2 3
Pass 1
At the start, the smallest element of the array is selected (which is 2) and swapped with the
element at 0th index (which is 9):
2 5 9 3
At the end of the first pass, the smallest element is in its correct position. Length of sorted sub-
array is 1 and unsorted sub-array is 3.
Pass 2
The smallest element of the unsorted sub-array is selected (which is 3) and swapped with the
element at 1st index (which is 5):
2 3 9 5
At the end of the second pass, length of sorted sub-array is 2 and unsorted sub-array is 2.
Pass 3
The smallest element of the unsorted sub-array is selected (which is 5) and swapped with the
element at 2nd index (which is 9):
2 3 5 9
With this, the third and final pass ends and the elements of the array are in sorted order.

Question 6
Why does Binary Search need a sorted array to perform the search operation?
Answer
In Binary Search, the array is repeatedly divided into two halves and the element is searched in
that half whose last element is greater than or equal to the element being searched. For this
reason, Binary Search needs a sorted array to perform the search operation.

Question 7
How does the binary search find the presence of an element quicker than the linear search?
Answer
As Binary Search repeatedly divides the array into two halves and performs the search in only one
of those two halves, it needs to make fewer comparisons relative to Linear Search hence it is
faster than Linear Search.

Question 8
Write a program to input integer elements into an array of size 20 and perform the following
operations:
1. Display largest number from the array
2. Display smallest number from the array
3. Display sum of all the elements of the array
Answer
import [Link];

public class SDAMinMaxSum


{
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 < 20; i++) {
arr[i] = [Link]();
}
int min = arr[0], max = arr[0], sum = 0;
for (int i = 0; i < [Link]; i++) {
if (arr[i] < min)
min = arr[i];

if (arr[i] > max)


max = arr[i];

sum += arr[i];
}

[Link]("Largest Number = " + max);


[Link]("Smallest Number = " + min);
[Link]("Sum = " + sum);
}
}

Question 9
Declare and instantiate a one dimensional int array named evenNums with five elements. Use an
initialiser list that contains the first five even integers, starting with 11.
Answer
int evenNums[] = {12, 14, 16, 18, 20};

Question 10
Suppose x is an array of type int[] with 50 elements. Write a code segment that will count and print
the frequency of number 42 in the array.
Answer
int c = 0;
for (int i = 0; i < 50; i++) {
if (x[i] == 42) {
c++;
}
}
[Link]("Frequency of 42 = " + c);

Question 11
A student wrote the following code segment, intending to print 11 22 33 44:
int arr[] = {11, 22, 33, 44};
for (int i = 1; i <= 4; i++)
[Link](arr[i]);
However, the program crashed with a run-time error. Can you explain the reason for this?
Answer
Array index starts at 0 not 1. In the given program, the for loop run from 1 to 4 whereas the
indexes of the array range from 0 to 3. When i becomes 4, the program tries to access an index of
arr that is not present in the array and this causes the program to crash. The correct way will be to
run the for loop from 0 to 3 instead of 1 to 4.

Question 12
Write a code segment to compute the sum of all positive real numbers stored in the following
array.
double numb[] = new double[50];
Answer
double sum = 0;
for (int i = 0; i < 50; i++) {
if (numb[i] > 0) {
sum += numb[i];
}
}
[Link]("Sum of positive real numbers = " + sum);

Question 13
Write a code segment that finds the largest integer in this two-dimensional array.
int data[][] = new int[5][5];
Answer
int l = data[0][0];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (data[i][j] > l) {
l = data[i][j];
} }}
[Link]("Largest Element = " + l);

Question 14
Given the following declarations:
final int SIZE = 20;
char[] name = new char[SIZE];
i. Write an assignment statement that stores 'D' into the first element of the array name.
ii. Write an output statement that prints the value of the tenth element of the array name.
iii. Write a for statement that fills the array name with spaces.
Answer
i. name[0] = 'D';
ii. [Link](name[9]);
iii. For Statement:
for (int i = 0; i < SIZE; i++) {
name[i] = ' ';
}

Question 15
What happens in Java if you try to access an element that is outside the bounds of the array?
Answer
Accessing an element that is outside the bounds of the array results in a runtime error in the form
of ArrayIndexOutOfBoundsException.

Question 16
Write Java statements for the following:
i. Create an array to hold 15 double values.
ii. Assign the value 10.5 to the last element in the array.
iii. Display the sum of the first and the last element.
iv. Write a loop that computes the sum of all elements in the array.
Answer
i. Create an array to hold 15 double values.
double arr[] = new double[15];
ii. Assign the value 10.5 to the last element in the array.
arr[14] = 10.5;
iii. Display the sum of the first and the last element.
double r = arr[0] + arr[14];
[Link]("Result = " + r);
iv. Write a loop that computes the sum of all elements in the array.
double sum = 0;
for (int i = 0; i < 15; i++) {
sum += arr[i];
}
[Link]("Sum = " + sum);

Question 17
Write a program to accept the year of graduation from school as an integer value from the user.
Using the binary search technique on the sorted array of integers given below, output the
message "Record exists" if the value input is located in the array. If not, output the message
"Record does not exist".
Sample Input:
n[0] n[1] n[2] n[3] n[4] n[5] n[6] n[7] n[8] n[9]
1982 1987 1993 1996 1999 2003 2006 2007 2009 2010
Answer
import [Link];

public class GraduationYear


{
public static void main(String args[]) {
Scanner in = new Scanner([Link]);
int n[] = {1982, 1987, 1993, 1996, 1999, 2003, 2006, 2007, 2009, 2010};

[Link]("Enter graduation year to search: ");


int year = [Link]();

int l = 0, h = [Link] - 1, idx = -1;


while (l <= h) {
int m = (l + h) / 2;
if (n[m] == year) {
idx = m;
break;
}
else if (n[m] < year) {
l = m + 1;
}
else {
h = m - 1;
}
}

if (idx == -1)
[Link]("Record does not exist");
else
[Link]("Record exists");
}
}

Question 18
Write a program that reads ten integers and displays them in the reverse order in which they were
read.
Answer
import [Link];
public class SDAReverse
{
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] + " ");
}
}
}

Question 19
Write a program that reads a long number, counts and displays the occurrences of each digit in it.
Answer
import [Link];

public class SDANumber


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

Scanner in = new Scanner([Link]);


[Link]("Enter a number: ");
long num = [Link]();
int dCount[] = new int[10];

while (num != 0) {
int d = (int)(num % 10);
dCount[d] = dCount[d] + 1;
num /= 10;
}

[Link]("Digit\tOccurence");
for (int i = 0; i < 10; i++) {
if (dCount[i] != 0) {
[Link](i + "\t" + dCount[i]);
}
}
}
}

Question 20
Write a program to input 10 integer elements in an array and sort them in descending order using
bubble sort technique.
Answer
import [Link];

public class BubbleSortDsc


{
public static void main(String args[]) {
Scanner in = new Scanner([Link]);
int n = 10;
int arr[] = new int[n];

[Link]("Enter the elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = [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] + " ");
}
}
}

Question 21
Write a program to perform binary search on a list of integers given below, to search for an
element input by the user. If it is found display the element along with its position, otherwise
display the message "Search element not found".
5, 7, 9, 11, 15, 20, 30, 45, 89, 97
Answer
import [Link];

public class BinarySearch


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

Scanner in = new Scanner([Link]);


int arr[] = {5, 7, 9, 11, 15, 20, 30, 45, 89, 97};

[Link]("Enter number to search: ");


int n = [Link]();

int l = 0, h = [Link] - 1, index = -1;


while (l <= h) {
int m = (l + h) / 2;
if (arr[m] < n)
l = m + 1;
else if (arr[m] > n)
h = m - 1;
else {
index = m;
break;
}

if (index == -1) {
[Link]("Search element not found");
}
else {
[Link](n + " found at position " + index);
}
}
}

Question 22
Write a program to store 6 elements in an array P and 4 elements in an array Q. Now, produce a
third array R, containing all the elements of array P and Q. Display the resultant array.
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
Answer
import [Link];

public class 3Arrays


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

Scanner in = new Scanner([Link]);


int P[] = new int[6];
int Q[] = new int[4];
int R[] = new int[10];
int i = 0;

[Link]("Enter 6 elements of array P:");


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

[Link]("Enter 4 elements of array Q:");


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

i = 0;
while(i < [Link]) {
R[i] = P[i];
i++;
}

int j = 0;
while(j < [Link]) {
R[i++] = Q[j++];
}

[Link]("Elements of Array R:");


for (i = 0; i < [Link]; i++) {
[Link](R[i] + " ");
}
}
}

Question 23
The annual examination result of 50 students in a class is tabulated in a Single Dimensional Array
(SDA) as follows:
Roll No. Subject A Subject B Subject C
....... ....... ....... .......
....... ....... ....... .......
....... ....... ....... .......
Write a program to read the data, calculate and display the following:
(a) Average marks obtained by each student.
(b) Print the roll number and the average marks of the students whose average is above. 80.
(c) Print the roll number and the average marks of the students whose average is below 40.
Answer
import [Link];

public class ExamResult


{
public static void main(String args[]) {
final int TOTAL_STUDENTS = 50;
Scanner in = new Scanner([Link]);

int rollNo[] = new int[TOTAL_STUDENTS];


int sA[] = new int[TOTAL_STUDENTS];
int sB[] = new int[TOTAL_STUDENTS];
int sC[] = new int[TOTAL_STUDENTS];
double avg[] = new double[TOTAL_STUDENTS];

for (int i = 0; i < TOTAL_STUDENTS; i++) {


[Link]("Enter student " + (i+1) + " details:");
[Link]("Roll No: ");
rollNo[i] = [Link]();
[Link]("Subject A Marks: ");
sA[i] = [Link]();
[Link]("Subject B Marks: ");
sB[i] = [Link]();
[Link]("Subject C Marks: ");
sC[i] = [Link]();
avg[i] = (sA[i] + sB[i] + sC[i]) / 3.0;
}

[Link]("\nRoll No\tAverage Marks");


for (int i = 0; i < TOTAL_STUDENTS; i++) {
[Link](rollNo[i] + "\t" + avg[i]);
}

[Link]("\nStudents with Average above 80:");


for (int i = 0; i < TOTAL_STUDENTS; i++) {
if (avg[i] > 80)
[Link](rollNo[i] + "\t" + avg[i]);
}

[Link]("\nStudents with Average below 40:");


for (int i = 0; i < TOTAL_STUDENTS; i++) {
if (avg[i] < 40)
[Link](rollNo[i] + "\t" + avg[i]);
}
}
}

Question 24
Declare a single dimensional array of size 28 to store daily temperatures for the month of
February. Using this structure, write a program to find:
1. The hottest day of the month
2. The coldest day of the month
3. The average temperature of the month
Answer
import [Link];
public class FebTemp
{
public static void main(String args[]) {
Scanner in = new Scanner([Link]);
double febTemp[] = new double[28];
int n = [Link];

[Link]("Enter Feb daily temperatures:");


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

double sum = 0.0;


int low = 0, high = 0;
for (int i = 0; i < n; i++) {
if (febTemp[i] < febTemp[low])
low = i;

if (febTemp[i] > febTemp[high])


high = i;

sum += febTemp[i];
}

double avg = sum / n;

[Link]("Hottest day = " + (high + 1));


[Link]("Coldest day = " + (low + 1));
[Link]("Average Temperature = " + avg);
}
}

You might also like