Вы находитесь на странице: 1из 121

ICSE Question Paper – 2018 (Solved)

Computer Applications
Class X

SECTION A (40 Marks)


Answer all questions from this Section

SECTION A (40 MARKS)


Attempt all questions

Question 1:
(a) Define abstraction. [2]
Ans. Abstraction refers to specifying the behaviour of a class without going into the details of the
implementation.

(b) Differentiate between searching and sorting. [2]


Ans. In searching, we are provided with an array which contains multiple elements and asked to find the index
of a specific element.
In sorting, an array is provided and we are asked to order the elements in either ascending or descending order.

(c) Write a difference between the functions isUpperCase() and toUpperCase(). [2]
Ans. Both isUpperCase() and toUpperCase() are functions of the Character class.
isUpperCase() accepts a character and returns true if the provided character is uppercase. Else, it returns false.
Ex:

1 boolean b1 = Character.isUpperCase('a');
2 boolean b2 = Character.isUpperCase('A');
3 System.out.println(b1 + " " + b2);

will print

1 false true

(d) How are private members of a class different from public members? [2]
Ans. Private members of a class can be accessed only by the methods of the class in which they are declared.
While public members can be accessed outside of the class also.

(e) Classify the following as primitive or non-primitive data types: [2]


(i) char
(ii) arrays
(iii) int
(iv) classes
Ans. (i) char – Primitive
(ii) arrays – Non primitive
(iii) int – Primitive
(iv) Classes – Non proimitive

Question 2
(a) (i) int res = ‘A’;
What is the value of res?
(ii) Name the package that contains wrapper classes. [2]
Ans. (i) res will hold the ASCII value of ‘A’ which is 65.
(ii) java.lang package contains wrapper classes.

(b) State the difference between while and do-while loop. [2]
Ans. A while is an entry controlled loop i.e. the loop condition is checked before the loop is executed while
do-while is an exit controlled loop i.e. the loop condition is checked after the loop is executed.
Because of this a do-while loop gets executed atleast once which is not true for a while loop.

(c) System.out.print(“BEST “);


System.out.println(“OF LUCK”);
Choose the correct option for the output of the above statements: [2]
(i) BEST OF LUCK
(ii) BEST
OF LUCK
Ans. (i) is the correct output.
System.out.print() does not add a new line at the end because of which ‘OF LUCK’ gets printed on the same
line as ‘BEST’.

(d) Write the prototype of a function check which takes an integer as an argument and returns a
character. [2]
Ans.

1 char function(int a)

(e) Write the return data type of the following functions: [2]
(i) endsWith()
(ii) log()
Ans. i) boolean
ii) double

Question 3
(a) Write a Java expression for the following: [2]
√(3x + x2) / (a + b)
Ans. Math.sqrt(3 * x + Math.pow(x, 2)) / (a + b)

(b) What is the value of y after evaluating the expression given below? [2]
y += ++y + y– + –y; when int y = 8.
Ans.
y += ++y + y– + –y
y = 8 + ++y + y– + –y
y=8+9+9+7
y = 33

(c) Give the output of the following: [2]


(i) Math.floor(-4.7)
(ii) Math.ceil(3.4) + Math.pow(2, 3)
Ans. i) -5.0
ii) 4.0 + 8.0 = 12.0
(d) Write two characteristics of a constructor. [2]
Ans. i) A constructor has the same name as that of the class
ii) A constructor does not have a return type

(e) Write the output for the following: [2]


System.out.println(“Incredible” + “\n” + “world”);
Ans.

1 Incredible
2 world

(f) Convert the following if else if construct into switch case: [2]

1 if(var == 1)
2 System.out.println("good");
3 else if(var == 2)
4 System.out.println("better");
5 else if(var == 3)
6 System.out.println("best");
7 else
8 System.out.println("invalid");

Ans.

1 switch(var) {
2 case 1:
3 System.out.println("good");
4 break;
5 case 2:
6 System.out.println("better");
7 break;
8 case 3:
9 System.out.println("best");
10 break;
11 default:
12 System.out.println("invalid");
13 }

(g) Give the output of the following string functions: [2]


(i) “ACHIEVEMENT”.replace(‘E’, ‘A’)
(ii) “DEDICATE”.compareTo(“DEVOTE”)
Ans. i) ACHIAVEMANT
ii) The first two characters are same. So, we take the ASCII values of the third characters and subtract to get
the result.
D – V = 68 – 86 = 18
(h) Consider the following String array and give the output: [2]

1 String arr[] = {"DELHI", "CHENNAI", "MUMBAI", "LUCKNOW", "JAIPUR"};


2 System.out.println(arr[0].length() > arr[3].length());
3 System.out.print(arr[4].substring(0, 3));

Ans.
System.out.println(arr[0].length() > arr[3].length());
arr[0].length() > arr[3].length()
“DELHI”.length() > “LUCKNOW”.length()
5>7
false
Output is false

System.out.print(arr[4].substring(0, 3));
JAIPUR.substring(0, 3)
JAI
Output is JAI

(i) Rewrite the following using ternary operator: [2]

1 if(bill > 10000)


2 discount = bill * 10.0 / 100;
3 else
4 discount = bill * 5.0 / 100;

Ans.

1 discount = bill > 10000 ? (bill * 10.0 / 100) : (bill * 5.0 / 100);

(j) Give the output of the following program segment and also mention how many times the loop is
executed: [2]

1 int i;
2 for(i = 5; i > 10; i++)
3 System.out.println(i);
4 System.out.println(i * 4);

Ans.
Loop condition i > 10 evaluates to 5 > 10 which is false. So, loop is not executed even once
System.out.println(i * 4) prints 5 * 4 = 20

SECTION B (60 Marks)


Attempt any four questions from this Section.
The answers in this section should consist of the programs in either BlueJ environment or any program
environment with Java as the base.
Each program should be written using Variable descriptions/Mneumonic codes so that the logic of the program
is clearly depicted.
Flow-charts and algorithms are not required.

Question 4
Design a class RailwayTicket with the following description:
Instance variables/data members:
String name: to store the name of the customer.
String coach: to store the type of coach customer wants to travel.
long mobno: to store customer’s mobile number.
int amt: to store basic amount of ticket.
int totalamt: to store the amount to be paid after updating the original amount.
Methods:
void accept(): to take input for name, coach, mobile number and amount.
void update(): to update the amount as per the coach selected. Extra amount to be added in the amount as
follows:

Type of coaches Amount


First_AC 700
Second_AC 500
Third_AC 250
sleeper None
void display(): To display all details of a customer such as name, coach, total amount and mobile number.
Write a main() method to create an object of the class and call the above methods.

Ans.

1 import java.util.Scanner;
2
3 public class RailwayTicket {
4 String name;
5 String coach;
6 long mobno;
7 int amt;
8 int totalamt;
9
10 void accept() {
11 Scanner scanner = new Scanner(System.in);
12 System.out.print("Enter name: ");
13 name = scanner.nextLine();
14 System.out.print("Enter coach: ");
15 coach = scanner.nextLine();
16 System.out.print("Enter mobno: ");
17 mobno = scanner.nextLong();
18 System.out.print("Enter amt: ");
19 amt = scanner.nextInt();
20 }
21
22 void update() {
23 if (coach.equals("First_AC")) {
24 totalamt = amt + 700;
25 } else if (coach.equals("Second_AC")) {
26 totalamt = amt + 500;
27 } else if (coach.equals("Third_AC")) {
28 totalamt = amt + 250;
29 } else if (coach.equals("sleeper")) {
30 totalamt = amt;
31 }
32 }
33
34 void display() {
35 System.out.println("Name: " + name);
36 System.out.println("Coach: " + coach);
37 System.out.println("Mobile Number: " + mobno);
38 System.out.println("Amount: " + amt);
39 System.out.println("Total Amount: " + totalamt);
40 }
41
42 void main() {
43 RailwayTicket railwayTicket = new RailwayTicket();
44 railwayTicket.accept();
45 railwayTicket.update();
46 railwayTicket.display();
47 }
48 }

Sample output:

1 Enter name: Nani


2 Enter coach: First_AC
3 Enter mobno: 9999999999
4 Enter amt: 3000
5 Name: Nani
6 Coach: First_AC
7 Mobile Number: 9999999999
8 Amount: 3000
9 Total Amount: 3700

Question 5
Write a program to input a number and check and print whether it is a Pronic number or not. Pronic number is
the number which is the product of two consecutive integers.
Examples:
12 = 3 × 4
20 = 4 × 5
42 = 6 × 7

Ans.

1 import java.util.Scanner;
2
3 public class PronicNumber {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.print("Enter number: ");
7 int number = scanner.nextInt();
8 boolean pronic = false;
9 for (int i = 1; i < number; i++) {
10 int product = i * (i + 1);
11 if (product == number) {
12 pronic = true;
13 }
14 }
15 System.out.println("Pronic number = " + pronic);
16 }
17 }

Sample output

1 Enter number: 42
2 Pronic number = true

Question 6
Write a program in Java to accept a string in lowercase and change the first letter of every word to uppercase.
Display the new string.
Sample INPUT: we are in cyber world
Sample OUTPUT: We Are In Cyber World
Ans.

1 import java.util.Scanner;
2
3 public class SentenceCase {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.print("Enter a sentence: ");
7 String sentence = scanner.nextLine();
8 String output = "";
9 for (int i = 0; i < sentence.length(); i++) {
10 char ch = sentence.charAt(i);
11 if (i == 0 || sentence.charAt(i - 1) == ' ') {
12 output = output + Character.toUpperCase(ch);
13 } else {
14 output = output + ch;
15 }
16 }
17 System.out.println("Output: " + output);
18 }
19 }

Sample output

1 Enter a sentence: we are in cyber world


2 Output: We Are In Cyber World

Question 7
Design a class to overload a function volume() as follows:
(i) double volume(double r) – with radius ‘r’ as an argument, returns the volume of sphere using the formula:
v = 4 / 3 × 22 / 7 × r3
(ii)double volume(double h, double r) – with height ‘h’ and radius ‘r’ as the arguments, returns the volume of a
cylinder using the formula:
v = 22 / 7 × r2 × h
(iii) double volume(double l, double b, double h) – with length ‘l’, breadth ‘b’ and height ‘h’ as the arguments,
returns the volume of a cuboid using the formula:
v=l×b×h

Ans.

1 public class Overload {


2
3 double volume(double r) {
4 double vol = 4.0 / 3 * 22 / 7 * Math.pow(r, 3);
5 return vol;
6 }
7
8 double volume(double h, double r) {
9 double v = 22.0 / 7 * Math.pow(r, 2) * h;
10 return v;
11 }
12
13 double volume(double l, double b, double h) {
14 double v = l * b * h;
15 return v;
16 }
17 }

Question 8
Write a menu-driven program to display the pattern as per user’s choice:

Pattern 1 Pattern 2
ABCDE B
ABCD LL
ABC UUU
AB EEEE
A
For an incorrect option, an appropriate error message should be displayed.

Ans.

1 import java.util.Scanner;
2
3 public class Pattern {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 System.out.print("Enter pattern number: ");
8 int choice = scanner.nextInt();
9 if (choice == 1) {
10 System.out.print("Enter number of lines: ");
11 int n = scanner.nextInt();
12 for (int i = n; i >= 1; i--) {
13 for (int j = 0; j < i; j++) {
14 System.out.print((char) ('A' + j));
15 }
16 System.out.println();
17 }
18 } else if (choice == 2) {
19 System.out.print("Enter string: ");
20 String s = scanner.next();
21 for (int i = 0; i < s.length(); i++) {
22 char ch = s.charAt(i);
23 for (int j = 1; j <= (i + 1); j++) {
24 System.out.print(ch);
25 }
26 System.out.println();
27 }
28 } else {
29 System.out.println("Invalid choice");
30 }
31
32 }
33 }

Sample output 1

1 Enter pattern number: 1


2 Enter number of lines: 5
3 ABCDE
4 ABCD
5 ABC
6 AB
7A

Sample output 2

1 Enter pattern number: 2


2 Enter string: BLUE
3B
4 LL
5 UUU
6 EEEE

Sample output 3

1 Enter pattern number: 3


2 Invalid choice
Question 9
Write a program to accept name and total marks of N number of students in two single subscripts array name[]
and totalmarks[].

Calculate and print:


(i) The average of the total marks obtained by N number of students.
[average = (sum of total marks of all the students) / N]
(ii) Deviation of each student’s total marks with the average.
[deviation = total marks of a student – average]

Ans.

1 import java.util.Scanner;
2
3 public class Student {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.print("Enter number of students: ");
7 int n = scanner.nextInt();
8 String[] name = new String[n];
9 int[] totalmarks = new int[n];
10 for (int i = 0; i < n; i++) {
11 System.out.println("Student " + (i + 1));
12 System.out.print("Enter name: ");
13 name[i] = scanner.next();
14 System.out.print("Enter marks: ");
15 totalmarks[i] = scanner.nextInt();
16 }
17
18 int sum = 0;
19 for (int i = 0; i < n; i++) {
20 sum = sum + totalmarks[i];
21 }
22 double average = (double) sum / n;
23 System.out.println("Average is " + average);
24
25 for (int i = 0; i < n; i++) {
26 double deviation = totalmarks[i] - average;

27 System.out.println("Deviation of " + name[i] + " is " +


deviation);
28 }
29 }
30 }

Sample output

1 Enter number of students: 3


2 Student 1
3 Enter name: Nani
4 Enter marks: 95
5 Student 2
6 Enter name: Kittu
7 Enter marks: 99
8 Student 3
9 Enter name: Bittu
10 Enter marks: 94
11 Average is 96.0
12 Deviation of Nani is -1.0
13 Deviation of Kittu is 3.0
14 Deviation of Bittu is -2.0
ICSE Question Paper – 2017 (Solved)
Computer Applications
Class X

SECTION A (40 Marks)


Answer all questions from this Section

SECTION A (40 MARKS)


Attempt all questions

Question 1:
a) What is Inheritance ? [2]
Ans. Inheritance is the process by which one class extends another class to inherit the variables and functions
and add any additional variables and methods.

b) Name the operators listed below [2]


i) < ii) ++ iii) && iv) ?:
Ans. i) Less than comparison operator
ii) Increment operator
iii) And logical operator
iv) Ternary operator

c) State the number of bytes occupied by char and int data types.[2]
Ans. char occupies two bytes and int occupied 4 bytes.

d) Write one difference between / and % operator. [2]


Ans. / is division operator while % is modulus operator which gives the remainder on dividing two numbers.

e) String x[] = {“SAMSUNG”, “NOKIA”, “SONY” , “MICROMAX”, “BLACKBERRY”};


Give the output of the following statements:
i) System.out.println(x[1]);
ii) System.out.println(x[3].length()); [2]
Ans. i) NOKIA
ii) “MICROMAX”.length() = 8

Question 2:
a) Name of the following: [2]
i) A keyword used to call a package in the program.
ii) Any one reference data types.
Ans. i) import
ii) String

b) What are the two ways of invoking functions? [2]


Ans. Call by value and call by reference

c) State the data type and value of res after the following is executed : [2]

1 char ch = 't';
2 res = Character.toUpperCase(ch);
Ans. Data type of res is char and value is T

d) Give the output of the following program segment and also mention the number of times the loop is
executed: [2]

1 int a,b;
2 for(a=6,b=4;a<=24;a=a+6)
3{
4 if(a%b==0)
5 break;
6}
7 System.out.println(a);

Ans.

Loop initialization: a = 6, b = 4

First iteration:
Condition check: a <= 24 --- 6 <= 24 ---- true
Loop is executed for the first time
Loop execution: a % b = 6 % 4 = 2 != 0 Hence, break is not executed
Loop increment operator: a = 1 + 6 --- a = 6 + 6 = 12

Second iteration:
Condition check: a <= 24 --- 12 <= 24 ---- true
Loop is executed for the second time
Loop execution: a % b = 12 % 4 = 0 = 0 Hence, break is executed
System.out.println(a); --- 12

Output is 12 and loop is executed two times

e) Write the Output: [2]

1 char ch= 'F';


2 int m=ch;
3 m=m+5;
4 System.out.println(m+ " " +ch);

Ans. ch = ‘F’
int m = ch; — ASCII value of ‘F’ i.e. 70 will be assigned to m
m = m + 5 = 70 + 5 = 75
System.out.println(m+ ” ” +ch); — 75 F
Output is
75 F

Question 3:
a) Write a Java expression for the following : [2]
ax5 + bx3 + c
Ans. a * Math.pow(x, 5) + b * Math.pow(x, 3) + c

b) What is the value of x1 if x=5 ? [2]


x1=++x – x++ + –x
Ans. x1=++x – x++ + –x
x1 = 6 (x is incremented to 6) – 6 (x is incremented to 7) + 6 (x is decremented to 6)
=6

c) Why is an object called an instance of a class? [2]


Ans. An object is called an instance of a class as every object created from a class gets its own instances of the
variables defined in the class. Multiple objects can be created from the same class.

d) Convert following do-while loop into for loop. [2]

1 int i=1;
2 int d=5;
3 do{
4 d=d*2
5 System.out.println(d);
6 i++;
7 }while(i<=5);

Ans.

