Multiple Choice Questions
Question 1
The size of an array that signifies the number of elements it can store is given using ........... brackets.
- {}
- [] ✓
- ()
- All of these
Question 2
Given array int x[] = {11, 22, 33, 44}; the value of x[1] is ........... .
- 11
- 22 ✓
- 33
- Invalid value
Question 3
Given array int x[] = {11, 22, 33, 44}; the value of x[1+2] is ........... .
- 11
- 22
- 33
- 44 ✓
Question 4
If int arr[] = {3, 5, 7, 9}; what is the value of arr.length?
- 3
- 5
- 4 ✓
- Cannot be determined
Question 5
Given array int z[] = {15, 16, 17}; It will occupy ........... bytes in memory.
- 3
- 12 ✓
- 24
- 64
Question 6
A linear search ...........
- can be used with sorted arrays only
- can be used with unsorted arrays only
- can be used with both sorted and unsorted arrays ✓
- cannot be used with arrays
Question 7
A binary search
- can be used with sorted arrays only ✓
- can be used with unsorted arrays only
- can be used with both sorted and unsorted arrays
- cannot be used with arrays
Question 8
Which of the following statements is true?
- Binary search is less efficient than the sequential search.
- Binary search is less efficient than the linear search.
- Binary search is more efficient than the sequential search. ✓
- 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.
- Binary ✓
- Linear
- Bubble
- Selection
Question 10
Which element is num[9] of the array num?
- 8th
- 9th
- 10th ✓
- 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 KboatMinMaxSum
{
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 < arr.length; i++) {
if (arr[i] > max)
max = arr[i];
if (arr[i] < min)
min = arr[i];
sum += arr[i];
}
System.out.println("Minimum value: " + min);
System.out.println("Maximum value: " + max);
System.out.println("Sum of the elements: " + sum);
}
}
Output
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 in ascending or descending order. | Searching means to search for a term or value in an array. |
Bubble sort and Selection sort are examples of sorting techniques. | Linear search and Binary search are examples of search techniques. |
iv. Linear search and Binary search
Answer
Linear Search | Binary Search |
---|---|
Linear search works on sorted and unsorted arrays | Binary search works on only sorted arrays (ascending or 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 |
v. Selection sort and Bubble sort
Answer
Selection sort | Bubble sort |
---|---|
Selection Sort selects the smallest element from unsorted sub-array and swaps it with the leftmost unsorted element. | Bubble Sort compares adjacent elements and swaps them if they are in wrong order. |
Performs lesser number of swaps to sort the same array relative to Bubble Sort | Performs more number of swaps to 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:
- Display largest number from the array
- Display smallest number from the array
- Display sum of all the elements of the array
Answer
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
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++;
}
}
System.out.println("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++)
System.out.println(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];
}
}
System.out.println("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];
}
}
}
System.out.println("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. System.out.println(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];
System.out.println("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];
}
System.out.println("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 java.util.Scanner;
public class KboatGraduationYear
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n[] = {1982, 1987, 1993, 1996, 1999, 2003, 2006, 2007, 2009, 2010};
System.out.print("Enter graduation year to search: ");
int year = in.nextInt();
int l = 0, h = n.length - 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)
System.out.println("Record does not exist");
else
System.out.println("Record exists");
}
}
Output
Question 18
Write a program that reads ten integers and displays them in the reverse order in which they were read.
Answer
import java.util.Scanner;
public class KboatSDAReverse
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int arr[] = new int[10];
System.out.println("Enter 10 integers:");
for (int i = 0; i < 10; i++) {
arr[i] = in.nextInt();
}
System.out.println("Integers in reverse order:");
for (int i = 9; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}
Output
Question 19
Write a program that reads a long number, counts and displays the occurrences of each digit in it.
Answer
import java.util.Scanner;
public class KboatSDANumber
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
long num = in.nextLong();
int dCount[] = new int[10];
while (num != 0) {
int d = (int)(num % 10);
dCount[d] = dCount[d] + 1;
num /= 10;
}
System.out.println("Digit\tOccurence");
for (int i = 0; i < 10; i++) {
if (dCount[i] != 0) {
System.out.println(i + "\t" + dCount[i]);
}
}
}
}
Output
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 java.util.Scanner;
public class KboatBubbleSortDsc
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = 10;
int arr[] = new int[n];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
//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;
}
}
}
System.out.println("Sorted Array:");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
Output
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 java.util.Scanner;
public class KboatBinarySearch
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int arr[] = {5, 7, 9, 11, 15, 20, 30, 45, 89, 97};
System.out.print("Enter number to search: ");
int n = in.nextInt();
int l = 0, h = arr.length - 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) {
System.out.println("Search element not found");
}
else {
System.out.println(n + " found at position " + index);
}
}
}
Output
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 java.util.Scanner;
public class Kboat3Arrays
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int P[] = new int[6];
int Q[] = new int[4];
int R[] = new int[10];
int i = 0;
System.out.println("Enter 6 elements of array P:");
for (i = 0; i < P.length; i++) {
P[i] = in.nextInt();
}
System.out.println("Enter 4 elements of array Q:");
for (i = 0; i < Q.length; i++) {
Q[i] = in.nextInt();
}
i = 0;
while(i < P.length) {
R[i] = P[i];
i++;
}
int j = 0;
while(j < Q.length) {
R[i++] = Q[j++];
}
System.out.println("Elements of Array R:");
for (i = 0; i < R.length; i++) {
System.out.print(R[i] + " ");
}
}
}
Output
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 java.util.Scanner;
public class KboatExamResult
{
public static void main(String args[]) {
final int TOTAL_STUDENTS = 50;
Scanner in = new Scanner(System.in);
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++) {
System.out.println("Enter student " + (i+1) + " details:");
System.out.print("Roll No: ");
rollNo[i] = in.nextInt();
System.out.print("Subject A Marks: ");
sA[i] = in.nextInt();
System.out.print("Subject B Marks: ");
sB[i] = in.nextInt();
System.out.print("Subject C Marks: ");
sC[i] = in.nextInt();
avg[i] = (sA[i] + sB[i] + sC[i]) / 3.0;
}
System.out.println("\nRoll No\tAverage Marks");
for (int i = 0; i < TOTAL_STUDENTS; i++) {
System.out.println(rollNo[i] + "\t" + avg[i]);
}
System.out.println("\nStudents with Average above 80:");
for (int i = 0; i < TOTAL_STUDENTS; i++) {
if (avg[i] > 80)
System.out.println(rollNo[i] + "\t" + avg[i]);
}
System.out.println("\nStudents with Average below 40:");
for (int i = 0; i < TOTAL_STUDENTS; i++) {
if (avg[i] < 40)
System.out.println(rollNo[i] + "\t" + avg[i]);
}
}
}
Output
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:
- The hottest day of the month
- The coldest day of the month
- The average temperature of the month
Answer
import java.util.Scanner;
public class KboatFebTemp
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
double febTemp[] = new double[28];
int n = febTemp.length;
System.out.println("Enter Feb daily temperatures:");
for (int i = 0; i < n; i++) {
febTemp[i] = in.nextDouble();
}
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;
System.out.println("Hottest day = " + (high + 1));
System.out.println("Coldest day = " + (low + 1));
System.out.println("Average Temperature = " + avg);
}
}
Output
Question 25
Repeat the above exercise using a double two-dimensional array with 4 rows and 7 columns to store daily temperatures for the month of February.
Answer
import java.util.Scanner;
public class KboatDDAFebTemp
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
double febTemp[][] = new double[4][7];
System.out.println("Enter Feb daily temperatures:");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 7; j++) {
febTemp[i][j] = in.nextDouble();
}
}
double sum = 0.0;
int lx = 0, ly = 0, hx = 0, hy = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 7; j++) {
if (febTemp[i][j] < febTemp[lx][ly]) {
lx = i;
ly = j;
}
if (febTemp[i][j] > febTemp[hx][hy]) {
hx = i;
hy = j;
}
sum += febTemp[i][j];
}
}
double avg = sum / 28;
System.out.println("Hottest day = " + (hx * 7 + hy + 1));
System.out.println("Coldest day = " + (lx * 7 + ly + 1));
System.out.println("Average Temperature = " + avg);
}
}
Output
Question 26
The weekly hours of all employees of ABC Consulting Ltd. are stored in a two-dimensional array. Each row records an employee's 7-day work hours with seven columns. For example, the following array stores the work hours of five employees. Write a program that displays employees and their total hours in decreasing order of the total hours.
S. No. | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
---|---|---|---|---|---|---|---|
Employee 0 | 8 | 5 | 1 | 11 | 1 | 0 | 0 |
Employee 1 | 11 | 6 | 0 | 2 | 2 | 2 | 4 |
Employee 2 | 4 | 5 | 4 | 10 | 4 | 3 | 1 |
Employee 3 | 4 | 7 | 3 | 12 | 6 | 2 | 0 |
Employee 4 | 3 | 8 | 3 | 2 | 4 | 4 | 0 |
Answer
import java.util.Scanner;
public class KboatABCConsulting
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter total number of employees: ");
int numEmps = in.nextInt();
int workHours[][] = new int[numEmps][7];
int empArr[] = new int[numEmps];
int hours[] = new int[numEmps];
//Enter employee hours in 2D array
for (int i = 0; i < numEmps; i++) {
System.out.println("Enter hours for Employee " + i);
for (int j = 0; j < 7; j++) {
workHours[i][j] = in.nextInt();
}
}
//Calculate total hours for each employee
for (int i = 0; i < numEmps; i++) {
int totalHours = 0;
for (int j = 0; j < 7; j++) {
totalHours += workHours[i][j];
}
empArr[i] = i;
hours[i] = totalHours;
}
//Sort total hours hours in decreasing order
for (int i = 0; i < numEmps - 1; i++) {
int index = i;
for (int j = i + 1; j < numEmps; j++) {
if (hours[j] > hours[index])
index = j;
}
int t = hours[i];
hours[i] = hours[index];
hours[index] = t;
t = empArr[i];
empArr[i] = empArr[index];
empArr[index] = t;
}
//Display sorted total hours
for (int i = 0; i < numEmps; i++)
System.out.println("Employee " + empArr[i]
+ "\t" + hours[i]);
}
}
Output
Question 27
Write a program that computes the standard deviation of N real numbers. The standard deviation s is computed according to:
The variable is the average of N input values through . The program first prompts the user for N and then declares an array of size N.
Answer
import java.util.Scanner;
public class KboatStdDev
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter N:");
int n = in.nextInt();
double a[] = new double[n];
System.out.println("Enter the numbers:");
for (int i = 0; i < n; i++) {
a[i] = in.nextDouble();
}
double sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i];
}
double avg = sum / n;
double z = 0;
for (int i = 0; i < n; i++) {
z += Math.pow(a[i] - avg, 2);
}
double s = Math.sqrt(z / n);
System.out.println("Standard Deviation(s) = " + s);
}
}