1 for(int i=1, d=5; i<=5; i++) {


2 d = d * 2;
3 System.out.println(d);
4}

e) Differentiate between constructor and function. [2]


Ans. The constructor of a class is invoked automatically during object creation while a function is invoked
manually after object creation.
A constructor is invoked only once while a function can be invoked multiple times.
A constructor has the same name as the class in which it is defined while a function can have any name.

f) Write the output for the following: [2]

1 String s= "Today is Test";


2 System.out.println(s.indexOf('T'));
3 System.out.println(s.substring(0,7)+ " "+ "Holiday");

Ans.
s.indexOf(‘T’) = 0
s.substring(0,7)+ ” “+ “Holiday”
= “Today is Test”.substring(0,7) + ” ” + “Holiday”
= “Today i” + ” ” + “Holiday”
= “Today i Holiday”
Output is
0
Today i Holiday

g) What are the values stored in variables r1 and r2: [2]


i) double r1 = Math.abs(Math.min(-2.83,-5.83));
ii) double r2 = Math.sqrt(Math.floor(16.3));
Ans. i) double r1 = Math.abs(Math.min(-2.83,-5.83));
= Math.abs(-5.83)
= 5.83
ii) double r2 = Math.sqrt(Math.floor(16.3));
= Math.sqrt(16)
= 4.0

h) Give the output of the following code: [2]

1 String A= "26", B= "100" ;


2 String D=A+B+ "200";
3 int x= Integer.parseInt(A);
4 int y=Integer.parseInt(B);
5 int d=x+y;
6 System.out.println("Result 1=" +D);
7 System.out.println("Result 2="+d);

Ans.
String A= “26″, B= “100″ ;
A = “26″, B = “100″

String D=A+B+ “200″;


D = “26″ + “100″ + “200″ = 26100200

int x= Integer.parseInt(A);
x = Integer.parseInt(“26″) = 26

int y=Integer.parseInt(B);
y= Integer.parseInt(B) = Integer.parseInt(“100″); = 100

int d=x+y;
d = 26 + 100 = 126

System.out.println(“Result 1=” +D);


Result 1=26100200

System.out.println(“Result 2=”+d);
Result 2=126

Output is
1 Result 1=26100200
2 Result 2=126

i) Analyze the given program segment and answer the following questions [2]

1 for(int i=3;i<=4;i++)
2{
3 for(int j=2;j<i;j++)
4{
5 System.out.print(" ");
6}
7 System.out.println("WIN");
8}

i) How many times does the inner loop execute ?


ii) Write the output of the program segment.
Ans. The output loop runs twice, with i = 3 and i = 4
When i = 3, the inner loop runs once with j = 2
When i = 4, the inner loop runs twice with j = 2 and j = 3

i) Inner loop executes 3 times


ii)

1 WIN
2 WIN

j) What is the difference between the Scanner class functions next() and nextLine()? [2]
Ans. next() read a single token i.e. all characters from the current position till a whitespace or tab or new line is
encountered.
nextLine() reads an entire line i.e. all characters from the current position till a new line is encountered.

SECTION B (60 Marks)


Attempt any four questions from this Section.
The answers in this section should consist of the programs in either BlueJ environment or any program
environment with Java as the base.
Each program should be written using Variable descriptions/Mneumonic codes so that the logic of the program
is clearly depicted.
Flow-charts and algorithms are not required.

Question 4.
Define a class Electric Bill with the following specifications: [15]
class: ElectricBill
Instance Variable/ data member:
String n – to store the name of the customer
int units – to store the number of units consumed
double bill – to store the amount to paid
Member methods:
Void accept() – to accept the name of the customer and number of units consumed
Void calculate() – to calculate the bill as per the following tariff :
Number of units — Rate per unit
First 100 units — Rs.2.00
Next 200 units — Rs.3.00
Above 300 units — Rs.5.00
A surcharge of 2.5% charged if the number of units consumed is above 300 units.
Void print() – To print the details as follows :
Name of the customer ………
Number of units consumed ……
Bill amount …….
Write a main method to create an object of the class and call the above member methods.

Ans.

1 import java.util.Scanner;
2
3 public class ElectricBill {
4
5 private String n;
6 private int units;
7 private double bill;
8
9 public void accept() {
10 Scanner scanner = new Scanner(System.in);
11 System.out.print("Enter name: ");
12 n = scanner.next();
13 System.out.print("Enter units: ");
14 units = scanner.nextInt();
15 }
16
17 public void calculate() {
18 if (units <= 100) {
19 bill = units * 2;
20 } else if (units > 100 && units <= 300) {
21 bill = 100 * 2 + (units - 100) * 3;
22 } else {
23 bill = 100 * 2 + 200 * 3 + (units - 300) * 5;
24 double surcharge = bill * 2.5 / 100;
25 bill = bill + surcharge;
26 }
27 }
28
29 public void print() {
30 System.out.println("Name of the customer: " + n);
31 System.out.println("Number of units consumed: " + units);
32 System.out.println("Bill amount: " + bill);
33 }
34
35 public static void main(String[] args) {
36 ElectricBill electricBill = new ElectricBill();
37 electricBill.accept();
38 electricBill.calculate();
39 electricBill.print();
40 }
41 }

Sample output

1 Enter name: Sai


2 Enter units: 50
3 Name of the customer: Sai
4 Number of units consumed: 50
5 Bill amount: 100.0

Question 5.

Write a program to accept a number and check and display whether it is a spy number or not. [15]
(A number is spy if the sum its digits equals the product of the digits.)
Example: consider the number 1124 , sum of the digits = 1 + 1 + 2 + 4 = 8
Product of the digits = 1 X 1 X 2 X 4=8

Ans.

1 import java.util.Scanner;
2
3 public class SpyNumber {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.print("Enter number: ");
7 int n = scanner.nextInt();
8
9 int sumOfDigits = 0;
10 int productOfDigits = 1;
11 while (n > 0) {
12 int remainder = n % 10;
13 sumOfDigits = sumOfDigits + remainder;
14 productOfDigits = productOfDigits * remainder;
15 n = n / 10;
16 }
17
18 if (sumOfDigits == productOfDigits) {
19 System.out.println("Spy number");
20 } else {
21 System.out.println("Not a spy number");
22 }
23 }
24 }

Sample output 1

1 Enter number: 1124


2 Spy number

Sample output 2

1 Enter number: 34
2 Not a spy number

Question 6.
Using switch statement, write a menu driven program for the following: [15]
i) To find and display the sum of the series given below:
S = x1 – x2 + x3 – x4 + x5 … – x20
(where x=2)
ii) To display the following series:
1 11 111 1111 11111
For an incorrect option, an appropriate error message should be displayed.

Ans.

1 import java.util.Scanner;
2
3 public class Menu {
4 public static void main(String[] args) {
5 System.out.println("1. Sum of series");
6 System.out.println("2. Display Series");
7 System.out.print("Enter your choice: ");
8 Scanner scanner = new Scanner(System.in);
9 int choice = scanner.nextInt();
10 switch (choice) {
11 case 1:
12 double sum = 0;
13 for (int i = 1; i <= 20; i++) {
14 if (i % 2 == 1) {
15 sum = sum + Math.pow(2, i);
16 } else {
17 sum = sum - Math.pow(2, i);
18 }
19 }
20 System.out.println("Sum = " + sum);
21 break;
22 case 2:
23 for (int i = 1; i <= 5; i++) {
24 for (int j = 1; j <= i; j++) {
25 System.out.print("1");
26 }
27 System.out.print(" ");
28 }
29 break;
30 default:
31 System.out.println("Invalid choice");
32 break;
33 }
34 }
35 }

Sample output 1

1 1. Sum of series
2 2. Display Series
3 Enter your choice: 1
4 Sum = -699050.0

Sample output 2

1 1. Sum of series
2 2. Display Series
3 Enter your choice: 2
4 1 11 111 1111 11111

Sample output 3

1 1. Sum of series
2 2. Display Series
3 Enter your choice: 3
4 Invalid choice

Question 7.
Write a program to input integer elements into an array of size 20 and perform the following operations: [15]
i) Display largest number from the array
ii) Display smallest number from the array
iii) Display sum of all the elements of the array

Ans.

1 import java.util.Scanner;
2
3 public class ArrayOperations {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 int[] numbers = new int[20];
7 System.out.print("Enter 20 numbers: ");
8 for (int i = 0; i < 20; i++) {
9 numbers[i] = scanner.nextInt();
10 }
11
12 int smallest = numbers[0];
13 int largest = numbers[0];
14 int sum = 0;
15 for (int i = 0; i < 20; i++) {
16 if (numbers[i] < smallest) {
17 smallest = numbers[i];
18 }
19 if (numbers[i] > largest) {
20 largest = numbers[i];
21 }
22 sum = sum + numbers[i];
23 }
24 System.out.println("Smallest = " + smallest);
25 System.out.println("Largest = " + largest);
26 System.out.println("Sum = " + sum);
27 }
28 }

Sample output

1 Enter 20 numbers: 3 9 1 50 8 5 2 8 6 9 7 5 4 9 7 9 2 67 2 32
2 Smallest = 1
3 Largest = 67
4 Sum = 245

Question 8:
Design a class to overload a function check() as follows:
i) void check(String str, char ch) – to find and print the frequency of a character
in a string.
Example :
Input — Output
Str = “success” number of s present is=3
ch = ‘s’
ii) void check (String s1) – to display only the vowels from string s1 , after converting it to lower case.
Example :
Input:
S1= “computer” output: o u e
Ans.

1 public class Overload {


2 public void check(String str, char ch) {
3 int result = 0;
4 for (int i = 0; i < str.length(); i++) {
5 char currentChar = str.charAt(i);
6 if (ch == currentChar) {
7 result++;
8 }
9 }
10 System.out.println("number of s present is = " + result);
11 }
12
13 public void check(String s1) {
14 s1 = s1.toLowerCase();
15 for (int i = 0; i < s1.length(); i++) {
16 char currentChar = s1.charAt(i);
17 if (currentChar == 'a' || currentChar == 'e' || currentChar
== 'i' || currentChar == 'o'
18 || currentChar == 'u') {
19 System.out.print(currentChar + " " );
20 }
21 }
22 }
23 }

Question 9:
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.

Ans.

1 import java.util.Scanner;
2
3 public class SelectionSort {
4 public static void main(String[] args) {
5
6 // Accept 40 words
7
8 Scanner scanner = new Scanner(System.in);
9 String[] words = new String[40];
10 System.out.println("Enter 40 words: ");
11 for (int i = 0; i < 40; i++) {
12 words[i] = scanner.nextLine();
13 }
14
15 // Sort using selection sort
16
17 for (int i = 0; i < words.length - 1; i++) {
18 int largestWordIndex = i;
19 for (int j = i + 1; j < words.length; j++) {
20 if (words[j].compareTo(words[largestWordIndex]) > 0) {
21 largestWordIndex = j;
22 }
23 }
24 String temp = words[largestWordIndex];
25 words[largestWordIndex] = words[i];
26 words[i] = temp;
27 }
28
29 // Print sorted array
30
31 for (int i = 0; i < 40; i++) {
32 System.out.println(words[i]);
33 }
34 }
35 }
ICSE Question Paper – 2016 (Solved)
Computer Applications
Class X

SECTION A (40 Marks)


Answer all questions from this Section

Question 1.

(a) Define Encapsulation. [2]


Ans. Encapsulation is the process of bundling state (instance variables) and behaviour
(methods) is a single unit (class).

(b) What are keywords? Give an example. [2]


Ans. Keywords are reserved words which convey special meaning to the compiler. They
cannot be used as identifiers. Ex: class, void

(c) Name any two library packages. [2]


Ans. java.util, java.io

(d) Name the type of error (syntax, runtime or logical error) in each case given below:
[2]
(i) Math.sqrt (36-45)
(ii) int a;b;c;
Ans. (i) Runtime error
Math.sqrt(36-45) = Math.sqrt(-9) which cannot be computed as square root of a negative
number is not defined. Therefor, a runtime error will be thrown.
(ii) Syntax error
Multiple variables can be defined in one of the following ways
int a, b, c;
int a; int b; int c;

(e) If int x[] = { 4, 3, 7, 8, 9, 10 }; what are the values of p and q? [2]


(i) p = x.length
(ii) q = x[2] + x[5] * x[1]
Ans. (i) 6
(ii) q = x[2] + x[5] * x[1]
= 7 + 10 * 3
= 7 * 30
= 37

Question 2.

(a) State the difference between == operator and equals() method. [2]
Ans. == compares if the two objects being compared refer to the instance while equals()
method which can be overridden by classes generally compares if the contents of the
objects are equals.

(b) What are the types of casting shown by the following examples: [2]
(i) char c = (char)120;
(ii) int x = ‘t’;
Ans. (i) Explicit casting
(ii) Implicit casting

(c) Differentiate between formal parameter and actual parameter. [2]


Ans. Format parameters are the parameters defined in the signature of a method. Actual
parameters are the values passed to the methods on function invocation.
Ex: Consider the following code snippet

1 public int add(int a, int b) {


2 return a + b;
3}
4
5 // Method invocation
6 int result = add(3, 4)

a and b are formal parameters while 3 and 4 are actual parameters.

(d) Write a function prototype of the following: [2]


A function PosChar which takes a string argument and a character argument and
returns an integer value.
Ans.

1 public int PosChar(String s, char c)

(e) Name any two types of access specifiers. [2]


Ans. public, private, protected and default/package access specifiers

Question 3.

(a) Give the output of the following string functions : [2]


(i) “MISSISSIPPI”.indexOf(‘S’) + “MISSISSIPPI”.lastIndexOf(‘I’)
(ii) “CABLE”.compareTo(“CADET”)
Ans.
(i) “MISSISSIPPI”.indexOf(‘S’) + “MISSISSIPPI”.lastIndexOf(‘I’)
= 2 + 10
= 12
(ii) String’s compareTo method compares ASCII values of characters starting from the left.
“CABLE”.compareTo(“CADET”)
The first and seconds characters are the same in both the strings. So, we compare the third
characters.
Compare B and D = ASCII value of B – ASCII value of D
= 66 – 68
= -2

(b) Give the output of the following Math functions: [2]


(i) Math.ceil(4.2)
(ii) Math.abs(-4)
Ans. (i) 5.0 (and not 5, as ceil() returns a double)
(ii) 4

(c) What is a parameterized constructor? [2]


Ans. A parameterized constructor is a constructor that accepts arguments which are used
to initialize the object being created.

(d) Write down java expression for : [2]


T = square root (A2 + B2 + C2)
Ans.

1 double T = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2) + Math.pow(c, 2));

(e) Rewrite the following using ternary operator : [2]

1 if(x%2 == 0)
2 System.out.print("EVEN");
3 else
4 System.out.print("ODD");

Ans.

1 System.out.print(x % 2 == 0 ? "EVEN" : "ODD");

(f) Convert the following while loop to the corresponding for loop : [2]

1 int m = 5, n = 10;
2 while (n>=1)
3{
4 System.out.println(m*n);
5 n–-;
6}

Ans.

1 for(int m=5, n=10; n >=1; n--) {


2 System.out.println(m*n);
3}

(g) Write one difference between primitive data types and composite data types. [2]
Ans. A primitive data type is not composed of other data types. Ex: int, float, double while
a composite data type is composed of other data types. Ex: class
(h) Analyze the given program segment and answer the following questions : [2]
(i) Write the output of the program segment
(ii) How many times does the body of the loop gets executed?

1 for(int m=5; m<=20; m+=5)


2{
3 if(m%3 == 0)
4 break;
5 else
6 if(m%5 == 0)
7 System.out.println(m);
8 continue;
9}

Ans.
For loop initialization: m = 5
Loop condition check: m <= 20 = 5 <=20 = true
Loop execution for first time
m%3 == 0
= 5 % 3 == 0
= 2 == 0
= false
else is executed
m%5 == 0
= 5 % 5 == 0
= 0 == 0
= true
5 is printed
Loop increment statement is executed: m+=5 = m = m + 5 = 5 + 5 = 10
Loop condition check: m <= 20 = 10 <=20 = true
Loop body is executed second time and 10 is printed
Loop increment statement is executed: m+=5 = m = m + 5 = 10 + 5 = 15
Loop condition check: m <= 20 = 15 <=20 = true
Loop body is executed third time

m%3 == 0
= 15 % 3 == 0
= 0 == 0
= true
break statement is executed and loop terminates

(i) 5
10
(ii) 3 times

(i) Give the output of the following expression : [2]


a+=a++ + ++a + -–a + a-– ; when a = 7
Ans.
a+=a++ + ++a + –-a + a–- ;
a = 7 + (a++ + ++a + -–a + a–-);
a = 7 + (7 + 9 + 8 + 8);
a = 39

(j) Write the return type of the following library functions : [2]
(i) isLetterOrDigit(char)
(ii) replace(char,char)
Ans. (i) boolean
(ii) String

SECTION B (60 Marks)


Attempt any four questions from this Section.
The answers in this section should consist of the programs in either BlueJ environment or
any program environment with Java as the base.
Each program should be written using Variable descriptions/Mneumonic codes so that the
logic of the program is clearly depicted.
Flow-charts and algorithms are not required.

Question 4.
Define a class named BookFair with the following description: [15]

Instance variables/Data members:


String Bname – stores the name of the book.
double price – stores the price of the book.

Member Methods:
(i) BookFair() – Default constructor to initialize data members.
(ii) void Input() – To input and store the name and the price of the book.
(iii) void calculate() – To calculate the price after discount. Discount is calculated based on
the following criteria.

PRICE DISCOUNT

Less than or equal to Rs 1000 2% of price

More than Rs 1000 and less than or equal to Rs 3000 10% of price

More than Rs 3000 15% of price

(iv) void display() – To display the name and price of the book after discount.

Write a main method to create an object of the class and call the above member methods.

Ans.

1 import java.util.Scanner;
2
3 public class BookFair {
4 private String Bname;
5 private double price;
6
7 public BookFair() {
8 Bname = null;
9 price = 0.0;
10 }
11
12 public void Input() {
13 Scanner scanner = new Scanner(System.in);
14 System.out.print("Enter book name: ");
15 Bname = scanner.nextLine();
16 System.out.print("Enter price: ");
17 price = scanner.nextDouble();
18 }
19
20 public void calculate() {
21 double discountPercentage = 0;
22 if (price <= 1000) {
23 discountPercentage = 2;
24 } else if (price > 1000 && price <= 3000) {
25 discountPercentage = 10;
26 } else if (price > 3000) {
27 discountPercentage = 15;
28 }
29 price = price - (price * discountPercentage / 100);
30 }
31
32 public void display() {
33 System.out.println("Name: " + Bname);
34 System.out.println("Price after discount: " + price);
35 }
36
37 public static void main(String[] args) {
38 BookFair bookFair = new BookFair();
39 bookFair.Input();
40 bookFair.calculate();
41 bookFair.display();
42 }
43 }

Sample output

1 Enter book name: How to Java


2 Enter price: 2500
3 Name: How to Java
4 Price after discount: 2250.0

Question 5.

Using the switch statement, write a menu driven program for the following: [15]

(i) To print the Floyd’s triangle [Given below]

1
23
456
7 8 9 10
11 12 13 14 15

(ii) To display the following pattern

I
IC
ICS
ICSE

For an incorrect option, an appropriate error message should be displayed.

Ans.

1 import java.util.Scanner;
2
3 public class Menu {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.println("1. Floyd's triangle");
7 System.out.println("2. ICSE Pattern");
8 System.out.print("Enter your choice: ");
9 int choice = scanner.nextInt();
10 switch (choice) {
11 case 1:
12 System.out.print("Enter n (number of lines): ");
13 int n = scanner.nextInt();
14 int currentNumber = 1;
15 for (int i = 1; i <= n; i++) {
16 for (int j = 1; j <= i; j++) {
17 System.out.print(currentNumber + " ");
18 currentNumber++;
19 }
20 System.out.println();
21 }
22 break;
23 case 2:
24 System.out.print("Enter word: ");
25 String word = scanner.next();
26 for (int i = 0; i < word.length(); i++) {
27 for (int j = 0; j <= i; j++) {
28 System.out.print(word.charAt(j) + " ");
29 }
30 System.out.println();
31 }
32 break;
33 default:
34 System.out.println("Invalid choice");
35 break;
36 }
37 }
38 }

Sample output 1

1 1. Floyd's triangle
2 2. ICSE Pattern
3 Enter your choice: 1
4 Enter n (number of lines): 5
51
62 3
74 5 6
8 7 8 9 10
9 11 12 13 14 15

Sample output 2

1 1. Floyd's triangle
2 2. ICSE Pattern
3 Enter your choice: 2
4 Enter word: ICSE
5I
6I C
7I C S
8I C S E

Sample output 3

1 1. Floyd's triangle
2 2. ICSE Pattern
3 Enter your choice: 3
4 Invalid choice

Question 6.
Special words are those words which starts and ends with the same letter. [15]
Examples:
EXISTENCE
COMIC
WINDOW

Palindrome words are those words which read the same from left to right and vice-versa.
Example:
MALAYALAM
MADAM
LEVEL
ROTATOR
CIVIC

All palindromes are special words, but all special words are not palindromes.

Write a program to accept a word check and print whether the word is a palindrome or only
special word.

Ans.

1 import java.util.Scanner;
2
3 public class Words {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 System.out.print("Enter word: ");
8 String word = scanner.next();
9
10 // Check if word is palindrome
11 String reverse = "";
12 for (int i = word.length() - 1; i >= 0; i--) {
13 reverse = reverse + word.charAt(i);
14 }
15 if (word.equals(reverse)) {
16 System.out.println("Palindrome");
17 }
18
19 // Check if word is a special word
20 char firstLetter = word.charAt(0);
21 char lastLetter = word.charAt(word.length() - 1);
22 if (firstLetter == lastLetter) {
23 System.out.println("Special word");
24 }
25 }
26 }

Sample output 1

1 Enter word: MALAYALAM


2 Palindrome
3 Special word

Sample output 2

1 Enter word: COMIC


2 Special word

Question 7:
Design a class to overload a function SumSeries() as follows: [15]
(i) void SumSeries(int n, double x) – with one integer argument and one double argument
to find and display the sum of the series given below:
s = (x/1) – (x/2) + (x/3) – (x/4) + (x/5) … to n terms
(ii) void SumSeries() – To find and display the sum of the following series:
s = 1 + (1 X 2) + (1 X 2 X 3) + … + (1 X 2 X 3 X 4 X … 20)

Ans.

1 public class Series {


2
3 public void SumSeries(int n, double x) {
4 double sum = 0;
5 for (int i = 1; i <= n; i++) {
6 if (i % 2 == 1) {
7 sum = sum + (x / i);
8 } else {
9 sum = sum - (x / i);
10 }
11 }
12 System.out.println("Sum = " + sum);
13 }
14
15 public void SumSeries() {
16 int sum = 0;
17 for (int i = 1; i <= 20; i++) {
18 int product = 1;
19 for (int j = 1; j <= i; j++) {
20 product = product * j;
21 }
22 sum = sum + product;
23 }
24 System.out.println("Sum = " + sum);
25 }
26 }

Question 8:
Write a program to accept a number and check and display whether it is a Niven number of
not. [15]
(Niven number is that number which is divisible by its sum of digits).
Example:
Consider the number 126.
Sum of its digits is 1 + 2 + 6 = 9 and 126 is divisible by 9.

Ans.

1 import java.util.Scanner;
2
3 public class NivenNumber {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.print("Enter a number: ");
7 int number = scanner.nextInt();
8
9 int sumOfDigits = 0;
10 int copyOfNum = number;
11 while (number > 0) {
12 int remainder = number % 10;
13 number = number / 10;
14 sumOfDigits = sumOfDigits + remainder;
15 }
16
17 if (copyOfNum % sumOfDigits == 0) {
18 System.out.println("Niven number");
19 } else {
20 System.out.println("Not a niven number");
21 }
22
23 }
24 }

Sample output 1

1 Enter a number: 126


2 Niven number

Sample output 2

1 Enter a number: 34
2 Not a niven number

Question 9:
Write a program to initialize the seven Wonders of the World along with their locations in
two different arrays. Search for a name of the country input by the user. If found, display
the name of the country along with its Wonder, otherwise display “Sorry Not Found!” [15]
Seven wonders – CHICHEN ITZA, CHRIST THE RDEEEMER, TAJMAHAL, GREAT WALL OF
CHINA, MACHU PICCHU, PETRA, COLOSSEUM
Locations – MEXICO, BRAZIL, INDIA, CHINA, PERU, JORDAN, ITALY
Example – Country Name: INDIA Output: INDIA – TAJMAHAL
Country Name: USA Output: Sorry Not Found!

Ans.

1 import java.util.Scanner;
2
3 public class SevenWonders {
4 public static void main(String[] args) {
String[] sevenWonders = { "CHICHEN ITZA", "CHRIST THE
5
RDEEEMER", "TAJMAHAL", "GREAT WALL OF CHINA",
6 "MACHU PICCHU", "PETRA", "COLOSSEUM" };
String[] locations =
7
{ "MEXICO", "BRAZIL", "INDIA", "CHINA", "PERU", "JORDAN", "ITALY" };
8
9 Scanner scanner = new Scanner(System.in);
10 System.out.print("Enter country: ");
11 String country = scanner.next();
12
13 // Search country in the array using linear search
14 int index = -1;
15 for (int i = 0; i < locations.length; i++) {
16 if (locations[i].equals(country)) {
17 index = i;
18 }
19 }
20
21 if (index != -1) {

22 System.out.println(locations[index] + " - " +


sevenWonders[index]);
23 } else {
24 System.out.println("Sorry Not Found!");
25 }
26
27 }
28 }

Sample output 1

1 Enter country: INDIA


2 INDIA - TAJMAHAL

Sample output 2

1 Enter country: USA


2 Sorry Not Found!
ICSE Question Paper – 2015 (Solved)
Computer Applications
Class X

SECTION A (40 Marks)


Answer all questions from this Section

Question 1.

(a) What are the default values of the primitive datatypes int and float? [2]
Ans. The default value of int is 0 and the default value of float is 0.0f.

(b) Name any two OOP’s principles. [2]


Ans. The OOPs principles are

 Encapsulation
 Abstraction
 Polymorphism
 Inheritance

(c) What are identifiers? [2]


Ans. Identifiers are names of variables, classes, packages, methods and packages in a java
program.

(d) Identify the literals listed below: [2]


(i) 0.5 (ii)’A’ (iii) false (iv) “a”
Ans. (i) Floating point literal
(ii) Character literal
(iii) Boolean literal
(iv) String literal

(e) Name the wrapper class of char type and boolean type. [2]
Ans. The wrapper class of char type is Character and the wrapper type of boolean type is
Boolean.

Question 2
(a) Evaluate the value of n if the value of p=5, q=19 [2]

1 int n = (q-p) > (p-q) ? (q-p) : (p-q);

Ans.

1 int n = (19-5) > (5-19) ? (19-5) : (5-19)


2 int n = 14 > -14 ? 14 : -14
3 int n = true ? 14 : -14
4 int n = 14
(b) Arrange the following primitive data types in an ascending order of their size: [2]
(i) char (ii) byte (iii) double (iv) int
Ans. The sizes of the given data types are as follows
char = 2 bytes
byte = 1 byte
double = 8 bytes
int = 4 bytes
Arranging them in ascending order gives byte < char < int < double

(c) What is the value stored in variable res given below: [2]

1 double res = Math.pow("345".indexOf('5'), 3);

Ans.

1 double res = Math.pow("345".indexOf('5'), 3);


2 = Math.pow(2, 3);
3 = 8.0

Answer is 8.0 instead of 8 as Math.pow returns a double and not an int.

(d) Name the two types of constructors. [2]


Ans. Default constructor and parameterized constructor.

(e) What are the values of a and b after the following function is executed, if the
values passed are 30 and 50 : [2]

1 void paws(int a, int b) {


2 a = a + b;
3 b = a - b;
4 a = a - b;
5 System.out.println(a + " , " + b);
6}

Ans.
q = 30, b = 50
a = a + b = 20 + 50 = 80
a = 80, b = 50
b = a – b = 80 – 50 = 30
a = 80, b = 30
a = a – b = 80 – 30 = 50
1 = 50, b = 30
System.out.println(a + ” , ” + b) will print
30 , 50

Question 3
(a) State the data type and the value of y after the following is executed : [2]
1 char x = '7';
2 y = Character.isLetter(x);

Ans. Data type of y will be boolean and value will be false.

(b) What is the function of catch block in exception handling? Where does it appear in
a program? [2]
Ans. catch batch catches the specified exception type and handles the same. It appears
between try and finally block. Ex: In the following snippet, if code1 throws an Exception,
code 2 will be executed.

1 try {
2 // code 1
3 } catch (Exception e) {
4 // code 2
5 } finally {
6 // code 3
7}

(c) State the output of the following program segment is executed: [2]

1 String a = "Smartphone", b = "Graphic Art";


2 String h = a.substring(2, 5);
3 String k = b.substring(8).toUpperCase();
4 System.out.println(h);
5 System.out.println(k.equalsIgnoreCase(h));

Ans.
String a = “Smartphone”, b = “Graphic Art”;

String h = a.substring(2, 5);


= “Smartphone”.substring(2, 5);
= art

String k = b.substring(8).toUpperCase();
= “Graphic Art”.substring(8).toUpperCase();
= Art.tpUpperCase()
= ART

System.out.println(h);
art

System.out.println(k.equalsIgnoreCase(h));
“ART”.equalsIgnoreCase(“art”)
true
The output will be
art
true

(d) The access specifier that gives most accessibility is __________ and the least
accessibility is ___________ [2]
Ans. public, private

(e) (i) Name the mathematical function which is used to find sine of an angle given in
radians
(ii) Name a string function which removes the blank spaces provided in the prefix and
suffix of a string [2]
Ans. (i) Math.sin()
(ii) trim()

(f) (i)What will the code print? [2]

1 int arr[] = new int [5];


2 System.out.println(arr);

(i) 0 (ii) value stored in arr[0] (iii) 0000 (iv) garbage value
Ans. (iv)garbage value – A random string will be printed. arr is an object. When an object is
printed, the .toString() method is invoked which gives the hashcode of the object which will
be a random value.

(ii) Name the keyword which is used to resolve the conflict between method
parameter and instance variables/fields
Ans. this keyword
Example

1 public class Main {


2
3 private int a = 10;
4
5 public void test(int a) {
6 System.out.println(a); // Will print the value passed to test() method
7 System.out.println(this.a); // Will print 10
8 }
9
10 }

(g) State the package that contains the class : [2]


(i) BufferedReader
(ii) Scanner
Ans. (i) java.io
(ii) java.util
(h) Write the output of the following code segment: [2]

1 char ch;
2 int x = 97;
3 do {
4 ch = (char) x;
5 System.out.print(ch + " ");
6 if (x % 10 == 0)
7 break;
8 ++x;
9 } while (x <= 100);

Ans. The do-while loop runs for values of x from 97 to 100 and prints the corresponding
char values.
97 is the ASCII value for a, 98 is the ASCII value for 99…
So, the output will be
abcd

(i) Write the Java expression for: a2+b2 /2ab [2]


Ans. (Math.pow(a, 2) + Math.pow(b, 2)) / (2 * a * b)

(j) If int y = 10 then find int z = (++y * (y++ + 5)); [2]


Ans. Increment operator has the highest precedence. So, ++y and y++ will be evaluated
starting from left.
In ++y, the value of y will be incremented to 11 and then 11 will be used in the expression.
When y++ is evaluated, the current value of y i.e. 11 will be used and then y will be
incremented from 11 to 12.

int z = (++y * (y++ + 5));


= 11 * (11 + 5 )
= 11 * 16
= 176

SECTION B (60 Marks)


Attempt any four questions from this Section.
The answers in this section should consist of the programs in either BlueJ environment or
any program environment with Java as the base.
Each program should be written using Variable descriptions/Mneumonic codes so that the
logic of the program is clearly depicted.
Flow-charts and algorithms are not required.

Question 4.

Define a class ParkingLot with the following description:


Instance variables/data members:
int vno – To store the vehicle number
int hours – To store the number of hours the vehicle is parked in the parking lot
double bill – To store the bill amount
Member methods:
void input() – To input and store vno and hours
void calculate() – To compute the parking charge at the rate of Rs.3 for the first hour or
part thereof, and Rs.1.50 for each additional hour or part thereof.
void display() – To display the detail
Write a main method to create an object of the class and call the above methods [15]

Ans.

1 import java.util.Scanner;
2
3 public class ParkingLot {
4 private int vno;
5 private int hours;
6 private double bill;
7
8 public void input() {
9 Scanner scanner = new Scanner(System.in);
10 System.out.print("Enter vehicle number: ");
11 vno = scanner.nextInt();
12 System.out.print("Enter hours: ");
13 hours = scanner.nextInt();
14 }
15
16 public void calculate() {
17 bill = 3 + (hours - 1) * 1.50;
18 }
19
20 public void display() {
21 System.out.println("Vehicle number: " + vno);
22 System.out.println("Hours: " + hours);
23 System.out.println("Bill: Rs. " + bill);
24 }
25
26 public static void main(String[] args) {
27 ParkingLot parkingLot = new ParkingLot();
28 parkingLot.input();
29 parkingLot.calculate();
30 parkingLot.display();
31 }
32 }

Sample Output

1 Enter vehicle number: 34


2 Enter hours: 4
3 Vehicle number: 34
4 Hours: 4
5 Bill: Rs. 7.5

Question 5

Write two separate programs to generate the following patterns using iteration(loop)
statements: [15]
(a)

1*
2* #
3* # *
4* # * #
5* # * # *

(b)
[/code]
54321
5432
543
54
5
[/code]

Ans.
(a)

1 import java.util.Scanner;
2
3 public class Pattern1 {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 System.out.print("Enter n: ");
8 int n = scanner.nextInt();
9 for (int i = 1; i <= n; i++) {
10 for (int j = 1; j <= i; j++) {
11 if (j % n == 1) {
12 System.out.print("* ");
13 } else {
14 System.out.print("# ");
15 }
16 }
17 System.out.println();
18 }
19 }
20 }

Sample output:

1 Enter n: 5
2*
3* #
4* # #
5* # # #
6* # # # #

(b)

1 import java.util.Scanner;
2
3 public class Pattern2 {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 System.out.print("Enter n: ");
8 int n = scanner.nextInt();
9 for (int i = n; i >= 1; i--) {
10 int num = n;
11 for (int j = 1; j <= i; j++) {
12 System.out.print(num + " ");
13 num--;
14 }
15 System.out.println();
16 }
17 }
18 }
Sample output

1 Enter n: 5
25 4 3 2 1
35 4 3 2
45 4 3
55 4
65

Question 6

Write a program in to input and store all roll numbers, names and marks in 3 subjects of n
number of students in five single dimensional arrays and display the remark based on
average marks as given below: [15]

Average marks = total marks/3

AVERAGE MARKS REMARK

85 – 100 EXCELLENT

75 – 84 DISTINCTION

60 – 74 FIRST CLASS

40 – 59 PASS

Less than 40 POOR

Ans.

1 import java.util.Scanner;
2
3 public class Marks {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.print("Enter number of students: ");
7 int n = scanner.nextInt();
8
9 int[] rollNumbers = new int[n];
10 String[] names = new String[n];
11 int[] subject1Marks = new int[n];
12 int[] subject2Marks = new int[n];
13 int[] subject3Marks = new int[n];
14
15 for (int i = 0; i < n; i++) {
16 System.out.println("Student " + (i + 1));
17 System.out.print("Enter roll number: ");
18 rollNumbers[i] = scanner.nextInt();
19 System.out.print("Enter name: ");
scanner.nextLine(); // To consume the new line produced on
20
hitting
21 // enter after entering roll number
22 names[i] = scanner.nextLine();
23 System.out.print("Enter marks in subject 1: ");
24 subject1Marks[i] = scanner.nextInt();
25 System.out.print("Enter marks in subject 2: ");
26 subject2Marks[i] = scanner.nextInt();
27 System.out.print("Enter marks in subject 3: ");
28 subject3Marks[i] = scanner.nextInt();
29 }
30
31 for (int i = 0; i < n; i++) {
System.out.println("Roll number = " + rollNumbers[i] + ", Name
32
= " + names[i]);

33 int averageMarks = (subject1Marks[i] + subject2Marks[i] +


subject3Marks[i]) / 3;
34 if (averageMarks >= 85 && averageMarks <= 100) {
35 System.out.println("EXCELLENT");
36 } else if (averageMarks >= 75 && averageMarks <= 84) {
37 System.out.println("DISTINCTION");
38 } else if (averageMarks >= 60 && averageMarks <= 74) {
39 System.out.println("FIRST CLASS");
40 } else if (averageMarks >= 40 && averageMarks <= 59) {
41 System.out.println("PASS");
42 } else if (averageMarks < 40) {
43 System.out.println("POOR");
44 }
45 }
46 }
47 }
Sample output

1 Enter number of students: 2


2 Student 1
3 Enter roll number: 1
4 Enter name: Kittu
5 Enter marks in subject 1: 90
6 Enter marks in subject 2: 100
7 Enter marks in subject 3: 95
8 Student 2
9 Enter roll number: 2
10 Enter name: Bittu
11 Enter marks in subject 1: 90
12 Enter marks in subject 2: 85
13 Enter marks in subject 3: 100
14 Roll number = 1, Name = Kittu
15 EXCELLENT
16 Roll number = 2, Name = Bittu
17 EXCELLENT

Question 7

Design a class to overload a function Joystring() as follows: [15]


(i) void Joystring(String s, char ch1, char ch2) with one string and two character arguments
that replaces the character argument ch1 with the character argument ch2 in the given
string s and prints the new string
Example:
Input value of s = "TECHNALAGY"
ch1 = 'A'
ch2 = 'O'
Output : "TECHNOLOGY"

(ii) void Joystring(String s) with one string argument that prints the position of the first
space and the last space of the given String s.
Example:
Input value of = "Cloud computing means Internet based computing"
First Index : 5
Last Index : 36

(iii) void Joystring(String s1, String s2) with two string arguments that combines the two
strings with a space between them and prints the resultant string
Example :
Input value of s1 = "COMMON WEALTH"
s2 = "GAMES"
Output : "COMMON WEALTH GAMES"
(use library functions)
Ans.

1 import java.util.Scanner;
2
3 public class StringOperations {
4 public void Joystring(String s, char ch1, char ch2) {
5 String output = s.replace(ch1, ch2);
6 System.out.println("Output = " + output);
7 }
8
9 public void Joystring(String s) {
10 int firstIndexOfSpace = s.indexOf(' ');
11 int lastIndexOfSpace = s.lastIndexOf(' ');
12 System.out.println("First index of space = " + firstIndexOfSpace);
13 System.out.println("Last index of space = " + lastIndexOfSpace);
14 }
15
16 public void Joystring(String s1, String s2) {
17 String output = s1.concat(" ").concat(s2);
18 System.out.println("Output = " + output);
19 }
20
21 public static void main(String[] args) {
22 Scanner scanner = new Scanner(System.in);
23 StringOperations stringOperations = new StringOperations();
24
25 // Joystring method 1
26 System.out.print("Enter string: ");
27 String s1 = scanner.nextLine();
28 System.out.print("Enter ch1: ");
29 char ch1 = scanner.nextLine().charAt(0);
30 System.out.print("Enter ch2: ");
31 char ch2 = (char) scanner.nextLine().charAt(0);
32 stringOperations.Joystring(s1, ch1, ch2);
33
34 // Joystring method 2
35 System.out.print("Enter string: ");
36 String s2 = scanner.nextLine();
37 stringOperations.Joystring(s2);
38
39 // Joystring method 3
40 System.out.print("Enter s1: ");
41 String s3 = scanner.nextLine();
42 System.out.print("Enter s2: ");
43 String s4 = scanner.nextLine();
44 stringOperations.Joystring(s3, s4);
45 }
46 }

Sample output

1 Enter string: TECHNALAGY


2 Enter ch1: A
3 Enter ch2: O
4 Output = TECHNOLOGY
5 Enter string: Cloud computing means Internet based computing
6 First index of space = 5
7 Last index of space = 36
8 Enter s1: COMMON WEALTH
9 Enter s2: GAMES
10 Output = COMMON WEALTH GAMES

Question 8

Write a program to input twenty names in an array. Arrange these names in descending
order of alphabets , using the bubble sort technique. [15]

Ans.

1 import java.util.Scanner;
2
3 public class SortNames {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 String[] names = new String[20];
7
8 // Accept names
9 System.out.println("Enter 20 names");
10 for (int i = 0; i < 20; i++) {
11 names[i] = scanner.nextLine();
12 }
13
14 // Sort names using bubble sort
15 for (int i = 0; i < names.length; i++) {
16 for (int j = 1; j < (names.length - i); j++) {
17 if (names[j - 1].compareTo(names[j]) > 0) {
18 String temp = names[j - 1];
19 names[j - 1] = names[j];
20 names[j] = temp;
21 }
22 }
23 }
24
25 // Print names
26 System.out.println("Sorted names: ");
27 for (int i = 0; i < names.length; i++) {
28 System.out.println(names[i]);
29 }
30
31 }
32 }

Sample output

1 Enter 20 names
2 Ram
3 Arjun
4 Tarun
5 Karthik
6 Sweety
7 Shalini
8 Priya
9 Archana
10 Shweta
11 Shiva
12 Sita
13 Krishna
14 Savitri
15 Hema
16 Siddharth
17 Nani
18 Sachin
19 Kittu
20 Bittu
21 Akhil
22 Sorted names:
23 Akhil
24 Archana
25 Arjun
26 Bittu
27 Hema
28 Karthik
29 Kittu
30 Krishna
31 Nani
32 Priya
33 Ram
34 Sachin
35 Savitri
36 Shalini
37 Shiva
38 Shweta
39 Siddharth
40 Sita
41 Sweety
42 Tarun

Question 9

Use switch statement,write a menu driven program to: [15]

(i) To find and display all the factors of a number input by the user (including 1 and
excluding number itself.)
Example :
Sample Input : n = 15.
Sample Output : 1, 3, 5

(ii) To find and display the factorial of a number input by the user. The factorial of a non-
negative integer n ,denoted by n!,is the product of all integers less than or equal to n.
Example :
Sample Input : n = 5
Sample Output : 120.

For an incorrect choice, an appropriate error message should be displayed.

Ans.

1 import java.util.Scanner;
2
3 public class Menu {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6
7 System.out.println("1. Factors");
8 System.out.println("2. Factorial");
9 System.out.print("Enter your choice: ");
10
11 int choice = scanner.nextInt();
12
13 switch (choice) {
14 case 1:
15 System.out.print("Enter n: ");
16 int n = scanner.nextInt();
17 for (int i = 1; i < n; i++) {
18 if (n % i == 0) {
19 System.out.println(i);
20 }
21 }
22 break;
23 case 2:
24 System.out.print("Enter n: ");
25 n = scanner.nextInt();
26 int factorial = 1;
27
28 for (int i = 1; i <= n; i++) {
29 factorial = factorial * i;
30 }
31 System.out.println("Factorial: " + factorial);
32 break;
33 default:
34 System.out.println("Invalid choice");
35 break;
36 }
37
38 }
39 }
Sample output 1

1 1. Factors
2 2. Factorial
3 Enter your choice: 1
4 Enter n: 15
51
63
75

Sample output 2

1 1. Factors
2 2. Factorial
3 Enter your choice: 2
4 Enter n: 5
5 Factorial: 120

Sample output 3

1 1. Factors
2 2. Factorial
3 Enter your choice: 3
4 Invalid choice
ICSE Question Paper – 2014 (Solved)
Computer Applications
Class X

SECTION A (40 Marks)


Answer all questions from this Section

Question 1.

(a) Which of the following are valid comments? [2]


(i) /* comment */
(ii) /*comment
(iii) //comment
(iv) */ comment */

Ans. (i) and (iii) are valid comments. (i) is a multi line comment and (iii) is a single line
comment.

(b) What is meant by a package? Name any two Java Application Programming
Interface packages. [2]
Ans. Related classes are grouped together as a package. A package provides namespace
management and access protection.
Some of the Java API packages – java.lang, java,util and java,io

(c) Name the primitive data type in Java that is:


(i) a 64-bit integer and is used when you need a range of values wider than those
provided by int.
(ii) a single 16-bit Unicode character whose default value is ‘\u0000′ [2]
Ans. (i) long
(ii) char

(d) State one difference between floating point literals float and double. [2]
Ans. (i) Float requires 4 bytes of storage while double requires 8 bytes.
(ii) Float is of single precision while double is of double precision.

(e) Find the errors in the given program segment and re-write the statements correctly
to assign values to an integer array. [2]

1 int a = new int( 5 );


2 for( int i=0; i<=5; i++ ) a[i]=i;

Ans. The corrected program segment is

1 int a = new int[5];


2 for( int i=0; i<=4; i++ ) a[i]=i;

Error 1: The size of an array is specified using square brackets [] and not parentheses ().
Error 2: Since the array is of length 5, the indices range from 0 to 4. The loop variable i is
used as an index to the array and in the given program segment, it takes values from 0 to
5. a[4] would result in an ArrayIndexOutOfBoundsException. Therefore, the loop condition
should be changed to i<=4. The given program segment creates an array of size 5 and
stores numbers from 0 to 4 in the array.

Question 2.

(a) Operators with higher precedence are evaluated before operators with relatively
lower precedence. Arrange the operators given below in order of higher precedence to
lower precedence. [2] (i) && (ii) % (iii) >= (iv) ++
Ans. ++ , % , >= , &&

(b) Identify the statements listed below as assignment, increment, method invocation
or object creation statements. [2]
(i) System.out.println(“Java”);
(ii) costPrice = 457.50;
(iii) Car hybrid = new Car();
(iv) petrolPrice++;
Ans. (i) Method Invocation – println() is a method of System.out.
(ii) Assignment – The value 457.70 is being assigned to the variable costPrice.
(iii) Object Creation – An object of type Car is created and stored in the variable hybrid.
(iv) Increment – The variable petrolPrice is incremented.

(c) Give two differences between switch statement and if-else statement. [2]
Ans. (i) Switch statement can be used to test only for equality of a particular variable with a
given set of values while an if-else statement can be used for testing arbitrary boolean
expressions.
(ii) If else can handle only primitive types and String while if-else can handle all data types.

(d) What is an infinite loop? Write an infinite loop statement. [2]


Ans. An infinite loop is a loop whose body executes continuously.

Infinite Loop using while:

1 while(true) {
2}

Infinite Loop using for

1 for( ; ;){
2}

Infinite loop using do-while

1 do {
2 } while(true);
(e) What is a constructor? When is it invoked? [2]
Ans. A constructor is a member function of a class used to perform initialization of the
object. It is invoked during object creation.

Question 3.

(a) List the variables from those given below that are composite data types. [2]
(i) static int x;
(ii) arr[i] = 10;
(iii) obj.display();
(iv) boolean b;
(v) private char chr;
(vi) String str;
Ans. The primitive data types in Java are byte, short, int, long, float, double, boolean and
char. All other data types – arrays, objects and interfaces – are composite data types.
(i) x is of a primitive data type
(ii) arr is variable of a composite data type of type int. i can be a variable of a primitive data
type (byte, short or int) or of a composite data type (Byte, Short, Integer)
(iii) obj is a variable of a composite data type
(iv) b is a variable of a primitive data type
(v) chr is a variable of a primitive data type
(vi) str is a variable of a composite data type – String which is of class type

(b) State the output of the following program segment: [2]

1 String str1 = "great"; String str2 = "minds";


2 System.out.println(strl.substring(0,2).concat(str2.substring(l)));
3 System.out.println(("WH" + (strl.substring(2).toUpperCase())));

Ans. Output is

1 grinds
2 WHEAT

Explanation for first print statement:


strl.substring(0,2) gives “gr”
str2.substring(l) “inds”
The two on concatenation gives “grinds”
Explanation for second print statement
strl.substring(2) gives “eat”
“eat” on conversion to upper case using the function toUpperCase() results in EAT
“WH” on concatenation with “EAT” using + gives “WHEAT”

(c) What are the final values stored in variables x and y below? [2]

1 double a = - 6.35;
2 double b = 14.74;
3 double x = Math.abs(Math.ceil(a));
4 double y = Math.rint(Math.max(a,b));

Ans. Math.ceil() gives the smallest of all those integers that are greater than the input. So,
Math.ceil(-6.35) gives -6.0 (not -6 as ceil returns a double value). Math.abs() gives the
absolute value of the number i.e. removes negative sign, if present. So, Math.abs(-6.0)
results in 6.0. So, x will be 6.0.

Math.max(-6.35, 14.74) returns 14.74. rint() returns the double value which is closest in
value to the argument passed and is equal to an integer. So, Math.rint(14.74) returns 15.0.
So, y will hold 15.0.

(d) Rewrite the following program segment using the if-else statements instead of the
ternary operator. [2]

1 String grade = (mark >= 90) ? "A" : (mark >= 80) ? "B" : "C";

Ans.

1 String grade;
2 if(marks >= 90) {
3 grade = "A";
4 } else if( marks >= 80 ) {
5 grade = "B";
6 } else {
7 grade = "C";
8}

(e) Give output of the following method: [2]

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


2 int a = 5;
3 a++;
4 System.out.println(a);
5 a -= (a--) - (--a);
6 System.out.println(a); }

Ans.

16
24

a++ increments a from 5 to 6. The first print statement prints the value of a which is 6.
a -= (a–) – (–a);
is equivalent to
a = a – ( (a–) – (–a) )
a=6–(6–4)
a=6–2
a=4

(f) What is the data type returned by the library functions: [2]
(i) compareTo()
(ii) equals()
Ans. (i) int
(ii) boolean

(g) State the value of characteristic and mantissa when the following code is executed.
[2]

1 String s = "4.3756";
2 int n = s.indexOf('.');
3 int characteristic = Integer.parseInt(s.substring(0,n));
4 int mantissa = Integer.valueOf(s.substring(n+1));

Ans. n = 1
characteristic = Integer.parseInt(s.substring(0,n)) =
Integer.parseInt(“4.3756″.substring(0,1)) = Integer.parseInt(“4″) = 4
characteristic = 4
mantissa = Integer.valueOf(“4.3756″.substring(1+1)) = Integer.valueOf(“3756″) = 3756
mantissa = 3756

(h) Study the method and answer the given questions. [2]

1 public void sampleMethod()


2 { for( int i=0; i<3; i++ )
3 { for( int j=0; j<2; j++)
4 { int number = (int)(Math.random() * 10);
5 System.out.println(number); } } }

(i) How many times does the loop execute?


(ii) What is the range of possible values stored in the variable number?
Ans. (i) The outer loop executes 3 times ( i= 0, 1, 2) and for each execution of the outer
loop, the inner loop executes two times ( j= 0, 1). So, the inner loop executes 3 * 2 = 6
times
(ii) Math.random() returns a value between 0 (inclusive) and 1 (exclusive).
Math.random() * 10 will be in the range 0 (inclusive) and 10 (exclusive)
(int)(Math.random() * 10) will be in the range 0 (inclusive) and 9 (inclusive) (only integer
values)

(i) Consider the following class: [2]

1 public class myClass {


2 public static int x = 3, y = 4;
3 public int a = 2, b = 3; }

(i) Name the variables for which each object of the class will have its own distinct
copy.
(ii) Name the variables that are common to all objects of the class.
Ans. For static variables, all objects share a common copy while for non static variable,
each object gets its own copy. Therefore, the answer is
(i) a, b
(ii) x, y

(j) What will be the output when the following code segments are executed? [2]
(i)

1 String s = "1001";
2 int x = Integer.valueOf(s);
3 double y = Double.valueOf(s);
4 System.out.println("x=" +x);
5 System.out.println("y=" +y);

(ii)

1 System.out.println("The King said \"Begin at the beginning!\" to me.");

Ans. (i) s = “1001″


x = 1001
y = 1001.0
Output will be

1 x=1001
2 y=1001.0

(ii) The King said “Begin at the beginning!” to me.


\” is an escape sequence which prints ”

SECTION B (60 Marks)


Attempt any four questions from this Section.

Question 4.
Define a class named movieMagic with the following description:
Instance variables/data members:
int year – to store the year of release of a movie
String title – to store the title of the movie.
float rating – to store the popularity rating of the movie.
(minimum rating = 0.0 and maximum rating = 5.0)
Member Methods:
(i) movieMagic() Default constructor to initialize numeric data members to 0 and String
data member to “”.
(ii) void accept() To input and store year, title and rating.
(iii) void display() To display the title of a movie and a message based on the rating as per
the table below.

RATING MESSAGE TO BE DISPLAYED

0.0 to 2.0 Flop

2.1 to 3.4 Semi-hit

3.5 to 4.5 Hit

4.6 to 5.0 Super Hit

Write a main method to create an object of the class and call the above member methods.

Ans.
Program

1 import java.util.Scanner;
2
3 public class movieMagic {
4
5 int year;
6 String title;
7 float rating;
8
9 public movieMagic() {
10 year = 0;
11 title = "";
12 rating = 0;
13 }
14
15 public void accept() {
16 Scanner scanner = new Scanner(System.in);
17 System.out.print("Enter title: ");
18 title = scanner.nextLine();
19 System.out.print("Enter year: ");
20 year = scanner.nextInt();
21 System.out.print("Enter rating: ");
22 rating = scanner.nextFloat();
23 }
24
25 public void display() {
26 System.out.println("Movie Title - " + title);
27 if (rating >= 0 && rating <= 2.0) {
28 System.out.println("Flop");
29 } else if (rating >= 2.1 && rating <= 3.4) {
30 System.out.println("Semi-hit");
31 } else if (rating >= 3.5 && rating <= 4.5) {
32 System.out.println("Hit");
33 } else if (rating >= 4.6 && rating <= 5.0) {
34 System.out.println("Super Hit");
35 }
36 }
37
38 public static void main(String[] args) {
39 movieMagic movie = new movieMagic();
40 movie.accept();
41 movie.display();
42 }
43
44 }

Sample Output

1 Enter title: Raja Rani


2 Enter year: 2012
3 Enter rating: 5.0
4 Movie Title - Raja Rani
5 Super Hit

Question 5.

A special two-digit number is such that when the sum of its digits is added to the product
of its digits, the result is equal to the original two-digit number.

Example: Consider the number 59.


Sum of digits = 5 + 9 = 14
Product of its digits = 5 x 9 = 45
Sum of the sum of digits and product of digits= 14 + 45 = 59
Write a program to accept a two-digit number. Add the sum of its digits to the product of
its digits. If the value is equal to the number input, output the message “Special 2-digit
number” otherwise, output the message “Not a Special 2-digit number”.

Ans. We create a Scanner object and accept the input number using nextInt() method. The
input is stored in the variable ‘number’. It is given in the question that the input will be a
two digit number. We need to extract the two digits of the number into two variables
‘leftDigit’ and ‘rightDigit’. The left digit can be extracted by dividing the number by 10.
(Note that ‘number’ is an int and the divisor 10 is an int. So, the result will be an int and
not a float i.e. we obtain only the quotient as the result). The right digit can be obtained by
calculating the remainder when ‘number’ is divided by 10.

Let us take an example input – number = 59.


Then, leftDigit = number / 10 = 59 / 10 = 5
rightDigit = number % 10 = 59 % 10 = 9

Once, we have the two numbers, calculating the sum and product of the digits is easy.

1 int sumOfDigits = rightDigit + leftDigit;


2 int productOfDigits = rightDigit * leftDigit;

Next, we add the two variables above and store it in a new variable.

1 int sumOfProductAndSum = sumOfDigits + productOfDigits;

Finally, we use if else decision statements to check if the sum of product of digits and sum
of digits is same as the input number and print an appropriate message.

Program

1 import java.util.Scanner;
2
3 public class SpecialNumber {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 System.out.print("Enter number: ");
8 int number = scanner.nextInt();
9 int rightDigit = number % 10;
10 int leftDigit = number / 10;
11 int sumOfDigits = rightDigit + leftDigit;
12 int productOfDigits = rightDigit * leftDigit;
13 int sumOfProductAndSum = sumOfDigits + productOfDigits;
14 if (sumOfProductAndSum == number) {
15 System.out.println("Special 2-digit number");
16 } else {
17 System.out.println("Not a Special 2-digit number");
18 }
19 }
20 }

Sample Outputs

1 Enter number: 59
2 Special 2-digit number
1 Enter number: 34
2 Not a Special 2-digit number

Question 6.
Write a program to assign a full path and file name as given below. Using library functions,
extract and output the file path, file name and file extension separately as shown.

Input C:\Users\admin\Pictures\flower.jpg
Output Path: C:\Users\admin\Pictures\
File name: flower
Extension: jpg

Ans. We need to use the methods of the String class like indexOf(), lastIndexOf() and
substring() to solve this problem.

The input String can be divided into three parts, the path, file name and extension. These
three parts are separated by a backslash character and a dot as shown in the figure below.

So, first we need to find the indices of the backslash character and dot which separate
these regions. Note that there are several backslash characters in the input but the
backslash character which separates the file path from the name is the last backslash
character in the String. So, we need to use the lastIndexOf() method to find the index of
this backslash character. Even though in the example input, there is only one dot, folder
names and file names can contain multiple dots. So, for finding the index of the dot which
separates the file name and extension also, we use lastIndexOf() method. Moreover, the
backslash character is written as ‘\\’ and not ‘\’ as \ is an escape character.

1 int indexOfLastBackslash = input.lastIndexOf('\\');


2 int indexOfDot = input.lastIndexOf('.');

Once, we have the indices of the backslash character and dot, we can use the substring
method to extract the three parts. Substring() method takes two integer arguments – begin
and end; and returns the substring formed by the characters between begin (inclusive) and
end (exclusive).

1 String outputPath = input.substring(0, indexOfLastBackslash + 1);


2 String fileName = input.substring(indexOfLastBackslash + 1, indexOfDot);
3 String extension = input.substring(indexOfDot + 1);

Program

1 import java.util.Scanner;
2
3 public class FileName {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 System.out.print("Enter file name and path: ");
8 String input = scanner.nextLine();
9 int indexOfLastBackslash = input.lastIndexOf('\\');
10 int indexOfDot = input.lastIndexOf('.');
11 String outputPath = input.substring(0, indexOfLastBackslash + 1);
String fileName = input.substring(indexOfLastBackslash + 1,
12
indexOfDot);
13 String extension = input.substring(indexOfDot + 1);
14 System.out.println("Path: " + outputPath);
15 System.out.println("File Name: " + fileName);
16 System.out.println("Extension: " + extension);
17 }
18 }

Sample Output

1 Enter file name and path: C:\Users\admin\Pictures\flower.jpg


2 Path: C:\Users\admin\Pictures\
3 File Name: flower
4 Extension: jpg

Question 7.
Design a class to overload a function area() as follows:
(i) double area(double a. double b, double e) with three double arguments, returns the
area of a scalene triangle using the formula:
where

(ii) double area(int a, int b, int height) with three integer arguments, returns the area of a
trapezium using the formula:

(iii) double area(double diagonal1, double diagonal2) with two double arguments, returns
the area of a rhombus using the formula:

Ans.

1 public class Area {


2
3 public double area(double a, double b, double c) {
4 double s = (a + b + c) / 2;
5 double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
6 return area;
7 }
8
9 public double area(int a, int b, int height) {
10 double area = 0.5 * height * (a + b);
11 return area;
12 }
13
14 public double area(double diagonal1, double diagonal2) {
15 double area = 0.5 * (diagonal1 * diagonal2);
16 return area;
17 }
18 }

Question 8.
Using the switch statement. write a menu driven program to calculate the maturity amount
of a Bank Deposit.

The user is given the following options:


(i) Term Deposit
(ii) Recurring Deposit
For option (i) accept principal(P), rare of ¡interest(r) and time period in years(n). Calculate
and output the maturity amount(A) receivable using the formula

For option (ii) accept Monthly Installment (P), rate of interest(r) and time period in months
(n). Calculate and output the maturity amount(A) receivable using the formula

For an incorrect option, an appropriate error message should be displayed.

Ans.

1 import java.util.Scanner;
2
3 public class Interest {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 System.out.println("Menu");
8 System.out.println("1. Term Deposit");
9 System.out.println("2. Recurring Deposit");
10 System.out.print("Enter your choice: ");
11 int choice = scanner.nextInt();
12 switch (choice) {
13 case 1:
14 System.out.print("Enter principal: ");
15 int P1 = scanner.nextInt();
16 System.out.print("Enter rate of interest: ");
17 int r1 = scanner.nextInt();
18 System.out.print("Enter period in years: ");
19 int n1 = scanner.nextInt();
20 double maturityAmount1 = P1 * Math.pow(1 + r1 / 100.0, n1);

21 System.out.println("Maturity Amount is " +


maturityAmount1);
22 break;
23 case 2:
24 System.out.print("Enter monthly installment: ");
25 int P2 = scanner.nextInt();
26 System.out.print("Enter rate of interest: ");
27 int r2 = scanner.nextInt();
28 System.out.print("Enter period in months: ");
29 int n2 = scanner.nextInt();
double maturityAmount2 = P2 * n2 + P2 * (n2 * (n2 + 1)
30
/ 2.0) * (r2 / 100.0) * (1.0 / 12);

31 System.out.println("Maturity Amount is " +


maturityAmount2);
32 break;
33 default:
34 System.out.println("Invalid choice");
35 }
36 }
37 }

Sample Outputs

1 Menu
2 1. Term Deposit
3 2. Recurring Deposit
4 Enter your choice: 1
5 Enter principal: 1500
6 Enter rate of interest: 3
7 Enter period in years: 5
8 Maturity Amount is 1738.9111114500001
1 Menu
2 1. Term Deposit
3 2. Recurring Deposit
4 Enter your choice: 2
5 Enter monthly installment: 300
6 Enter rate of interest: 1
7 Enter period in months: 24
8 Maturity Amount is 7275.0
1 Menu
2 1. Term Deposit
3 2. Recurring Deposit
4 Enter your choice: 3
5 Invalid choice

Question 9.
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”.
(1982, 1987, 1993. 1996, 1999, 2003, 2006, 2007, 2009, 2010)

Ans.

1 import java.util.Scanner;
2
3 public class Search {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 System.out.print("Enter year of graduation: ");
8 int graduationYear = scanner.nextInt();
int[] years =
9
{1982, 1987, 1993, 1996, 1999, 2003, 2006, 2007, 2009, 2010};
10 boolean found = false;
11 int left = 0;
12 int right = years.length - 1;
13 while (left <= right) {
14 int middle = (left + right) / 2;
15 if (years[middle] == graduationYear) {
16 found = true;
17 break;
18 } else if (years[middle] < graduationYear) {
19 left = middle + 1;
20 } else {
21 right = middle - 1;
22 }
23 }
24 if (found) {
25 System.out.println("Record exists");
26 } else {
27 System.out.println("Record does not exist");
28 }
29 }
30 }

Sample Outputs

1 Enter year of graduation: 2007


2 Record exists
1 Enter year of graduation: 1900
2 Record does not exist
ICSE Paper – 2013
Class – X
Subject – Computer Applications
(Two Hours)

Attempt ALL questions from Section A and any FOUR questions from Section B.
The intended marks for questions or parts of questions are given in brackets [ ].

SECTION A (40 Marks)


Attempt ALL questions.

Question 1

a) What is meant by precedence of operators? [2]


Ans. Precedence of operators refers to the order in which the operators are applied to the
operands in an expression. For example, * has higher precedence than +. So, the
expression 8 + 2 * 5 will evaluate to 8 + 10 = 18

b) What is a literal? [2]


Ans. A literal is a constant data item. There are different literals like integer literals,
floating point literals and character literals.

c) State the Java concept that is implemented through:


i) a super class and a subclass.
ii) the act of representing essential features without including background details. [2]
Ans. i) Inheritance
ii) Abstraction

d) Give a difference between constructor and method. [2]


Ans. i)A constructor has no return type which a method has a return type.
ii) The name of the constructor should be the same as that of the class while the name of a
method can be any valid identifier.
iii) A constructor is automatically called upon object creation while methods are invoked
explicitly.

e) What are the types of casting shown by the following examples? [2]
i) double x =15.2;
int y =(int) x;
ii) int x =12;
long y = x;
Ans. i) Explicit casting
ii) Implicit casting

Question 2:

a) Name any two wrapper classes. [2]


Ans. Byte, Short, Integer, Long, Float, Double, Boolean, Character
b) What is the difference between break and continue statements when they occur in a
loop. [2]
Ans. The break statement terminates the loop while the continue statements current
iteration of the loop to be skipped and continues with the next iteration.

c) Write statements to show how finding the length of a character array and char[]
differs from finding the length of a String object str. [2]
Ans. The length of a character array is found by accessing the length attribute of the array
as shown below:
char[] array = new char[7];
int lengthOfCharArray = array.length;
The length of a String object is found by invoking the length() method which returns the
length as an int.
String str = “java”;
int lengthOfString = str.length();

d) Name the Java keyword that: [2]


(i) indicates a method has no return type.
(ii) stores the address of the currently calling object.
Ans. i) void
ii) this

e) What is an exception? [2]


Ans. An exception is an unforeseen situation that occurs during the execution of a
program. In simpler words, they are the errors that occur during the execution of a
program. The JRE throws an Exception object to indicate an exception which contains the
information related to that exception.

Question 3:

a) Write Java statement to create an object mp4 of class digital. [2]


Ans.

1 digital mp4 = new digital();

b) State the values stored in variables str1 and str2 [2]

1 String s1 = "good";
2 String s2="world matters";
3 String str1 = s2.substring(5).replace('t','n');
4 String str2 = s1.concat(str1);

Ans. s2.substring(5) gives ” matters”. When ‘t’ is replaced with ‘n’, we get ” manners”.
“good” when concatenated with ” manners” gives “good manners”.
So, str1 = ” manners” and str2 = “good manners”.

c) What does a class encapsulate? [2]


Ans. A class encapsulated the data (instance variables) and methods.
d) Rewrite the following program segment using the if..else statement. [2]
comm =(sale>15000)?sale*5/100:0;
Ans.

1 if ( sale > 15000 ) {


2 comm = sale * 5 / 100;
3 } else {
4 comm = 0;
5}

e) How many times will the following loop execute? What value will be returned? [2]

1 int x = 2, y = 50;
2 do{
3 ++x;
4 y-=x++;
5 }while(x<=10);
6 return y;

Ans. In the first iteration, ++x will change x from 2 to 3. y-=x++ will increase x to 4. And y
becomes 50-3=47.
In the second iteration, ++x will change x from 4 to 5. y-=x++ will increase x to 6. And y
becomes 47-5=42.
In the third iteration, ++x will change x from 6 to 7. y-=x++ will increase x to 8. And y
becomes 42-7=35.
In the fourth iteration, ++x will change x from 8 to 9. y-=x++ will increase x to 10. And y
becomes 35-9=26.
In the fifth iteration, ++x will change x from 10 to 11. y-=x++ will increase x to 12. And y
becomes 26-11=15.
Now the condition x<=10 fails.
So, the loop executes five times and the value of y that will be returned is 15.

f) What is the data type that the following library functions return? [2]
i) isWhitespace(char ch)
ii) Math.random()
Ans. i) boolean
ii) double

g) Write a Java expression for ut + ½ ft2 [2]


Ans. u * t + 0.5 * f * Math.pow ( t, 2)

h) If int n[] ={1, 2, 3, 5, 7, 9, 13, 16} what are the values of x and y? [2]

1 x=Math.pow(n[4],n[2]);
2 y=Math.sqrt(n[5]+[7]);
Ans. n[4] is 7 and n[2] is 3. So, Math.pow(7,3) is 343.0.
n[5] is 9 and n[7] is 16. So Math.sqrt(9+16) will give 5.0.
Note that pow() and sqrt() return double values and not int values.

i) What is the final value of ctr after the iteration process given below, executes? [2]

1 int ctr=0;
2 for(int i=1;i&lt;=5;i++)
3 for(int j=1;j&lt;=5;j+=2)
4 ++ctr;

Ans. Outer loop runs five times. For each iteration of the outer loop, the inner loop runs 3
times. So, the statement ++ctr executes 5*3=15 times and so the value of ctr will be 15.

j) Name the methods of Scanner class that: [2]


i) is used to input an integer data from standard input stream.
ii) is used to input a string data from standard input stream.
Ans. i) scanner.nextInt()
ii) scanner.next()

SECTION B (60 Marks )

Attempt any four questions from this Section.

The answers in this section should consist of the program in Blue J environment with Java
as the base. Each program should be written using Variable descriptions / Mnemonics
Codes such that the logic of the program is clearly depicted.

Flow-charts and Algorithms are not required.

Question 4:

Define a class called FruitJuice with the following description: [15]


Instance variables/data members:
int product_code – stores the product code number
String flavour – stores the flavor of the juice.(orange, apple, etc)
String pack_type – stores the type of packaging (tetra-pack, bottle etc)
int pack_size – stores package size (200ml, 400ml etc)
int product_price – stores the price of the product
Member Methods:
FriuitJuice() – default constructor to initialize integer data members
to zero and string data members to “”.
void input() – to input and store the product code, flavor, pack type,
pack size and product price.
void discount() – to reduce the product price by 10.
void display() – to display the product code, flavor, pack type,
pack size and product price.

Ans.
1 import java.util.Scanner;
2
3 public class FruitJuice {
4
5 int product_code;
6 String flavour;
7 String pack_type;
8 int pack_size;
9 int product_price;
10
11 public FruitJuice() {
12 product_code = 0;
13 flavour = "";
14 pack_type = "";
15 pack_size = 0;
16 product_price = 0;
17 }
18
19 public void input() {
20 Scanner scanner = new Scanner(System.in);
21 System.out.print("Enter product code: ");
22 product_code = scanner.nextInt();
23 System.out.print("Enter flavour: ");
24 flavour = scanner.next();
25 System.out.print("Enter pack type: ");
26 pack_type = scanner.next();
27 System.out.print("Enter pack size: ");
28 pack_size = scanner.nextInt();
29 System.out.print("Enter product price: ");
30 product_price = scanner.nextInt();
31 }
32
33 public void discount() {
34 product_price = (int) (0.9 * product_price);
35 }
36
37 public void display() {
38 System.out.println("Product Code: " + product_code);
39 System.out.println("Flavour: " + flavour);
40 System.out.println("Pack Type: " + pack_type);
41 System.out.println("Pack Size: " + pack_size);
42 System.out.println("Product Price: " + product_price);
43 }
44 }

Question 5:

The International Standard Book Number (ISBN) is a unique numeric book identifier which is
printed on every book. The ISBN is based upon a 10-digit code. The ISBN is legal if:
1xdigit1 + 2xdigit2 + 3xdigit3 + 4xdigit4 + 5xdigit5 + 6xdigit6 + 7xdigit7 + 8xdigit8 +
9xdigit9 + 10xdigit10 is divisible by 11.
Example: For an ISBN 1401601499
Sum=1×1 + 2×4 + 3×0 + 4×1 + 5×6 + 6×0 + 7×1 + 8×4 + 9×9 + 10×9 = 253 which is
divisible by 11.
Write a program to:
(i) input the ISBN code as a 10-digit integer.
(ii) If the ISBN is not a 10-digit integer, output the message “Illegal ISBN” and terminate the
program.
(iii) If the number is 10-digit, extract the digits of the number and compute the sum as
explained above.
If the sum is divisible by 11, output the message, “Legal ISBN”. If the sum is not divisible by
11, output the message, “Illegal ISBN”. [15]

Ans.

The data type of ISBN should be long instead of int as the maximum value of an int is
2,147,483,647 which is less than 9999999999 – the maximum possible value of an ISBN.

1 import java.util.Scanner;
2
3 public class ISBN {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 System.out.print("Enter ISBN code: ");
8 long isbnInteger = scanner.nextLong();
9 String isbn = isbnInteger + "";
10 if (isbn.length() != 10) {
11 System.out.println("Ilegal ISBN");
12 } else {
13 int sum = 0;
14 for (int i = 0; i < 10; i++) {
15 int digit = Integer.parseInt(isbn.charAt(i) + "");
16 sum = sum + (digit * (i + 1));
17 }
18 if (sum % 11 == 0) {
19 System.out.println("Legal ISBN");
20 } else {
21 System.out.println("Illegal ISBN");
22 }
23 }
24 }
25 }

Question 6:

Write a program that encodes a word into Piglatin. To translate word into Piglatin word,
convert the word into uppercase and then place the first vowel of the original word as the
start of the new word along with the remaining alphabets. The alphabets present before
the vowel being shifted towards the end followed by “AY”.
Sample Input(1): London Sample Output(1): ONDONLAY
Sample Input(2): Olympics Sample Output(2): OLYMPICSAY [15]

Ans.

1 import java.util.Scanner;
2
3 public class Piglatin {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 System.out.print("Enter a String: ");
8 String input = scanner.next();
9 input = input.toUpperCase();
10 String piglatin = "";
11 boolean vowelFound = false;
12 for (int i = 0; i < input.length(); i++) {
13 char c = input.charAt(i);

14 if ((c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') &&


!vowelFound) {
15 piglatin = c + piglatin;
16 vowelFound = true;
17 } else {
18 piglatin = piglatin + c;
19 }
20 }
21 piglatin = piglatin + "AY";
22 System.out.println("Piglatin word is " + piglatin);
23 }
24 }

Question 7:

Write a program to input 10 integer elements in an array and sort them


In descending order using bubble sort technique. [15]
Ans.

1 import java.util.Scanner;
2
3 public class BubbleSort {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 System.out.println("Enter ten numbers:");
8 int[] numbers = new int[10];
9 for (int i = 0; i < 10; i++) {
10 numbers[i] = scanner.nextInt();
11 }
12 for (int i = 0; i < 10; i++) {
13 for (int j = 0; j < 10 - i - 1; j++) {
14 if (numbers[j] < numbers[j + 1]) {
15 int temp = numbers[j];
16 numbers[j] = numbers[j + 1];
17 numbers[j + 1] = temp;
18 }
19 }
20 }
21 System.out.println("Sorted Numbers:");
22 for (int i = 0; i < 10; i++) {
23 System.out.println(numbers[i]);
24 }
25 }
26 }

Question 8:
Design a class to overload a function series() as follows: [15]
(i) double series(double n) with one double argument and
returns the sum of the series.
sum = 1/1 + 1/2 + 1/3 + ….. 1/n
(ii) double series(double a, double n) with two double arguments
and returns the sum of the series.
sum = 1/a2 + 4/a5 + 7/a8 + 10/a11 ….. to n terms

Ans.

1 public class Overload {


2
3 public double series(double n) {
4 double sum = 0;
5 for (int i = 1; i <= n; i++) {
6 sum = sum + (1.0 / i);
7 }
8 return sum;
9 }
10
11 public double series(double a, double n) {
12 double sum = 0;
13 for (int i = 0; i < n; i++) {
14 sum = sum + ((3 * i + 1.0) / Math.pow(a, 3 * i + 2));
15 }
16 return sum;
17 }
18 }

Question 9:

Using the switch statement, write a menu driven program: [15]


(i) To check and display whether a number input by the user is
a composite number or not (A number is said to be a composite, if it
has one or more then one factors excluding 1 and the number itself).
Example: 4, 6, 8, 9…
(ii) To find the smallest digit of an integer that is input:
Sample input: 6524
Sample output: Smallest digit is 2
For an incorrect choice, an appropriate error message should be displayed.
Ans.

1 import java.util.Scanner;
2
3 public class Menu {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 System.out.println("Menu");
8 System.out.println("1. Check composite number");
9 System.out.println("2. Find smallest digit of a number");
10 System.out.print("Enter your choice: ");
11 int choice = scanner.nextInt();
12 switch (choice) {
13 case 1:
14 System.out.print("Enter a number: ");
15 int number = scanner.nextInt();
16 if (isComposite(number)) {
17 System.out.println("It is a composite number");
18 } else {
19 System.out.println("It is not a composite number");
20 }
21 break;
22 case 2:
23 System.out.print("Enter a number: ");
24 int num = scanner.nextInt();
25 int smallest = smallestDigit(num);
26 System.out.println("Smallest digit is " + smallest);
27 break;
28 default:
29 System.out.println("Incorrect choice");
30 break;
31 }
32 }
33
34 public static boolean isComposite(int n) {
35 for (int i = 2; i < n; i++) {
36 if (n % i == 0) {
37 return true;
38 }
39 }
40 return false;
41 }
42
43 public static int smallestDigit(int number) {
44 int smallest = 9;
45 while (number > 0) {
46 int rem = number % 10;
47 if (rem < smallest) {
48 smallest = rem;
49 }
50 number = number / 10;
51 }
52 return smallest;
53 }
54 }
ICSE Class 10 Computer Applications ( Java ) 2012 Solved Question
Paper

COMPUTER APPLICATIONS
(Theory)
(Two Hours)

Answers to this Paper must be written on the paper provided separately.


You will not be allowed to write during the first 15 minutes.
This time is to be spent in reading the question paper.
The time given at the head of this Paper is the time allowed for writing.the answers.
This Paper is divided into two Sections.
Attempt all questions from Section A and any four questions from Section B. The intended marks for questions
or parts of questions are given in brackets [ ].

SECTION A (40 Marks)

Attempt all questions.

Question 1

(a) Give one example each of a primitive data type and a composite data type. [2]
Ans. Primitive Data Types – byte, short, int, long, float, double, char, boolean
Composite Data Type – Class, Array, Interface

(b) Give one point of difference between unary and binary operators. [2]
Ans. A unary operator requires a single operand whereas a binary operator requires two operands.
Examples of Unary Operators – Increment ( ++ ) and Decrement ( — ) Operators
Examples of Binary Operators – +, -, *, /, %

(c) Differentiate between call by value or pass by value and call by reference or pass by reference. [2]
Ans. In call by value, a copy of the data item is passed to the method which is called whereas in call by
reference, a reference to the original data item is passed. No copy is made. Primitive types are passed by value
whereas reference types are passed by reference.

(d) Write a Java expression for (under root of 2as+u2) [2]


Ans. Math.sqrt ( 2 * a * s + Math.pow ( u, 2 ) )
( or )
Math.sqrt ( 2 * a * s + u * u )

(e) Name the types of error (syntax, runtime or logical error) in each case given below:
(i) Division by a variable that contains a value of zero.
(ii) Multiplication operator used when the operation should be division.
(iii) Missing semicolon. [2]
Ans.
(i) Runtime Error
(ii) Logical Error
(iii) Syntax Error
Question 2

(a)Create a class with one integer instance variable. Initialize the variable using:
(i) default constructor
(ii) parameterized constructor. [2]
Ans.

1 public class Integer {


2
3 int x;
4
5 public Integer() {
6 x = 0;
7 }
8
9 public Integer(int num) {
10 x = num;
11 }
12 }

(b)Complete the code below to create an object of Scanner class.


Scanner sc = ___________ Scanner( ___________ ) [2]
Ans. Scanner sc = new Scanner ( System.in )

(c) What is an array? Write a statement to declare an integer array of 10 elements. [2]
Ans. An array is a reference data used to hold a set of data of the same data type. The following statement
declares an integer array of 10 elements -
int arr[] = new int[10];

(d) Name the search or sort algorithm that:


(i) Makes several passes through the array, selecting the next smallest item in the array each time and
placing it where it belongs in the array.
(ii) At each stage, compares the sought key value with the key value of the middle element of the array.
[2]
Ans. (i) Selection Sort
(ii) Binary Search

(e) Differentiate between public and private modifiers for members of a class. [2]
Ans. Variables and Methods whwith the public access modie the class also.

Question 3

(a) What are the values of x and y when the following statements are executed? [2]

1 int a = 63, b = 36;


2 boolean x = (a < b ) ? true : false; int y= (a > b ) ? a : b ;
Ans. x = false
y = 63

(b) State the values of n and ch [2]

1 char c = 'A':
2 int n = c + 1;

Ans. The ASCII value for ‘A’ is 65. Therefore, n will be 66.

(c) What will be the result stored in x after evaluating the following expression? [2]

1 int x=4;
2 x += (x++) + (++x) + x;

Ans. x = x + (x++) + (++x) + x


x=4+4+6+6
x = 20

(d) Give the output of the following program segment: [2]

1 double x = 2.9, y = 2.5;


2 System.out.println(Math.min(Math.floor(x), y));
3 System.out.println(Math.max(Math.ceil(x), y));

Ans.
2.0
3.0
Explanation : Math.min(Math.floor(x), y) = Math.min ( 2.0, 2.5 ) = 2.0
Math.max(Math.ceil(x), y)) = Math.max ( 3.0, 2.5 ) = 3.0

(e) State the output of the following program segment. [2]

1 String s = "Examination";
2 int n = s.length();
3 System.out.println(s.startsWith(s.substring(5, n)));
4 System.out.println(s.charAt(2) == s.charAt(6));

Ans.
false
true
Explanation : n = 11
s.startsWith(s.substring(5, n)) = s.startsWith ( “nation” ) = false
( s.charAt(2) == s.charAt(6) ) = ( ‘a’== ‘a’ ) = true

(f) State the method that:


(i) Converts a string to a primitive float data type
(ii) Determines if the specified character is an uppercase character [2]
Ans. (i) Float.parseFloat(String)
(ii) Character.isUpperCase(char)

(g) State the data type and values of a and b after the following segment is executed.[2]

1 String s1 = "Computer", s2 = "Applications";


2 a = (s1.compareTo(s2));
3 b = (s1.equals(s2));

Ans. Data type of a is int and b is boolean.


ASCII value of ‘C’ is 67 and ‘A’ is 65. So compare gives 67-65 = 2.
Therefore a = 2
b = false

(h) What will the following code output? [2]

1 String s = "malayalam";
2 System.out.println(s.indexOf('m'));
3 System.out.println(s.lastIndexOf('m'));

Ans.
0
8

(i) Rewrite the following program segment using while instead of for statement [2]

1 int f = 1, i;
2 for (i = 1; i <= 5; i++) {
3 f *= i;
4 System.out.println(f);
5}

Ans.

1 int f = 1, i = 1;
2 while (i <= 5) {
3 f *= i;
4 System.out.println(f);
5 i++;
6}

(j) In the program given below, state the name and the value of the
(i) method argument or argument variable
(ii) class variable
(iii) local variable
(iv) instance variable [2]

1 class myClass {
2
3 static int x = 7;
4 int y = 2;
5
6 public static void main(String args[]) {
7 myClass obj = new myClass();
8 System.out.println(x);
9 obj.sampleMethod(5);
10 int a = 6;
11 System.out.println(a);
12 }
13
14 void sampleMethod(int n) {
15 System.out.println(n);
16 System.out.println(y);
17 }
18 }

Ans. (i) name = n value =5


(ii) name = y value = 7
(iii) name = a value = 6
(iv) name = obj value = new MyClass()

SECTION B (60 MARKS)

Attempt any four questions from this Section.


The answers in this Section should consist of the Programs in either Blue J environment or any program
environment with Java as the base. Each program should be written using Variable descriptions/Mnemonic
Codes so that the logic of the program is clearly depicted.
Flow-Charts and Algorithms are not required.

Question 4

Define a class called Library with the following description:


Instance variables/data members:
Int acc_num – stores the accession number of the book
String title – stores the title of the book stores the name of the author
Member Methods:
(i) void input() – To input and store the accession number, title and author.
(ii)void compute – To accept the number of days late, calculate and display and fine charged at the rate of Rs.2
per day.
(iii) void display() To display the details in the following format:
Accession Number Title Author
Write a main method to create an object of the class and call the above member methods. [ 15]

Ans.

1 public class Library {


2
3 int acc_num;
4 String title;
5 String author;
6
7 public void input() throws IOException {
BufferedReader br
8
= new BufferedReader(newInputStreamReader(System.in));
9 System.out.print("Enter accession number: ");
10 acc_num = Integer.parseInt(br.readLine());
11 System.out.print("Enter title: ");
12 title = br.readLine();
13 System.out.print("Enter author: ");
14 author = br.readLine();
15 }
16
17 public void compute() throws IOException {
BufferedReader br
18
= new BufferedReader(newInputStreamReader(System.in));
19 System.out.print("Enter number of days late: ");
20 int daysLate = Integer.parseInt(br.readLine());;
21 int fine = 2 * daysLate;
22 System.out.println("Fine is Rs " + fine);
23 }
24
25 public void display() {
26 System.out.println("Accession Number\tTitle\tAuthor");
27 System.out.println(acc_num + "\t" + title + "\t" + author);
28 }
29
30 public static void main(String[] args) throws IOException {
31 Library library = new Library();
32 library.input();
33 library.compute();
34 library.display();
35 }
36 }

Question 5

Given below is a hypothetical table showing rates of Income Tax for male citizens below the age of 65 years:

Taxable Income (TI) in Income Tax in

Does not exceed 1,60,000 Nil

Is greater than 1,60,000 and less than or equal to 5,00,000 ( TI – 1,60,000 ) * 10%

Is greater than 5,00,000 and less than or equal to 8,00,000 [ (TI - 5,00,000 ) *20% ] + 34,000

Is greater than 8,00,000 [ (TI - 8,00,000 ) *30% ] + 94,000

Write a program to input the age, gender (male or female) and Taxable Income of a person.If the age is more
than 65 years or the gender is female, display “wrong category*.
If the age is less than or equal to 65 years and the gender is male, compute and display the Income Tax payable
as per the table given above. [15]
Ans.

1 import java.util.Scanner;
2
3 public class IncomeTax {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 System.out.print("Enter age: ");
8 int age = scanner.nextInt();
9 System.out.print("Enter gender: ");
10 String gender = scanner.next();
11 System.out.print("Enter taxable income: ");
12 int income = scanner.nextInt();
13 if (age > 65 || gender.equals("female")) {
14 System.out.println("Wrong category");
15 } else {
16 double tax;
17 if (income <= 160000) { tax = 0;
} else if (income > 160000 && income <= 500000) { tax =
(income - 160000) * 10 / 100; } else if (income >= 500000 &&
income <= 800000) {
18 tax = (income - 500000) * 20 / 100 + 34000;
19 } else {
20 tax = (income - 800000) * 30 / 100 + 94000;
21 }
22 System.out.println("Income tax is " + tax);
23 }
24 }
25 }

Question 6

Write a program to accept a string. Convert the string to uppercase. Count and output the number of double
letter sequences that exist in the string.
Sample Input: “SHE WAS FEEDING THE LITTLE RABBIT WITH AN APPLE
Sample Output: 4 [ 15]

Ans.

1 import java.util.Scanner;
2
3 public class StringOperations {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 System.out.print("Enter a String: ");
8 String input = scanner.nextLine();
9 input = input.toUpperCase();
10 int count = 0;
11 for (int i = 1; i < input.length(); i++) {
12 if (input.charAt(i) == input.charAt(i - 1)) {
13 count++;
14 }
15 }
16 System.out.println(count);
17 }
18 }

Question 7
Design a class to overload a function polygon() as follows:
(i) void polygon(int n, char ch) : with one integer argument and one character type argument that draws a filled
square of side n using the character stored in ch.
(ii) void polygon(int x, int y) : with two integer arguments that draws a filled rectangle of length x and breadth
y, using the symbol ‘@’
(iii)void polygon( ) : with no argument that draws a filled triangle shown below.

Example:
(i) Input value of n=2, ch=’O’
Output:
OO
OO
(ii) Input value of x=2, y=5
Output:
@@@@@
@@@@@
(iii) Output:
*
**
*** [15]

Ans.

1 public class Overloading {


2
3 public void polygon(int n, char ch) {
4 for (int i = 1; i <= n; i++) {
5 for (int j = 1; j <= n; j++) {
6 System.out.print(ch);
7 }
8 System.out.println();
9 }
10 }
11
12 public void polygon(int x, int y) {
13 for (int i = 1; i <= x; i++) {
14 for (int j = 1; j <= y; j++) {
15 System.out.print("@");
16 }
17 System.out.println();
18 }
19 }
20
21 public void polygon() {
22 for (int i = 1; i <= 3; i++) {
23 for (int j = 1; j <= i; j++) {
24 System.out.print("*");
25 }
26 System.out.println();
27 }
28 }
29 }

Question 8

Using the switch statement, writw a menu driven program to:


(i) Generate and display the first 10 terms of the Fibonacci series 0,1,1,2,3,5….The first two Fibonacci
numbers are 0 and 1, and each subsequent number is the sum of the previous two.
(ii)Find the sum of the digits of an integer that is input.
Sample Input: 15390
Sample Output: Sum of the digits=18
For an incorrect choice, an appropriate error message should be displayed [15]

Ans.

1 import java.util.Scanner;
2
3 public class Menu {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 System.out.println("Menu");
8 System.out.println("1. Fibonacci Sequence");
9 System.out.println("2. Sum of Digits");
10 System.out.print("Enter choice: ");
11 int choice = scanner.nextInt();
12 switch (choice) {
13 case 1:
14 int a = 0;
15 int b = 1;
16 System.out.print("0 1 ");
for (int i = 3; i <= 10; i++) { int c =
a + b; System.out.print(c + " "); a
= b; b = c;
17
} break; case 2:
System.out.print("Enter a number: "); int num =
scanner.nextInt(); int sum = 0; while(num
> 0) {
18 int rem = num % 10;
19 sum = sum + rem;
20 num = num / 10;
21 }
22 System.out.println("Sum of digits is " + sum);
23 break;
24 default:
25 System.out.println("Invalid Choice");
26 }
27 }
28 }

Question 9

Write a program to accept the names of 10 cities in a single dimension string array and their STD (Subscribers
Trunk Dialing) codes in another single dimension integer array. Search for a name of a city input by the user in
the list. If found, display “Search Successful” and print the name of the city along with its STD code, or else
display the message “Search Unsuccessful, No such city in the list’. [15]

Ans.

1 import java.util.Scanner;
2
3 public class Cities {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 String[] cities = new String[10];
8 int[] std = new int[10];
9 for (int i = 0; i < 10; i++) {
10 System.out.print("Enter city: ");
11 cities[i] = scanner.next();
12 System.out.print("Enter std code: ");
13 std[i] = scanner.nextInt();
14 }
15 System.out.print("Enter city name to search: ");
16 String target = scanner.next();
17 boolean searchSuccessful = false;
18 for (int i = 0; i < 10; i++) {
19 if (cities[i].equals(target)) {
20 System.out.println("Search successful");
21 System.out.println("City : " + cities[i]);
22 System.out.println("STD code : " + std[i]);
23 searchSuccessful = true;
24 break;
25 }
26 }
27 if (!searchSuccessful) {
System.out.println("Search Unsuccessful, No such city in the
28
list");
29 }
30 }
31 }
ICSE Class 10 Computer Applications ( Java ) 2011 Solved Question
Paper

COMPUTER APPLCATIONS

(Theory)
Two Hours

Answers to this Paper must be written on the paper provided separately.


You will not be allowed to write during the first 15 minutes.
This time is to be spent in reading the Question Paper.
The time given at the head of the Paper is the time allowed for writing the answers.
This paper is divided into two Sections.
Attempt all questions from Section A and any four questions from Section B.
The intended marks for questions or parts of questions are given in bracket [ ]

SECTION – A (40 Marks)

Question 1.

(a) What is the difference between an object and a class? [2]


Ans. 1. A class is a blueprint or a prototype of a real world object. It contains instance
variables and methods whereas an object is an instance of a class.
2. A class exists in the memory of a computer while an object does not.
3. There will be only one copy of a class whereas multiple objects can be instantiated from
the same class.

(b) What does the token ‘keyword’ refer to in the context of Java? Give an example for
keyword. [2]
Ans. Keywords are reserved words which convey special meanings to the compiler and
cannot be used as identifiers. Example of keywords : class, public, void, int

(c) State the difference between entry controlled loop and exit controlled loop. [2]
Ans. In an entry controlled loop, the loop condition is checked before executing the body
of the loop. While loop and for loop are the entry controlled loops in Java.
In exit controlled loops, the loop condition is checked after executing the body of the loop.
do-while loop is the exit controlled loop in Java.

(d) What are the two ways of invoking functions? [2]


Ans. If the function is static, it can be invoked by using the class name. If the function is
non-static, an object of that class should be created and the function should be invoked
using that object.

(e) What is difference between / and % operator? [2]


Ans. / is the division operator whereas % is the modulo (remainder) operator. a / b gives
the result obtained on diving a by b whereas a % b gives the remainder obtained on diving
a by b.

Question 2.
(a) State the total size in bytes, of the arrays a [4] of char data type and p [4] of float
data type. [2]
Ans. char is two bytes. So a[4] will be 2*4=8 bytes.
float is 4 bytes. So p[4] will be 4*4=16 bytes.

(b) (i) Name the package that contains Scanner class.


(ii) Which unit of the class gets called, when the object of the class is created? [2]
Ans. (i) java.util
(ii) Constructor

(c) Give the output of the following: [2]

1 String n = “Computer Knowledge”;


2 String m = “Computer Applications”;
3 System.out.println(n.substring (0,8). concat (m.substring(9)));
4 System.out.println(n.endsWith(“e”));

Ans. n.substring(0,8) gives “Computer”. m.substring(9) gives “Applications”. These two on


concatenation gives “ComputerApplications”. n ends with “e”. So, it gives true.
The output is:

1 ComputerApplications
2 true

(d) Write the output of the following: [2]


(i) System.out.println (Character.isUpperCase(‘R’));
(ii) System.out.println(Character.toUpperCase(‘j’));
Ans. (i) true
(ii) J

(e) What is the role of keyword void in declaring functions? [2]


Ans. void indicates that the function doesn’t return any value.

Question 3

(a) Analyse the following program segment and determine how many times the loop
will be executed and what will be the output of the program segment ? [2]

1 int p = 200;
2 while(true)
3{
4 if (p<100)
5 break;
6 p=p-20;
7}
8 System.out.println(p);
Ans.p values changes as follows : 200, 180, 160, 140, 120, 100, 80. So, the loop executes
six times and value of p is 80.

(b) What will be the output of the following code? [2]


(i)

1 int k = 5, j = 9;
2 k += k++ – ++j + k;
3 System.out.println("k= " +k);
4 System.out.println("j= " +j);

Ans.

1k = 6
2 j = 10

Explanation:
k += k++ – ++j + k
k = k + k++ – ++j + k
k = 5 + 5 – 10 + 6
k=6
j = 10 as it has been incremented in the ++j operation.

(ii) [2]

1 double b = -15.6;
2 double a = Math.rint (Math.abs (b));
3 System.out.println("a= " +a);

Ans.

1 a =16.0

Maths.abs(-15.6) will give 15.6 and Math.rint(15.6) gives 16.0.

(c) Explain the concept of constructor overloading with an example . [2]


Ans. A class can have more than one constructor provided that the signatures differ. This
is known as constructor overloading.
Example:

1 class Age {
2
3 int age;
4
5 public Age() {
6 age = -1;
7 }
8
9 public Age(int age) {
10 this.age = age;
11 }
12 }

(d) Give the prototype of a function search which receives a sentence sentnc and a
word wrd and returns 1 or 0 ? [2]
Ans.

1 public boolean function ( sentence sentnc, word wrd )

or

1 public int function ( sentence sentnc, word wrd )

(e) Write an expression in Java for z = (5×3 + 2y ) / ( x + y) [2]


Ans.

1 z = ( 5 * Math.pow ( x, 3 ) + 2 * y ) / ( x + y )

(f) Write a statement each to perform the following task on a string: [2]
(i) Find and display the position of the last space in a string s.
(ii) Convert a number stored in a string variable x to double data type
Ans. (i) System.out.println(s.lastIndexOf(” “);
(ii) Double.parseDouble(x)

(g) Name the keyword that: [2]


(i) informs that an error has occurred in an input/output operation.
(ii) distinguishes between instance variable and class variables.
Ans. (i) throw
(ii) static

(h) What are library classes ? Give an example. [2]


Ans. Library classes are the predefined classes which are a part of java API. Ex: String,
Scanner

(i) Write one difference between Linear Search and Binary Search . [2]
Ans. Linear search can be used with both sorted and unsorted arrays. Binary search can be
used only with sorted arrays.

SECTION – B (60 Marks)


Attempt any four questions from this Section.

The answers in this Section should consist of the Programs in either Blue J environment or
any program environment with Java as the base.
Each program should be written using Variable descriptions/Mnemonic Codes such that the
logic of the program is clearly depicted.
Flow-Charts and Algorithms are not required.

Question 4.

Define a class called mobike with the following description: [15]


Instance variables/data members: int bno – to store the bike’s number
int phno – to store the phone number of the customer
String name – to store the name of the customer
int days – to store the number of days the bike is taken on rent
int charge – to calculate and store the rental charge
Member methods:
void input( ) – to input and store the detail of the customer.
void computer( ) – to compute the rental charge
The rent for a mobike is charged on the following basis.
First five days Rs 500 per day;
Next five days Rs 400 per day
Rest of the days Rs 200 per day
void display ( ) – to display the details in the following format:
Bike No. PhoneNo. No. of days Charge

Ans.

1 import java.util.Scanner;
2
3 public class mobike {
4
5 int bno;
6 int phno;
7 String name;
8 int days;
9 int charge;
10
11 public void input() {
12 Scanner scanner = new Scanner(System.in);
13 System.out.print("Enter bike number: ");
14 bno = scanner.nextInt();
15 System.out.print("Enter phone number: ");
16 phno = scanner.nextInt();
17 System.out.print("Enter your name: ");
18 name = scanner.next();
19 System.out.print("Enter number of days: ");
20 days = scanner.nextInt();
21 }
22
23 public void compute() {
24 if (days <= 5) {
25 charge = 500 * days;
26 } else if (days <= 10) {
27 charge = 5 * 500 + (days - 5) * 400;
28 } else {
29 charge = 5 * 500 + 5 * 400 + (days - 10) * 200;
30 }
31 }
32
33 public void display() {
System.out.println("Bike No. \tPhone No. \t No. of Days \t
34
Charge");
35 System.out.println(bno + "\t" + phno + "\t" + days + "\t" + charge);
36 }
37 }

Question 5.

Write a program to input and sort the weight of ten people. Sort and display them in
descending order using the selection sort technique. [15]

Ans.

1 import java.util.Scanner;
2
3 public class SelectionSort {
4
5 public void program() {
6 Scanner scanner = new Scanner(System.in);
7 int[] weights = new int[10];
8 System.out.println("Enter weights: ");
9 for (int i = 0; i < 10; i++) {
10 weights[i] = scanner.nextInt();
11 }
12 for (int i = 0; i < 10; i++) {
13 int highest = i;

14 for (int j = i + 1; j < 10; j++) { if(weights[j]


> weights[highest]) {
15 highest = j;
16 }
17 }
18 int temp = weights[highest];
19 weights[highest] = weights[i];
20 weights[i] = temp;
21 }
22 System.out.println("Sorted weights:");
23 for (int i = 0; i < 10; i++) {
24 System.out.println(weights[i]);
25 }
26 }
27 }

Question 6.

Write a program to input a number and print whether the number is a special number or
not. (A number is said to be a special number, if the sum of the factorial of the digits of the
number is same as the original number). [15]

Ans.

1 import java.util.Scanner;
2
3 public class SpecialNumber {
4
5 public int factorial(int n) {
6 int fact = 1;
for (int i = 1; i <= n; i++) { fact = fact * i;
7} return fact; } public int sumOfDigita(intnum)
{ int sum = 0; while (num > 0) {
8 int rem = num % 10;
9 sum = sum + rem;
10 num = sum / 10;
11 }
12 return sum;
13 }
14
15 public boolean isSpecial(int num) {
16 int fact = factorial(num);
17 int sum = sumOfDigita(fact);
18 if (sum == num) {
19 return true;
20 } else {
21 return false;
22 }
23 }
24
25 public void check() {
26 Scanner scanner = new Scanner(System.in);
27 System.out.print("Enter a number: ");
28 int num = scanner.nextInt();
29 if (isSpecial(num)) {
30 System.out.println("It is a special number");
31 } else {
32 System.out.println("It is not a special number");
33 }
34 }
35
36 }

Question 7

Write a program to accept a word and convert it into lowercase if it is in uppercase, and
display the new word by replacing only the vowels with the character following it. [15]

Example
Sample Input : computer
Sample Output : cpmpvtfr

Ans.

1 import java.util.Scanner;
2
3 public class StringConversion {
4
5 public static void convert() {
6 Scanner scanner = new Scanner(System.in);
7 System.out.print("Enter a String: ");
8 String input = scanner.next();
9 input = input.toLowerCase();
10 String answer = "";
11 for (int i = 0; i < input.length(); i++) {
12 char c = input.charAt(i);
13 if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
14 answer = answer + (char) (c + 1);
15 } else {
16 answer = answer + c;
17 }
18 }
19 System.out.println(answer);
20 }
21
22 }

Question 8.
Design a class to overload a function compare ( ) as follows: [15]
(a) void compare (int, int) – to compare two integer values and print the greater of the two
integers.
(b) void compare (char, char) – to compare the numeric value of two character with higher
numeric value
(c) void compare (String, String) – to compare the length of the two strings and print the
longer of the two.

Ans.

1 public class Overloading {


2
3 public void compare(int a, int b) {
4 int max = Math.max(a, b);
5 System.out.println(max);
6 }
7
8 public void compare(char a, char b) {
9 char max = (char) Math.max(a, b);
10 System.out.println(max);
11 }
12
13 public void compare(String a, String b) {
14 if (a.length() > b.length()) {
15 System.out.println(a);
16 } else if (a.length() < b.length()) {
17 System.out.println(b);
18 } else {
19 System.out.println(a);
20 System.out.println(b);
21 }
22 }
23 }

Question 9
Write a menu driven program to perform the following . (Use switch-case statement) [15]
(a) To print the series 0, 3, 8, 15, 24 ……. n terms (value of ‘n’ is to be an input by the
user).
(b) To find the sum of the series given below:
S = 1/2+ 3/4 + 5/6 + 7/8 … 19/20

Ans.

Series 1 : The i term is i -1.


th 2

1 import java.util.Scanner;
2
3 public class Menu {
4
5 public void series1(int n) {
6 for (int i = 1; i <= n; i++) {
7 int term = i * i - 1;
8 System.out.print(term + " ");
9 }
10 }
11
12 public double series2(int n) {
13 double sum = 0;
14 for (int i = 1; i <= n; i++) {
15 sum = sum + (double) (2 * i - 1) / (2 * i);
16 }
17 return sum;
18 }
19
20 public void menu() {
21 Scanner scanner = new Scanner(System.in);
22 System.out.println("1. Print 0, 3, 8, 15, 24... n tersm");
System.out.println("2. Sum of series 1/4 + 3/4 + 7/8 + ... n
23
terms");
24 System.out.print("Enter your choice: ");
25 int choice = scanner.nextInt();
26 System.out.print("Enter n: ");
27 int n = scanner.nextInt();
28 switch (choice) {
29 case 1:
30 series1(n);
31 break;
32 case 2:
33 double sum = series2(n);
34 System.out.println(sum);
35 break;
36 default:
37 System.out.println("Invalid choice");
38 }
39 }
40
41 public static void main(String[] args) {
42 Menu menu = new Menu();
43 menu.menu();
44 }
45 }
ICSE Class 10 Computer Applications ( Java ) 2009 Solved Question
Paper

ICSE Computer Applications 2009


(Two Hours)
Attempt all questions from Section A and any four four questions from Section B. The
intended marks for each question are given in brackets []

Section A

Question 1:

(a) Why is a class called a factory of objects? [2]


Ans. A class is known as a factory of objects because objects are instantiated from classes.
Each object gets a copy of the instance variables present in the class. It is like a factory
producing objects.

(b) State the difference between a boolean literal and a character literal. [2]
Ans. i) A boolean literal can store one of two values – true and false. A character literal can
store a single Unicode character.
ii) The memory required by a boolean literal depends on the implementation. The memory
required by a character literal is 2 bytes.

(c) What is the use and syntax of a ternary operator? [2]


Ans. The ternary operator is a decision making operator which can be used to replace
certain if else statement.
Syntax: condition ? expression1 : expression2

(d) Write one word answer for the following: [2]


i) A method that converts a string to a primitive integer data type
ii) The default initial value of a boolean variable data type
Ans. i) Integer.parseInt()
ii) false

(e) State one similarity and one difference between while and for loop. [2]
Ans. A while loop contains only a condition while a for loop contains initialization,
condition and iteration.

Question 2:

(a) Write the function prototype for the function “sum” that takes an integer variable
(x) as its argument and returns a value of float data type. [2]
Ans.

1 public float sum(int x)

(b) What is the use of the keyword this? [2]


Ans. this refers to the object on which the method has been invoked. If an instance variable
and a local variable in a method have the same name, the local variable hides the instance
variable. The keyword this can be used to access the instance variable as shown in the
example below:

1 public class thisKeywordExample {


2
3 int a; // varaible 1
4
5 public void method() {
6 int a; // variable 2
7 a = 4; // varaible 1 will be changed
8 a = 3; // varaible 2 will be changed
9
10 }
11 }

(c) Why is a class known as a composite data type? [2]


Ans. A class is composed of instance variables which are of different data types. hence, a
class can be viewed as a composite data type which is composed of primitive and other
composite data types.

(d) Name the keyword that: [2]


i) is used for allocating memory to an array
ii) causes the control to transfer back to the method call
Ans. i) new
ii) return

(e) Differentiate between pure and impure functions. [2]


Ans. i) A pure function does not change the state of the object whereas an impure function
changes the state of the object by modifying instance variables.
ii) get functions are examples of pure functions and set functions are examples if impure
functions.

Question 3:

(a) Write an expression for [2]


Ans. (Math.pow(a+b),n)/(Math.sqrt(3)+b)

(b) The following is a segment of a program.

1 x = 1; y = 1;
2 if(n > 0)
3{
4 x = x + 1;
5 y = y - 1;
6}

What will be the value of x and y, if n assumes a value (i) 1 (ii) 0? [2]
Ans. i) 1 > 0 is true, so if block will be executed.
x=x+1=1+1=2
y=y–1=1–1=0
ii) 0 > 0 is false, so if block will not be executed and therefore, the values of x and y won’t
change.
x=1
y=1

(c) Analyze the following program segment and determine how many times the body
of loop will be executed (show the working). [2]

1 x = 5; y = 50;
2 while(x<=y)
3{
4 y=y/x;
5 System.out.println(y);
6}

Ans.

Iteration 1 : 5 <= 50 - true y = y / x = 50 / 5 = 10 10 will be


1
printed
Iteration 2 : 5 <= 10 - true y = y / x = 10 / 5 = 2 2 will be
2
printed
3 Iteration 3 : 5 <= 2 - false

The loop will be executed two times.

(d) When there are multiple definitions with the same function name, what makes
them different from each other? [2]
Ans. The function prototype make multiple definitions of a function different from each
other. Either the number, type or order or arguments should be different for the functions
having identical names.

Q3. (e) Given that int x[][] = { {2,4,6}, {3,5,7} };


What will be the value of x[1][0] and x[0][2] ? [2]
Ans. We can write the array as

As shown in the figure x[1][0] is 3 and x[0][2] is 6.

(f) Give the output of the following code segment when (i) opn = ‘b’ (ii) opn = ‘x’ (iii)
opn = ‘a’. [3]
1 switch(opn)
2{
3 case 'a':
4 System.out.println("Platform Independent");
5 break;
6 case 'b':
7 System.out.println("Object Oriented");
8 case 'c':
9 System.out.println("Robust and Secure");
10 break;
11 default:
12 System.out.println("Wrong Input");
13 }

Ans. i) Output will be

1 Object Oriented
2 Robust and Secure

As there is no break statement for case ‘b’, statements in case ‘c’ will also be printed when
opn = ‘b’.
ii) Output will be

1 Wrong Input

As ‘x’ doesn’t match with either ‘a’, ‘b’ or ‘c’, the default statement will be executed.
iii) Output will be

1 Platform Independent

(g) Consider the following code and answer the questions that follow: [4]

1 class academic
2{
3 int x, y;
4 void access()
5 {
6 int a, b;
7 academic student = new academic();
8 System.out.println("Object created");
9 }
10 }
i) What is the object name of class academic?
ii) Name the class variables used in the program?
iii) Write the local variables used in the program.
iv) Give the type of function used and its name.
Ans. i) student
ii) x and y
iii) a and b
iv) Type: Non Static
Name: access

Q3 (h) Convert the following segment into an equivalent do loop. [3]

1 int x,c;
2 for(x=10,c=20;c>10;c=c-2)
3 x++;

Ans.

1 int x, c;
2 x = 10;
3 c = 20;
4 do {
5 x++;
6 c = c - 2;
7 } while (c > 10);

Section B

Question 4
An electronics shop has announced the following seasonal discounts on the purchase of
certain items.

Purchase Amount in Rs. Discount on Laptop Discount on Desktop PC

0 – 25000 0.0% 5.0%

25001 – 57000 5.0% 7.6%

57001 – 100000 7.5% 10.0%

More than 100000 10.0% 15.0%


Write a program based on the above criteria to input name, address, amount of purchase
and type of purchase (L for Laptop and D for Desktop) by a customer. Compute and print
the net amount to be paid by a customer along with his name and address. [15]

(Hint: discount = (discount rate/100)* amount of purchase

Net amount = amount of purchase – discount)

Ans.

1 import java.util.Scanner;
2
3 public class Electronics {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 System.out.print("Enter name: ");
8 String name = scanner.nextLine();
9 System.out.print("Enter address: ");
10 String address = scanner.nextLine();
11 System.out.print("Enter type of purchase: ");
12 String type = scanner.nextLine();
13 System.out.print("Enter amount of purchase: ");
14 int amount = scanner.nextInt();
15 double discountRate = 0.0;
16 if (type.equals("L")) {
17 if (amount <= 25000) {
18 discountRate = 0;
19 } else if (amount >= 25001 && amount <= 57000) {
20 discountRate = 5.0;
21 } else if (amount >= 57001 && amount <= 100000) {
22 discountRate = 7.5;
23 } else if (amount > 100000) {
24 discountRate = 10.0;
25 }
26 } else if (type.equals("D")) {
27 if (amount <= 25000) {
28 discountRate = 5.0;
29 } else if (amount >= 25001 && amount <= 57000) {
30 discountRate = 7.6;
31 } else if (amount >= 57001 && amount <= 100000) {
32 discountRate = 10.0;
33 } else if (amount > 100000) {
34 discountRate = 15.0;
35 }
36 }
37 double discount = (discountRate / 100) * amount;
38 double netAmount = amount - discount;
39 System.out.println("Name: " + name);
40 System.out.println("Address: " + address);
41 System.out.println("Net Amount: " + netAmount);
42 }
43
44 }

Sample Output:

1 Enter name: Ram


2 Enter address: 12-5/6
3 Enter type of purchase: L
4 Enter amount of purchase: 200000
5 Name: Ram
6 Address: 12-5/6
7 Net Amount: 180000.0

Question 5:
Write a program to generate a triangle or an inverted triangle till n terms based upon the
user’s choice of triangle to be displayed. [15]

Example 1
Input: Type 1 for a triangle and
type 2 for an inverted triangle
1
Enter the number of terms
5
Output:
1
22
333
4444
55555

Example 2:
Input: Type 1 for a triangle and
type 2 for an inverted triangle
2
Enter the number of terms
6
Output:
666666
55555
4444
333
22
1

Ans.

1 import java.util.Scanner;
2
3 public class Traingle {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
System.out.print("Type 1 for a triangle and type 2 for an inverted
7
triangle: ");
8 int choice = scanner.nextInt();
9 System.out.print("Enter number of terms: ");
10 int n = scanner.nextInt();
11 if (choice == 1) {
12 for (int i = 1; i <= n; i++) {
13 for (int j = 1; j <= i; j++) {
14 System.out.print(i + " ");
15 }
16 System.out.println();
17 }
18 } else if (choice == 2) {
19 for (int i = n; i >= 1; i--) {
20 for (int j = 1; j <= i; j++) {
21 System.out.print(i + " ");
22 }
23 System.out.println();
24 }
25 }
26 }
27
28 }
Question 6:
Write a program to input a sentence and print the number of characters found in the
longest word of the given sentence.
For example is S = “India is my country” then the output should be 7. [15]

Ans.

1 import java.util.Scanner;
2
3 public class LongestWord {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 System.out.print("Enter a sentence: ");
8 String sentence = scanner.nextLine();
9 int longest = 0;
10 int currentWordLength = 0;
11 for (int i = 0; i < sentence.length(); i++) {
12 char ch = sentence.charAt(i);
13 if (ch == ' ') {
14 if (currentWordLength > longest) {
15 longest = currentWordLength;
16 }
17 currentWordLength = 0;
18 } else {
19 currentWordLength++;
20 }
21 }
22 if (currentWordLength > longest) {
23 longest = currentWordLength;
24 }

25 System.out.println("The longest word has " + longest + "


characters");
26 }
27 }

Question 7:

Write a class to overload a function num_calc() as follows: [15]


i) void num_calc(int num, char ch) with one integer argument and one character argument,
computes the square of integer argument if choice ch is ‘s’ otherwise finds its cube.

ii) void num_calc(int a, int b, char ch) with two integer arguments and one character
argument. It computes the product of integer arguments if ch is ‘p’ else adds the integers.

iii) void num_calc(String s1, String s2) with two string arguments, which prints whether the
strings are equal or not.

Ans.

1 public class Overloading {


2
3 public void num_calc(int num, char ch) {
4 if (ch == 's') {
5 double square = Math.pow(num, 2);
6 System.out.println("Square is " + square);
7 } else {
8 double cube = Math.pow(num, 3);
9 System.out.println("Cube is " + cube);
10 }
11 }
12
13 public void num_calc(int a, int b, char ch) {
14 if (ch == 'p') {
15 int product = a * b;
16 System.out.println("Product is " + product);
17 } else {
18 int sum = a + b;
19 System.out.println("Sum is " + sum);
20 }
21 }
22
23 public void num_calc(String s1, String s2) {
24 if (s1.equals(s2)) {
25 System.out.println("Strings are same");
26 } else {
27 System.out.println("Strings are different");
28 }
29 }
30 }

Question 8
Write a menu driven program to access a number from the user and check whether it is a
BUZZ number or to accept any two numbers and to print the GCD of them. [15]

a) A BUZZ number is the number which either ends with 7 is is divisible by 7.

b) GCD (Greatest Common Divisor) of two integers is calculated by continued division


method. Divide the larger number by the smaller; the remainder then divides the previous
divisor. The process is repeated till the remainder is zero. The divisor then results the GCD.

Ans.

1 import java.util.Scanner;
2
3 public class Menu {
4
5 public boolean isBuzzNumber(int num) {
6 int lastDigit = num % 10;
7 int remainder = num % 7;
8 if (lastDigit == 7 || remainder == 0) {
9 return true;
10 } else {
11 return false;
12 }
13 }
14
15 public int gcd(int a, int b) {
16 int dividend, divisor;
17 if (a > b) {
18 dividend = a;
19 divisor = b;
20 } else {
21 dividend = b;
22 divisor = a;
23 }
24 int gcd;
25 while (true) {
26 int remainder = dividend % divisor;
27 if (remainder == 0) {
28 gcd = divisor;
29 break;
30 }
31 dividend = divisor;
32 divisor = remainder;
33 }
34 return gcd;
35 }
36
37 public void menu() {
38 Scanner scanner = new Scanner(System.in);
39 System.out.println("1. Buzz Number");
40 System.out.println("2. GCD");
41 System.out.print("Enter your choice: ");
42 int choice = scanner.nextInt();
43 if (choice == 1) {
44 System.out.print("Enter a number: ");
45 int num = scanner.nextInt();
46 if (isBuzzNumber(num)) {
47 System.out.println(num + " is a buzz number");
48 } else {
49 System.out.println(num + " is not a buzz number");
50 }
51 } else if (choice == 2) {
52 System.out.print("Enter two numbers: ");
53 int num1 = scanner.nextInt();
54 int num2 = scanner.nextInt();
55 int gcd = gcd(num1, num2);
56 System.out.println("GCD: " + gcd);
57 } else {
58 System.out.println("Invalid Choice");
59 }
60 }
61
62 public static void main(String[] args) {
63 Menu menu = new Menu();
64 menu.menu();
65 }
66
67 }

Sample Output 1:

1 1. Buzz Number
2 2. GCD
3 Enter your choice: 1
4 Enter a number: 49
5 49 is a buzz number

Sample Output 2:

1 1. Buzz Number
2 2. GCD
3 Enter your choice: 2
4 Enter two numbers: 49 77
5 GCD: 7

Question 9
The annual examination results of 50 students in a class is tabulated as follows.

Roll no. Subject A Subject B Subject C

… … … …

Write a program to read the data, calculate and display the following:

a) Average mark obtained by each student.


b) Print the roll number and average marks of the students whose average mark is above
80.
c) Print the roll number and average marks of the students whose average mark is below
40.

Ans.

1 import java.util.Scanner;
2
3 public class StudentMarks {
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 int[] rno = new int[50];
8 int[] subjectA = new int[50];
9 int[] subjectB = new int[50];
10 int[] subjectC = new int[50];
11 double[] average = new double[50];
12 for (int i = 0; i < 50; i++) {
13 System.out.print("Enter Roll No: ");
14 rno[i] = scanner.nextInt();
15 System.out.print("Enter marks in subject A: ");
16 subjectA[i] = scanner.nextInt();
17 System.out.print("Enter marks in subject B: ");
18 subjectB[i] = scanner.nextInt();
19 System.out.print("Enter marks in subject C: ");
20 subjectC[i] = scanner.nextInt();
21 average[i] = (subjectA[i] + subjectB[i] + subjectC[i]) / 3.0;
22 }
23 System.out.println("Roll No - Average");
24 for (int i = 0; i < 50; i++) {
25 System.out.println(rno[i] + " - " + average[i]);
26 }
27 System.out.println("Students with average greater than 80");
28 for (int i = 0; i < 50; i++) {
29 if (average[i] > 80) {
30 System.out.println(rno[i] + " - " + average[i]);
31 }
32 }
33 System.out.println("Students with average less than 40");
34 for (int i = 0; i < 50; i++) {
35 if (average[i] < 40) {
36 System.out.println(rno[i] + " - " + average[i]);
37 }
38 }
39 }
40 }

Sample Output:

1 run:
2 Enter Roll No: 1
3 Enter marks in subject A: 100
4 Enter marks in subject B: 100
5 Enter marks in subject C: 97
6 Enter Roll No: 2
7 Enter marks in subject A: 10
8 Enter marks in subject B: 10
9 Enter marks in subject C: 10
10 Enter Roll No: 3
11 Enter marks in subject A: 50
12 Enter marks in subject B: 50
13 Enter marks in subject C: 50
14 ...
15 Roll No - Average
16 1 - 99.0
17 2 - 10.0
18 3 - 50.0
19 ...
20 Students with average greater than 80
21 1 - 99.0
22 Students with average less than 40
23 2 - 10.0
24 ...

Вам также может понравиться