Computer-Applications-ICSE-10th-Question Bank
Computer-Applications-ICSE-10th-Question Bank
Computer-Applications-ICSE-10th-Question Bank
(ICSE)
X
1. Name the programming technique that implements programs as an organised collection of
interactive objects.
a. Procedure Oriented Programming b. Modular
Programming
c. Object Oriented Programming d. None of these
Ans. c. Object Oriented Programming
2. Name the characteristics of Object Oriented Programming that hides the complexity and
provides a simple interface.
a. Encapsulation b.
Polymorphism
c. Abstraction d. Inheritance
Ans. c. Abstraction
3. Which among the following operator is used to access individual members of an object?
a. . (dot) b. + (plus)
c. – (minus) d. / (divide)
Ans. a. . (dot)
4. Which among the following modifier is used in a ‘class’?
a. public b. default
c. Both a and b d. None of
these
Ans. c. Both a and b
5. Which among the following is a valid class name?
a. Simple Interest b. SimpleInterest
c. 1SimpleInterest d.
Simple@Interest
Ans. b. SimpleInterest
6. Which among the following is a valid object name?
a. obj1 b. 1obj
c. Obj 1 d. Obj#1
Ans. a. obj1
7. Which among the following is a valid float literal?
2
a. 12.36f b. 12.36F
c. 12.36 d. Both a and
b
Ans. d. Both a and b
8. Which among the following is a valid octal integer literal?
a. 0178 b. 675
c. 0675 d. 0X675
Ans. c. 0675
9. Which among the following is a valid method of initialising?
a. boolean f=true; b. boolean
f=True;
c. boolean f=’true’; d. None of these
Ans. a. boolean f=true;
10. Which among the following is not a punctuator?
a. ; semicolon b. , comma
c. : colon d. . dot
Ans. d. . dot
11. Which among the following is not a primitive data type?
a. int b. float
c. String d. char
Ans. c. String
12. What is the largest possible value that can be stored in short data type?
a. 215-1 b. 231-1
c. 27-1 d. 263-1
Ans. a. 215-1
13. If a is of type int and b is of type float what would be the resultant data type of a+b?
a. int b. float
c. double d. short
Ans. b. float
B. State whether the following statements are True (T) or False (F).
1. Encapsulation refers to the art of hiding the complexities and giving a simple interface. F
2. Procedure Oriented Language follows top down approach. T
3. Java is an example of Object Oriented Language. T
3 Revision Tour I
4. Hiding the complexity and giving a simple interface is called Inheritance. F
5. Abstraction is same as encapsulation. F
6. An object is called a class factory. F
7. A class is an instance of an object. F
8. A class is a mechanism to implement encapsulation. T
9. Data members in a class is used to represent the characteristic of an object. T
10. The new operator is used to create an object. T
11. It’s a rule to have a class-name beginning in capital letter. F
Section A
Answer the following questions:
3. Define Encapsulation.
4
Ans. Encapsulation is a principle of Object Oriented Programming (OOP) that binds together
characteristics and behaviour of an object into a single unit represented by a class.
4. What is Inheritance?
Ans. Inheritance is the concept that when a class of objects is defined, any subclass that is defined can
inherit the definitions of one or more general classes.
6. State three differences between Procedure Oriented Language and Object Oriented
Languages.
Ans.
More importance is given to the program More importance is given to the data rather
rather than the data. than the program.
12. Write one difference between primitive data type and composite data type.
Ans.
5 Revision Tour I
Fundamental data type Composite data type
These are inbuilt data type provided by the These are data types created by the user using
Java Language. fundamental or user defined data type or both.
Object Class
Object is created through new keyword mainly Class is declared using class keyword e.g.
e.g. Student s1=new Student(); class Student{}
17. State the difference between a Boolean literal and a character literal.
6
Ans. A boolean literal consist of only two values i.e. true or false. A character literal on the other hand
is any character enclosed within single quotes.
21. Evaluate the value of n if the value of p=5 and q=19: int n = (q-p)>(p-q)?(q-p):(p-q); Ans.
n=14
22. What is meant by precedence of operators?
Ans. When several operations occur in an expression, each part is evaluated and resolved in a
predetermined order called operator precedence.
27. Write a statement in Java that will declare an object named si of the SimpleInterest class.
Ans. SimpleInterest si = new SimpleInterest();
7 Revision Tour I
28. Rewrite the following program after removing the errors, underlining each correction:
class My Class
{
int a, b;
void initialize( )
{
a=5;
b=6;
}
void show ( )
{
System.out.println (a+ ‘’ ‘’ + b);
}
static void main( )
{
My Class ob = new My Class ( );
ob. initialize ( ); show ( ). ob;
}
}
Ans. class MyClass
{
int a, b; void
initialize( )
{ a=5;
b=6;
}
void show ( )
{
System.out.println (a+ ‘’ ‘’ + b);
}
8
v. My@Class
Ans. i. Invalid, as a variable name cannot have a blank space. ii. Invalid, as a variable
name cannot begin with a digit. iv. Invalid, as a variable name cannot have a special
character, like #.
v. Invalid, as a variable name cannot have a special character, like @.
30. What is the resultant data type of the following mathematical expression? a+b*c-d
a. where a is int, b is int, c is float and d is float type
b. where a is float, b is long, c and d is of int type
c. where a is of double and b,c and d are of int type
d. where a is char and b,c and d are of int type
e. where a, b, c and d are of int type, however the expression is slightly modified as (a+b*c-d)/7.0
Ans. a. float
b. float
c. double
d. int
e. double
9 Revision Tour I
Ans. a. 5
15
b. 19
-37
c. 6
4
d. 14 14 27 16 15 35
e. true true
10 14
10
f. true true
8
g. false true
h. 10 17 17
true
32. What will be the output when the following code segment is executed?
System.out.println(“The king said \”Begin at the beginning!\ “to me”);
Ans. The king said “Begin at the beginning!” to me
34. What is the value of y after evaluating the expression given below? y+=++y + y-- + --y;
when int y=8
Ans. y=33
35. Give the output of the following expression:
a+=a++ + ++a + --a + a--; when a=7. Ans. a=39
37. What are the values of x and y when the following statements are executed? int a = 63, b =
36; boolean x = (a < b ) ? true : false; int y= (a > b ) ? a : b;
Ans. x=false y=63
38. What will be the result stored in x after evaluating the following expression? int x=4;
x += (x++) + (++x) + x; Ans. x=20
11 Revision Tour I
System.out.println(“j=” +j);
Ans. k= 6
j= 10
40. What is the result stored in x, after evaluating the following expression?
int x = 5; x = x++ * 2 + 3 * –x;
Ans. x=-8
43. State the number of bytes occupied by char and int data types.
Ans. char = 2 bytes int = 4
bytes
12
SECTION B
Programming Questions
1. Write a program to find the sum and difference between 25 and 16 using variables in different
lines.
Ans. class q1
{
static void main()
{
int a=25,b=16,s,d;
s=a+b;
d=a-b;
System.out.println(“Sum=”+s);
System.out.println(“Difference=”+d);
}
}
2. Write a program to find the product of 5, 7 and 12 using variables.
Ans. class q2
{
static void main()
{
int a=5,b=7,c=12,d;
d=a*b*c;
System.out.println(“Product=”+d);
}
}
3. Write a program to find the product of the sum and difference between 17 and 2 using
variables.
Ans. class q3
{
static void main()
{
int a=17,b=2,s,d;
s=a+b;
d=a-b;
System.out.println(“Sum=”+s);
System.out.println(“Difference=”+d);
}
}
13 Revision Tour I
4. Write a program to average of 36, 45 and 53 using variables of adequate data type.
Ans. class q4
{
static void main()
{
int a=36,b=45,c=53;
float av;
av=(float)(a+b+c)/3;
System.out.println(“Average=”+av);
}
}
5. Write a program using int variables to find the sum of three numbers say 15, 36 and 45 and
subtract the result from 100 using variables.
Ans. class q5
{
static void main()
{
int a=15,b=36,c=45,d=100,e;
e=d-(a+b+c);
System.out.println(“Answer=”+e);
}
}
6. Write a program to display the names of five fruits with a single System.out.println();
statement, but in different lines.
Ans. class q6
{
static void main()
{
System.out.println(“Apple\nOrange\nGuava\nBanana\nLemon”);
}
}
7. Write a program to find the sum, difference and product of 12.35 and 7.3 using variables with
a single System.out.println(); statement, however with horizontal tab space in the result.
Ans. class q7
{
static void main()
{
float a=12.35f,b=7.3f,s,d,p;
s=a+b;
d=a-b;
14
p=a*b;
System.out.println(“Sum=”+s);
System.out.println(“Difference=”+d);
System.out.println(“Product=”+p);
}
}
8. Write a program using float type variables to find the area and perimeter of a square whose side
is 12.5 cm.
Ans. class q8
{
static void main()
{
float s=12.5f,a,p;
a=s*s;
p=4*s;
System.out.println(“Area=”+a);
System.out.println(“Perimeter=”+p);
}
}
9. Write a program using int variables to find the area and perimeter of a rectangle of length 12cm
and breadth 8cm.
Ans. class q9
{
static void main()
{
int l=12,b=8,a,p;
a=l*b;
p=2*(l+b);
System.out.println(“Area=”+a);
System.out.println(“Perimeter=”+p);
}}
10. Write a program using variables to find the profit and profit percent of a certain transaction
where
S.P.= `10000 and C.P.= ` 7000.
Ans. class q10
{
static void main()
{
15 Revision Tour I
float sp=10000,cp=7000,p,pp;
p=sp-cp;
pp=p/cp*100;
System.out.println(“Profit=”+p);
System.out.println(“Profit Percent=”+pp);
}}
11. Write a program to input the Principal, Rate and Time and calculate the Simple Interest.
}}
16
13. Write a program to initialise two integer variables a and with 5 and 6 respectively and
interchange them. Thus after interchanging, a and b will be 6 and 5 respectively.
Ans. class q13
{
static void main()
{
int a=5,b=6,c;
System.out.println(“Before Interchange: a=”+a+“b=”+b);
c=a; a=b; b=c;
System.out.println(“After Interchange: a=”+a+“b=”+b);
}}
14. Write a program to initialise three int variables a, b and c with 234, 456 and 712 and store the
sum of the last digits of the variables into d and display it.
Ans. class q14
{
static void main()
{
int a=234,b=456,c=712,d;
d=a%10+b%10+c%10;
System.out.println(“Sum=”+d);
}}
15. Write a program to initialise an int variable a with 76498 and from it extract the first digit and
store it into a variable f and extract the last digit into a variable l and display both these digits.
Ans. class q15
{
static void main()
{
int a=76498,f,l;
f=a/10000; l=a%10;
System.out.println(“First Digit=”+f);
System.out.println(“Last Digit=”+l);
}}
16. Write a program using ternary operator to check whether 27 is a multiple of 3 or not.
Ans. class q16
{
static void main()
{
System.out.println((27%3==0)?“Multiple of 3”:“Not a multiple of 3”);
}
17 Revision Tour I
}
18
a. Missing semicolon b. Mismatched braces in classes and methods.
c. Misspelled keywords and identifiers. d. Addition is required but subtraction is performed.
Ans. d. Addition is required but subtraction is performed.
19 Revision Tour I
8. Which among the following represents a syntax error?
a. Dividing an integer by zero.
b. Accessing an element that is out of bounds of an array.
c. Trying to store a value which is incompatible to a certain data-type.
d. Missing semicolon
Ans. d. Missing semicolon
9. If the data that is to take part in a calculation in a method is fixed, which form of input is
necessary?
a. Initialisation b. Parameterised
input
c. Scanner input d. None of these
Ans. a. Initialisation
10. In case you need to give a proper message (prompt string) before taking an input from the user,
which would be the most preferable method?
a. Parameterised input b. Initialisation
c. Scanner input d. None of
these
Ans. c. Scanner input
C. State whether the following statements are True (T) or False (F).
1. Scanner class is present in the java.lang package. F
2. Math.abs( ) is used to find the absolute value of a number. T
3. The return type of Math.sqrt( ) function is float. F
4. The fraction 1/2 will evaluate to 0.5. F
20 Revision Tour II
5. The continue statement in a switch block is used to avoid fall through. F
6. The default statement is essential in a switch block. F
7. The for loop is an entry controlled loop. T
8. The while loop is an exit controlled loop. F
9. The do-while loop is generally used when the number of iterations is known. F 10. You can have
only the for loop as the nested loops. F
SECTION A
Answer the following questions.
3. What are the different types of errors that may occur in a Java program?
Ans. Syntax Error, Logical Error and Run-time Error.
21 Revision Tour II
Ans. A comment is a programmer-readable explanation or annotation in the source code of a computer
program.
Types: Single-line comment and Multiline comment
7. What are conditional statements? With which commands do you implement conditional
statement in Java?
Ans. Conditional construct are specific statements that allow us to check a condition and execute certain
parts of code depending on whether the condition is true or false.
Implementation is done using: if, if-else, if-else if-else, switch-case and ternary operators.
9. What is the difference between the Scanner class functions next() and nextLine()?
Ans. next() can read the input only till the space. It can’t read two words separated by space. Also, next()
places the cursor in the same line after reading the input. nextLine() reads input including space
between the words (that is, it reads till the end of line \n).
12. What are logical operators? Explain each of them with the help of an example.
Ans. The logical operators are used to combine simple relational statements into more complex
expressions.
The test expression or condition is checked The test expression or condition is checked
before entering the loop. after entering the loop.
It the test expression evaluates to false, the Even if the test expression evaluates to false,
loop doesn’t get executed. the loop gets executed atleast once.
15. Give the general syntax of a while-loop. How do you create infinite loops using a while-loop
structure?
Ans. The syntax of a while loop is, while
(condition or test-expression)
{
bodyoftheloop;
}
One of the method of creating an infinite loop is to write ‘true’ in the test-expression of the loop.
while(true)
System.out.println(“Infinite”);
16. Give the general syntax of a do-while loop. How do you create infinite loops using do-while loop
structure?
Ans. The syntax of the dowhile loop is: do
{
statement;
}while (condition);
Infinite loop using do-while loop: do
{
System.out.println(“Infinite”);
}while(true);
17. Compare loops according to its usage.
Ans. Generally the for-loop is used when the number of iterations is known. The while loop is generally
used when the number of iterations is not known. The do-while loop is generally used when it is
necessary to execute the loop at least once.
18. What are Nested-loops? Give an example of a nested for-loop to show its functionality.
Ans. A loop within a loop is called a nested loop.
Example of a nested loop is:
public class Loops
{
23 Revision Tour II
static void Nested()
{
int x , y;
for(x=1;x<=3;x++)
{
for(y=1; y<=3 ; y++)
{
System.out.println(x+” “+y);
}
}
}
}
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Here x starts from 1 and then enters the inner loop where y too, starts from 1. That is why we get 1 and
1 as the first result. As told earlier the inner loop should finish its iteration first. Therefore y
continues iteration till it reaches 3, in the meanwhile x continues to be at 1. That is why the next
two outputs are 1 and 2 & 1 and 3. After it comes out of the inner loop the value of x increments by
1. Thus x is 2 and y starts back from 1 again and it reaches 3 while x continues to be 2. Hence the
next result is 2 & 1, 2 & 2 and 2 & 3. Then x reaches 3 and y starts from 1, hence we get the result 3
& 1, 3 & 2 and 3 & 3. Since x is exhausted i.e. it has already iterated for 3 times, the control comes
out of it and the program ends.
24. Give the output and determine how many times the loop will execute:
x=1; y=1;
while(x<=y)
{ y = y/x;
System.out.println(y);
}
Ans. x=1; y=1; x<=y -> the loop
executes once. y=y/x =1/1=1
x<=y -> the loop executes next time
The entire process will continue infinite number of times, with the output as 1 in different lines.
25 Revision Tour II
case 1:
System.out.println(“good”); break; case 2:
System.out.println(“better”);
break; case 3:
System.out.println(“best”);
break; default:
System.out.println(“invalid”);
}
27. Rewrite the following using ternary operator:
if (bill >10000 ) discount = bill * 10.0/100; else discount = bill *
5.0/100;
Ans. discount=(bill >10000 ) ? bill * 10.0/100: bill * 5.0/100;
28. Rewrite the following program segment using the if .. else statement.
comm = (sale>15000)?sale*5/100:0; Ans.
if (sale>15000)
comm=sale*5/100 else
comm=0;
29. Rewrite the following using ternary operator :
if(x%2==0)
System.out.print(“EVEN”); else
System.out.print(“ODD”); Ans.
System.out.print((x%2==0)?”EVEN”:“ODD”);
30. Convert the following segment into an equivalent do loop. int x,c;
for (x=10, c=20; c>=10; c = c – 2) x++;
Ans.
int x=10,c=20;
do {
x++;
c=c-2;
}while(c>=10);
31. Give the output of the following program segment and also mention how many times the loop is
executed: int i; for (i = 5 : i > 10; i ++)
System.out.println(i);
System.out.println(i * 4); Ans.
Output:
20
The loop do not execute, as the condition results to false.
32. Convert the following while loop to the corresponding for loop:
27 Revision Tour II
WIN
36. 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.
int k=1, i=2; while
(++i<6) k*=i;
System.out.println(k);
Ans. The loop executes 3 times.
Output:
60
37. How many times will the following loop execute? What value will be returned?
int x = 2, y = 50;
do
{
++x; y- = x++;
}
while(x <= 10); return y;
Ans. The loop will execute 5 times. Value
returned is 15.
38. 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?
int p=200;
while(true)
{
if(p<100) break;
p=p-20;
}
System.out.println(p);
Ans. The loop executes 7 times.
Output:
80
39. 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. Ans.
i. Runtime error ii.
Logical error iii. Syntax
error
40. Give the output of the following program segment:
42. What are the final values stored in variables x and y below?
double a = - 6.35; double b = 14.74; double
x = Math.abs(Math.ceil(a)); double y =
Math.rint(Math.max(a,b)); Ans. x=6.0 and y=15.0
29 Revision Tour II
(i) How many times does the loop execute?
(ii) What is the range of possible values stored in the variable number?Ans.
(i) The loops executes for 6 times.
(ii) The possible range of values stored in ‘number’ is 0 to 9.
46. What are the values of a and b after the following function is executed, if the values passed are 30
and 50:
void paws(int a, int b)
{
a = a + b; b=a
– b;
a = a – b;
}
Ans. a=50 and b=30
47. Write the output of the following code segment:
char ch; int x = 97;
do
{
ch = (char)x;
System.out.print(ch+“ ”);
if(x%10==0) break;
++x;
}
while(x<=100); Ans.
Output: abcd
48. Analyze the given program segment and answer the following questions:
(i) Write the output of the program segment.
(ii) How many times does the body of the loop gets executed?
for(int m=5; m<=20; m+=5)
{
if(m%3 == 0) break;
else
if(m%5 == 0) System.out.println(m);
continue;
}
Ans. i. Output:
5 10
ii. The loop executes 3 times.
49. Give the output of the following program segment and also mention the number of times the
loop is executed:
31 Revision Tour II
o) 5.0
p) 4
51. Write equivalent Java expressions for the following:
Ans.
a. Math.sqrt(a+b)
b. 1/3.0+Math.pow(a,3)+1/3.0*Math.pow(b,3)
c. s=u*t+1/2.0*a*Math.pow(t,2)
d. d=Math.sqrt(l*l+b*b);
e. (-b+Math.sqrt(b*b-4*a*c))/(2*a)
f. (Math.pow(a,3)+Math.pow(b,3))/ (Math.pow(a,3)-Math.pow(b,3))
g. Math.abs((a-b)/(a+b))
h. Math.cbrt((a+b)/(a*b))
i. Math.pow(a+b.n)/Math.sqrt(3+b)
j. z=(5*x*x*x+2*y)/(x+y);
k. Math.sqrt(2*a*s+u*u)
l. Math.sqrt(3*x+x*x)/(a+b)
m. (a*a+b*b)/(2*a*b)
n. T=Math.sqrt(A*A+B*B+C*C);
o. a*Math.pow(x,5)+b*Math.pow(x,3)+c
1. Write a program to input the area of a square and find its perimeter.
Ans. import java.util.*; class Sol1
{
static void main()
{
Scanner sc=new Scanner(System.in);
double a,s,p;
System.out.println(“Enter the area of a square:”);
a=sc.nextDouble(); s=Math.sqrt(a);
p=4*s;
System.out.println(“Perimeter=”+p);
}
}
2. Write a program to input the length and breadth of a rectangle and find its diagonal.
33 Revision Tour II
b=sc.nextInt(); if(a%7==0
&& b%7==0)
System.out.println(“Both are multiples of 7”); else
System.out.println(“Both are not multiples of 7”);
}}
4. Write a program to pass 2 integer numbers as parameters. If either of the two numbers is 0, display
invalid entry and the program should end, if it is valid entry, divide the larger number with the
smaller number and display the result.
Ans.
class Sol4
{
static void divide(int a,int b)
{
if(a==0 || b==0)
System.out.println(“Invalid Entry”); else
{ float q;
if(a>b)
q=(float)a/b; else
q=(float)b/a;
System.out.println(“Quotient:”+q);
}
}
}
5. Write a program to input 3 unique integers and print the smallest among them.
Ans. import java.util.*; class Sol5
{
static void main()
{
Scanner sc=new Scanner(System.in); int
a,b,c;
System.out.println(“Enter 3 integers:”);
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt(); if(a<b &&
a<c)
System.out.println(“Smallest:”+a); else
if(b<a && b<c)
System.out.println(“Smallest:”+b); else
System.out.println(“Smallest:”+c);
35 Revision Tour II
if(a<b+c && b<a+c && c<a+b)
{
if(a==b && b==c)
System.out.println(“Equilateral triangle”);
else if(a==b || b==c || c==a)
System.out.println(“Isosceles triangle”);
else
System.out.println(“Scalene triangle”);
} else
System.out.println(“Cannot form a triangle”);
}
}
8. Write a program to accept three sides of a triangle as parameter and check whether it can form a
triangle or not. If it forms a triangle, check whether it is an acute angled, obtuse angled or right-
angled triangle.
(Hint: To form a triangle, each side should be less the sum of the other two sides..
To form an acute angled triangle the square of every side should be less than the sum of the squares of
the other two sides.
To form an obtuse angled triangle the square of any side should be greater than the sum of the
squares of the other two sides.
To form an right angled triangle the square of any side should be equal to the sum of the
squares of the other two sides.)
Ans. import java.util.*; class Sol8
{
static void main()
{
Scanner sc=new Scanner(System.in); int
a,b,c;
System.out.println(“Enter 3 sides:”);
a=sc.nextInt(); b=sc.nextInt();
c=sc.nextInt();
if(a<b+c && b<a+c && c<a+b)
{
if(a*a<b*b+c*c && b*b<a*a+c*c && c*c<a*a+b*b)
System.out.println(“Acute angled triangle”); else
if(a*a>b*b+c*c || b*b>a*a+c*c || c*c>a*a+b*b)
System.out.println(“Obtuse angled triangle”); else
System.out.println(“Right angled triangle”);
} else
System.out.println(“Cannot form a triangle”);
37 Revision Tour II
Scanner sc=new Scanner(System.in); float
tc,d,ap;
System.out.println(“Enter the total cost of the items:”);
tc=sc.nextFloat(); if(tc<=2000) d=5/100f*tc;
else if(tc>=2001 && tc<=5000)
d=25/100f*tc;
else if(tc>=5001 && tc<=10000)
d=35/100f*tc; else
d=50/100f*tc; ap=tc-d;
System.out.println(“Amount Payable:”+ap);
}
}
11. An electronics shop has announced the following seasonal discounts on the purchase of certain
items.
Purchase Amount is` Discount on Laptop Discount on desktop PC
Write a program based on the above criteria, to input name, address, amount of purchase and the 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.
(Hint: discount = (discount rate/100)* amount of purchase
Net amount = amount of purchase – discount)
Ans. import java.util.*; class Sol11
{
static void main()
{
Scanner sc=new Scanner(System.in);
String name, add;
float a,d=0,na=0; char
type;
System.out.println(“Enter the name:”); name=sc.nextLine();
System.out.println(“Enter the address:”);
add=sc.nextLine();
System.out.println(“Enter the amount of purchase:”); a=sc.nextFloat();
39 Revision Tour II
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.
Ans. import java.util.*; class
Sol12
{
static void main()
{
Scanner sc=new Scanner(System.in);
int age; String gender; float ti,it;
System.out.println(“Enter the age:”); age=sc.nextInt();
System.out.println(“Enter the gender:”); gender=sc.nextLine();
sc.nextLine();//dummy input
System.out.println(“Enter the taxable income:”);
ti=sc.nextFloat();
if(age>65 && gender.equals(“female”)) System.out.println(“Wrong
category”); else
{
if(ti<=160000) it=0;
else if(ti>160000 && ti<=500000) it=10/100f*(ti-160000);
else if(ti>500000 && ti<=800000) it=20/100f*(ti-500000)+34000;
else
it=30/100f*(ti-800000)+94000; System.out.println(“Income Taxable:”+it);
}
}
}
13. Write programs for each of the following to print the series:
a. 2, 4, 6, 8, 10, … , 100
b. 99, 97, 95, 93, 91, …, 1
c. 7, 14, 21, 28, 35, …, 70
d. 80, 72, 64, 56, 48, …, 8
e. 1, 4, 9, 16, 25, 36, …. 100
f. 0, 3, 8, 15, 24, 35, …, 99
g. 1, 2, 4, 7, 11, 16, 22, 29, …, upto n terms. [Take n as input]
h. 2, 4, 8, 14, 22, 32, 44, 59, …, upto n terms. [Take n as input]
i. 1, 2, 5, 10, 17, 26, 37, 50, …, upto n terms. [Take n as input]
j. 1, 1, 2, 3, 5, 8, 13, 21, 34, …, upto n terms. [Take n as input]
k. 1, 2, 5, 12, 29, 70, 169, …, upto n terms. [Take n as input]Ans.
a) class Sol13
{
static void main()
{
b) class Sol13
{ static void main()
{
int i;
for(i=99;i>=1;i-=2)
{
System.out.print(i+“ ”);
}
}
}
c) class Sol13
{ static void main()
{
int i;
for(i=7;i<=70;i+=7)
{
System.out.print(i+“ ”);
}
}
}
d) class Sol13
{ static void main()
{
int i;
for(i=80;i>=8;i-=8)
{
System.out.print(i+“ ”);
}
}
}
e) class Sol13
41 Revision Tour II
{
static void main()
{
int i;
for(i=1;i<=10;i++)
{
System.out.print((i*i)+“ ”);
}
}
}
f)
class Sol13
{
static void main()
{
int i;
for(i=1;i<=10;i++)
{
System.out.print((i*i-1)+“ ”);
}
}
}
g) import java.util.*;
class Sol13
{
static void main()
{
int i,n,s=1;
Scanner sc=new Scanner(System.in); System.out.print(“Enter the number of terms:”);
n=sc.nextInt();
for(i=1;i<=n;i++)
{
System.out.print(s+“ ”);
s=s+i;
}
}
}
h) import java.util.*;
class Sol13
i)
import java.util.*;
class Sol13
{
static void main()
{
int i,n,s=1,c=1;
Scanner sc=new Scanner(System.in); System.out.print(“Enter the number of terms:”);
n=sc.nextInt();
for(i=1;i<=n;i++)
{
System.out.print(s+“ ”);
s=s+c; c=c+2;
}
}
} j) import java.util.*;
class Sol13
{
static void main()
{
int i,n,f=1,s=0,t;
Scanner sc=new Scanner(System.in);
System.out.print(“Enter the number of terms:”); n=sc.nextInt();
for(i=1;i<=n;i++)
{
t=f+s;
System.out.print(t+“ ”);
f=s; s=t;
43 Revision Tour II
}
}
}
k) import java.util.*;
class Sol13
{
static void main()
{
int i,n,f=1,s=0,t;
Scanner sc=new Scanner(System.in);
System.out.print(“Enter the number of terms:”); n=sc.nextInt();
for(i=1;i<=n;i++)
{
t=f+2*s;
System.out.print(t+“ ”);
f=s; s=t;
}
}
}
14. Write a program to find the sum of all 3-digit even natural numbers.
Ans. class Sol14
{
static void main()
{ int i,s=0;
for(i=100;i<=998;i+=2)
{
s+=i;
}
System.out.print(“Sum=”+s);
}}
15. Write a program to find the sum of all 3 digit odd natural numbers, which are multiples of 5.
Ans. class Sol15
{
static void main()
{ int i,s=0;
for(i=101;i<=999;i+=2)
{
If(i%5==0)
s+=i;
45 Revision Tour II
}}
18. Write a program to input 10 integers and find the sum of two-digit as well as three-digit numbers
separately.
Ans.
import java.util.*;
class Sol18
{
static void main()
{
int i,n,s2=0,s3=0;
Scanner sc=new Scanner(System.in); System.out.print(“Enter
10 integers:”);
for(i=1;i<=10;i++)
{
n=sc.nextInt();
if(n>=10 && n<=99)
s2+=n;
if(n>=100 && n<=999)
s3+=n;
}
System.out.println(“Sum of 2 digit numbers:”+s2);
System.out.println(“Sum of 3 digit numbers:”+s3);
}
}
19. Write a program to input 10 integers and display the largest as well as the smallest integer.
Ans. import java.util.*; class
Sol19
{
static void main()
{
int i,n,lar=0,sma=0;
Scanner sc=new Scanner(System.in); System.out.print(“Enter
10 integers:”);
for(i=1;i<=10;i++)
{
n=sc.nextInt();
if(i==1)
lar=sma=n;
else
{
if(n>lar)
47 Revision Tour II
static void main()
{
int i,n,f=0,p=0;
Scanner sc=new Scanner(System.in); System.out.print(“Enter
10 integers:”);
for(i=1;i<=10;i++)
{
n=sc.nextInt();
if(i==1)
p=n; else
{
if(n!=p)
f=1; }
} if(f==0)
System.out.println(“All numbers are same”); else
System.out.println(“All numbers are not same”);
}
}
22. Write a program to input 10 integers and check whether the entered numbers are in ascending
order or not.
For Example, INPUT:
Enter 10 numbers: 10 12 13 25 45 55 67 78 106 122 OUTPUT:
The numbers are in ascending order.
INPUT:
Enter 10 numbers: 25 34 56 67 12 32 43 21 23 111 OUTPUT:
The numbers are not in ascending order.
Ans. import java.util.*; class
Sol22
{
static void main()
{
int i,n,f=0,p=0;
Scanner sc=new Scanner(System.in); System.out.print(“Enter
10 integers:”);
for(i=1;i<=10;i++)
{
n=sc.nextInt();
if(i==1)
p=n; else
{ if(n<p)
f=1; p=n;
}
49 Revision Tour II
Ans. import java.util.*; class
Sol25
{
static void main()
{
int i,n,s=0;
Scanner sc=new Scanner(System.in);
System.out.print(“Enter an integer:”);
n=sc.nextInt();
for(i=1;i<n;i++)
{
if(n%i==0)
s+=i;
}
if(s==n)
System.out.println(“Perfect Number”); else
if(s>n)
System.out.println(“Abundant Number”); else
System.out.println(“Deficient Number”);
}}
26. Write a program to input two integers and check whether it forms an amicable pair or not. An
amicable pair is such that, the sum of the factors excluding itself of one number is the other
number and sum of the factors excluding itself of the other number is this number.
Example, (220, 284). Since sum of factors excluding itself of :
220= 1+2+4+5+10+11+20+22+ 44+55+110=284 284= 1+
2+4+71+142=220.
Ans. import java.util.*; class
Sol26
{
static void main()
{
int a,b,sa=0,sb=0;
Scanner sc=new Scanner(System.in); System.out.print(“Enter
2 integers:”);
a=sc.nextInt(); b=sc.nextInt();
for(i=1;i<a;i++)
{
if(a%i==0)
sa+=i;
}
for(i=1;i<b;i++)
51 Revision Tour II
01 11 121
101 112 12321
1001 1123 1234321
10001 11235 123454321
100001 112358 12345654321
xxiv. xxv.
xxvi. 1 xxvii. 1
11 23
121 456
1331 7 8 9 10
14641 11 12 13 14 14
1 5 10 5 1
1 6 15 15 6 1
Ans.
i)
class Sol27
{
static void main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
53 Revision Tour II
ii)
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=5;j>=i;j--)
{
System.out.print(j);
}
System.out.println();
}
}
}
iii)
class Sol27
{ static void
main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=i;j>=1;j--)
{
System.out.print(j);
}
System.out.println();
}
}
}
System.out.print(j);
}
System.out.println();
}
}
}
v) class Sol27
{ static void
main()
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=i;j>=1;j--)
{
System.out.print(j);
}
System.out.println();
}
}
}
System.out.print(i);
55 Revision Tour II
}
System.out.println();
}
}
}
vii)
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
System.out.print(i);
}
System.out.println();
}
}
}
viii)
class Sol27
{ static void
main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=i;j<=5;j++)
{
System.out.print(i);
}
System.out.println();
}
}
} ix) class
Sol27
System.out.print(i);
}
System.out.println();
}
}
}
x) class
Sol27
{ static void
main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(“*”);
}
System.out.println();
}
}
}
xi) class
Sol27
{ static void
main()
57 Revision Tour II
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
System.out.print(“*”);
}
System.out.println();
}
}
}
xii)
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
if(i==j || i+j==6)
System.out.print(“*”);
else
System.out.print(“ ”);
}
System.out.println();
}
}}
xiii)
class Sol27
{ static void
main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
59 Revision Tour II
}}
xviii)
class Sol27
{ static void main()
{
int i,j,f;
for(i=1;i<=6;i++)
{
f=0; for(j=1;j<=2*i-1;j++)
{ if(j<=i) ++f; else --f;
System.out.print(f);
}
System.out.println();
}
}}
61 Revision Tour II
{
int i,j; for(i=6;i>=1;i--)
{
for(j=i;j<=5;j++) System.out.print(“ ”); for(j=i;j>=1;j--)
System.out.print(j); for(j=2;j<=i;j++) System.out.print(j);
System.out.println();
}
}}
63 Revision Tour II
{
for(j=1;j<=11;j++)
{
if(i+j>=7 && j-i<=5) System.out.print(“*”); else
System.out.print(“ ”);
}
System.out.println();
}
}}
65 Revision Tour II
r=r*10+d;
}
c2=0;
for(j=1;j<=r;j++)
{
if(r%j==0)
c2++;
}
if(c1==2 && c2==2)
System.out.println(i+“ ”);
}
}
}
30. Input an integer and form a new number where the digits are in ascending order.
Ans. import java.util.*;
class Sol30
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,j,n,s=0,c=0,d;
System.out.println(“Enter a number:”);
n=sc.nextInt();
for(i=9;i>=0;i--) {
for(j=n;j>0;j/=10)
{
d=j%10;
if(d==i)
s=s+d*(int)Math.pow(10,c++);
}
}
System.out.println(“New Number:”+s);
}
}
31. Write a program to pass an integer as argument and print the largest as well as smallest digit.
Ans.
class Sol31
{
static void main(int n)
{
int i,d,max=0,min=0;
67 Revision Tour II
INPUT: Enter an integer: 1234 OUTPUT:
13
Ans.
import java.util.*;
class Sol33
{
static void main()
{
Scanner sc=new Scanner(System.in); int
i,d,n,s=0,c=0;
System.out.println(“Enter a number:”);
n=sc.nextInt();
for(i=n;i>0;i/=10)
{
d=i%10; if(d%2==1)
s=s+d*(int)Math.pow(10,c++);
}
System.out.println(“New Number:”+s);
}
}
34. Write a program to pass an integer as argument and print the number by having the digits
arranged in ascending order.
Ans.
class Sol34
{
static void main(int n)
{
int i,j,s=0,c=0,d;
for(i=9;i>=0;i--)
{
for(j=n;j>0;j/=10)
{
d=j%10;
if(d==i)
s=s+d*(int)Math.pow(10,c++);
}
}
System.out.println(“New Number:”+s);
}
}
69 Revision Tour II
}
}
37. Write a program to input an integer and check whether it is an automorphic, trimorphic or
triautomorphic number or not. A number n is said to be automorphic, if its square ends in n. For
instance 5 is automorphic, because 52= 25, which ends in 5, 25 is automorphic, because 252=625,
which ends in 25. A number n is called trimorphic if n3 ends in n. For example 493, = 117649, is
trimorphic. A number n is called tri-automorphic if 3n2 ends in n; for example 667 is tri-
automorphic because 3 × 6672, = 1334667, ends in 667. Ans. import java.util.*; class Sol37
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,j,f=0,n;
System.out.println(“Enter a number:”);
n=sc.nextInt();
for(i=n;i>0;i/=10)
f++;
if((n*n)%(int)Math.pow(10,f)==n)
System.out.println(“Automorphic Number”);
else if((n*n*n)%(int)Math.pow(10,f)==n)
System.out.println(“Trimorphic Number”); else
if((3*n*n)%(int)Math.pow(10,f)==n)
System.out.println(“Tri-automorphic Number”);
else
System.out.println(“Not Automorhic,Trimorphic or Tri-automorphic Number”);
}
}
38. Write a program to input a number and check whether it is a happy number or not. If you
iterate the process of summing the squares of the decimal digits of a number and if this
process terminates in 1, then the original number is called a happy number. For example
7=> (72)=49=> (42+92)=97=>(92 +72)=130 =>(12 +32+02)=10 =>(12+02)= 1.
Ans.
import java.util.*;
class Sol38
{
static void main()
{
Scanner sc=new Scanner(System.in);
int d,s,n;
System.out.println(“Enter a number:”);
n=sc.nextInt();
71 Revision Tour II
if(n==1)
System.out.println(“Magic Number”);
else
System.out.println(“Not a Magic Number”);
}
}
40. Write a program to input an integer and check whether it is Harshad or Niven number or not.
A number is said to be Harshad if it is divisible by the sum of the digits of that number, example
126 and 1729. Ans.
import java.util.*;
class Sol40
{
static void main()
{
Scanner sc=new Scanner(System.in);
int d,s=0,n,i;
System.out.println(“Enter a number:”);
n=sc.nextInt();
for(i=n;i>0;i/=10)
{
d=i%10;
s+=d;
}
if(n%s==0)
System.out.println(“Harshad Number”);
else
System.out.println(“Not a Harshad Number”);
}
}
41. Write a program to input a number and check whether it is a Kaprekar number or not. Take a
positive whole number n that has d number of digits. Take the square n and separate the
result into two pieces: a right-hand piece that has d digits and a left-hand piece that has
either d or d-1 digits. Add these two pieces together. If the result is n, then n is a Kaprekar
number. Examples are 9 (92 = 81, 8 + 1 = 9), 45 (452 = 2025, 20 + 25 = 45), and 297 (2972 =
88209, 88 + 209 = 297).
Ans. import java.util.*;
class Sol41
{
static void main()
{
73 Revision Tour II
43. Write a program to input two integers and find their Highest Common Factor(H.C.F).
For Example, INPUT:
Enter 2 integers:
12
8 OUTPUT:
H.C.F. = 4 Ans.
import java.util.*;
class Sol43
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,a,b,l=0;
System.out.println(“Enter 2 numbers:”);
a=sc.nextInt(); b=sc.nextInt();
for(i=a;i<=a*b;i++)
{
if(i%a==0 && i%b==0)
{ l=i;
break;
}
}
System.out.println(“HCF.:”+(a*b)/l);
}
}
44. Write a menu driven class to accept a number from the user and check whether it is a
Palindrome or a Perfect number.
(a) Palindrome number- (a number is a Palindrome which when read in reverse order is same as
read in the right order) Example: 11, 101, 151, etc.
(b) Perfect number- (a number is called Perfect if it is equal to the sum of its factors other than the
number itself.) Example: 6=1+2+3 Ans.
import java.util.*;
class Sol44
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,s=0,ch,d;
System.out.println(“M E N U”);
System.out.println(“1. Palindrome Number”);
75 Revision Tour II
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,r,ch,d;
System.out.println(“M E N U”);
System.out.println(“1. Buzz Number”);
System.out.println(“2. GCD”);
System.out.println(“Enter your choice:”);
ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println(“Enter a number:”);
n=sc.nextInt();
if(n%10==7 || n%7==0)
System.out.println(“Buzz Number”);
else
System.out.println(“Not a Buxx
number”); break; case 2:
System.out.println(“Enter 2
numbers:”); n=sc.nextInt();
d=sc.nextInt();
do
{
r=n%d;
if(r!=0)
{
n=d;
d=r;
}
}while(r!=0);
System.out.println(“GCD:”+d);
break; default:
System.out.println(“Invalid choice!”);
}
}
}
46. Write a program to find the sum of the following series:
S=1+(1+2)+(1+2+3)+(1+2+3+4)+(1+2+3+4+5)+…+(1+2+3+4+…+10)
77 Revision Tour II
48. Write a program to find the sum of series, taking the value of ‘a’ and ‘n’ from the user.
Ans.
import java.util.*;
class Sol48
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,n,i,f=1; float
sum=0;
System.out.println(“Enter the value of a:”); a=sc.nextInt();
System.out.println(“Enter the value of n:”); n=sc.nextInt();
for(i=1;i<=n;i++)
{
sum+=(float)(a+f)/(f+1);
f+=2;
}
System.out.println(“Sum:”+sum);
}
}
49. Write a program to compute and display the sum of the following series:-
Ans.
import java.util.*;
class Sol49
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a=1,n,i,p=1;
float sum=0;
System.out.println(“Enter the value of n:”);
n=sc.nextInt();
for(i=1;i<=n;i++)
{
a=a+(i+1);
p=p*(i+1);
79 Revision Tour II
} break; case 2:
for(i=n;i>=1;i--)
{
for(j=1;j<=i;j++)
{
System.out.print(i);
}
System.out.println();
} break; default:
System.out.println(“Invalid choice!”);
}
}
}
51. 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).
Example: 145 is a special number, because l! + 4! + 5! = 1+24+120 = 145
(Where ! stands for factorial of the number and the factorial value of a number is the product of
all integers from 1 to that number, example 5! = 1*2*3*4*5 = 120).
Ans.
import java.util.*;
class Sol51
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,j,ch,d,f,s=0;
System.out.println(“Enter a number:”);
n=sc.nextInt();
for(i=n;i>0;i/=10)
{
d=i%10;
f=1;
for(j=1;j<=d;j++)
f=f*j; s+=f;
}
if(s==n)
System.out.println(“Special Number”);
else
Ans.
import java.util.*;
class Sol52
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,ch;float s=0;
System.out.println(“M E N U”);
System.out.println(“1. First Series”);
System.out.println(“2. Second Series”);
System.out.println(“Enter your choice:”);
ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println(“Enter the number of terms:”);
n=sc.nextInt();
for(i=1;i<=n;i++)
{
s=i*i-1;
System.out.print(s+“ ”);
}
break; case
2:
for(i=1;i<=19;i+=2)
{
s+=(float)i/(i+1);
}
System.out.println(“Sum=”+s);
break; default:
System.out.println(“Invalid choice!”);
}
81 Revision Tour II
}}
53. Write a program to input a number and print all its prime factors using prime factorization.
For Example,
INPUT: Enter an integer: 24
OUTPUT: Prime Factors using Prime Factorisation are:
2
2
2
3 Ans.
import java.util.*;
class Sol53
{
static void main()
{
Scanner sc=new Scanner(System.in);
int n,f=2;
System.out.println(“Enter a number:”);
n=sc.nextInt();
while(n>1)
{
if(n%f==0)
{
System.out.println(f);
n=n/f;
}
else
f++;
}
}
}
54. Write a program to input a number and check whether it is a Smith number or not. Smith
number is such a number, the sum of whose digits equals the sum of the digits of its prime
factors.
Smith number is a composite number in which the sum of its digits is equal to the sum of the
digits of all its prime factors.
For Example 378 is a Smith Number as the sum of the digits of 378 are : 3+7+8 = 18. The prime
factors of 378 are: 2, 3, 3, 3, 7 ( sum = 2+3+3+3+7 = 18).
Similarly 22 is a Smith Number as the sum of the digits are : 2+2=4. The prime factors of 22
are: 2 and 11 (Sum = 2+(1+1) = 4
83 Revision Tour II
55. 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-digitnumber” otherwise,
output the message “Not a special2-digit number”.
Ans. import java.util.*;
class Sol55
{
static void main()
{
Scanner sc=new Scanner(System.in);
int n,f,l;
System.out.println(“Enter a number:”);
n=sc.nextInt();
if(n>=10 && n<=99)
{
f=n/10;
l=n%10;
if(f+l+f*l==n)
System.out.println(“Special 2-digit number”);
else
System.out.println(“Not a Special 2-digit number”);
}
else
System.out.println(“Not a 2-digit number”);
}
}
56. 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), rate of interest(r) and time period in years(n). Calculate and
output the maturity amount(A) receivable using the formula
System.out.println(“Amount=”+A);
break; case 2:
System.out.println(“Enter the principal:”);
p=sc.nextDouble();
System.out.println(“Enter the rate:”);
r=sc.nextDouble();
85 Revision Tour II
System.out.println(“Enter the time period:”);
n=sc.nextDouble();
A=p*n+p*n*(n+1)/2*r/100*1/12.0;
System.out.println(“Amount=”+A);
break; default:
System.out.println(“Invalid choice!”);
}
}
}
57. Use switch statement,write a menu driven program to:
(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 : 5!=1×2×3×4×5=120.
For an incorrect choice, an appropriate error message should be displayed.
Ans.
import java.util.*;
class Sol57
{
static void main()
{
Scanner sc=new Scanner(System.in);
int ch,n,i,f=1;
System.out.println(“M E N U”);
System.out.println(“1. Factors”);
System.out.println(“2. Factorial”); System.out.println(“Enter your
choice:”); ch=sc.nextInt();
System.out.println(“Enter a number:”);
n=sc.nextInt();
switch(ch)
{ case 1:
87 Revision Tour II
59. Using switch statement, write a menu driven program for the following:
(i) To find and display the sum of the series given below:
S = x1 – x2 + x3 0 x4 + x5 ............................ – x20
(where x = 2)
(ii) To display the following series:
11 111 1111 11111
For an incorrect option, an appropriate error message should be displayed.
Ans.
import java.util.*;
class Sol59
{
static void main()
{
Scanner sc=new Scanner(System.in);
int ch,n,i,f=0;double s=0;
System.out.println(“M E N U”);
System.out.println(“1. First Series”);
System.out.println(“2. Second Series”);
System.out.println(“Enter your choice:”);
ch=sc.nextInt();
switch(ch)
{
case 1:
for(i=1;i<=20;i++)
{
if(i%2==1)
s=s+Math.pow(2,i);
else
s=s-Math.pow(2,i);
}
System.out.println(“Sum=”+s);
break; case 2:
for(i=1;i<=5;i++)
{
f=f*10+1;
System.out.print(f+“ ”);
}
break;
default:
System.out.println(“Invalid choice!”);
89 Revision Tour II
A. Tick () the correct option.
1. Which among the following is not a primitive data type?
a. int b. short
c. String d. Long
Ans. c. String
2. Name the operator that is used to allocate memory space for an object.
a. Dot b. New
c. Both a and b d. None of these
Ans. b. New
3. What is the name given to a memory location called in Java?
a. Variable b. Constant
c. Data Type d. None of these
Ans. a. Variable
4. Which are the data types used in Java?
a. Primitive data type b. Composite data type
c. Both a and b d. None of these
Ans. c. Both a and b
5. How are the characteristics of an object represented in a class?
a. Data Members b. Member Functions
c. Access specifiers d. None of these
Ans. a. Data Members
6. Which among the following is used to change the state of an object?
a. Data Members b. Name of the
class
c. Both a and b d. None of these
Ans. a. Data Members
7. How is encapsulation implemented in a program?
a. Using a class b. Using only
Functions
91 Revision Tour II
8. Information passed to a method through arguments is called _____________.
a. Message b. Variables
c. Numbers d. Data
Ans. a. Message
9. What among the following is not a component of a message?
a. An object identifier b. A method
name
c. Arguments d. Data Members
Ans. d. Data Members
10. How many objects can you create from a class?
a. One b. Two
c. Three d. Any number
A class is a group of similar objects. Object is a real world entity such as pen,
laptop, mobile, chair etc.
These are inbuilt data type provided by These are data types created by the user using
the Java Language. fundamental or composite data type or both.
The size of it is fixed. The size of it depends upon the size of the
individual components of it.
13. What does a class encapsulate?
Ans. A class encapsulate characteristics represented by data members and behaviour represented by
member functions.
B. Consider the following code and answer the questions that follow: class
academic
{
int x,y;
void access()
{
int a,b;
academic student=new academic();
System.out.println(“Object Created”);
}
}
a. What is the object name of the class?
b. Name the instance variables used in the class.
C. Consider the following code and answer the questions that follow:
class vxl
{
int x,y; void init( )
{
x=5; y=10;
}
protected void access( )
{
int a=50, b=100; vxl vin=new vxl( );
vin.int( );
System.out.println(“Object created”);
System.out.println(“I am X=”+vin.x);
System.out.println(“I am Y=”+vin.y);
}
}
a. What is the object name of the class vxl?
b. Name the local variables of class.
c. What is the access specifier of method access( )?
d. Write the output of the above program.
Ans.
a. vin
b. a and b
c. protected
d. Output:
Object created
I am X=5
I am Y=10
D. Find the errors in the program given below and rewrite the corrected form:
My class
{
SECTION B
Write programs for the following:
1. Write a class with name Employee and basic as its data member, to find the gross pay of an
employee for the following allowances and deduction. Use meaningful variables.
Dearness Allowance = 25% of the Basic Pay
House Rent Allowance = 15% of Basic Pay
Provident Fund = 8.33% of Basic Pay
Net Pay = Basic Pay + Dearness Allowance + House Rent Allowance
void calc()
{
double pf,gp,np,hra,da;
da=25/100.0*basic;
hra=15/100.0*basic;
pf=8.33/100*basic;
np=basic+da+hra; gp=np-pf;
System.out.println(“Gross Pay=”+gp);
}
}
2. Define a class ‘Salary’ described as below:
Data Members:
Name, Address, Phone, Subject Specialisation, Monthly Salary, Income Tax.
Member methods:
i. To accept the details of a teacher including the monthly salary.
ii. To display the details of the teacher. iii. To compute the annual Income Tax as 5% of
the annual salary above ` 1,75,000/-.
Write a main method to create object of the class and call the above member method.
Ans.
import java.util.*;
class Salary
{
String Name, Address,subSpe;
double mSal,it; long phone;
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter your name:”);
Name=sc.nextLine();
System.out.println(“Enter your address:”);
Address=sc.nextLine();
class Employee
{
String pan, name; double
tax_income,tax;
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter your PAN no.:”); pan=sc.nextLine();
System.out.println(“Enter your name:”); name=sc.nextLine();
System.out.println(“Enter taxable income:”);
tax_income=sc.nextDouble();
}
void display()
{
System.out.println(“Pan Number\t\tName\t\tTax-income\t\tTax”);
System.out.println(pan+“\t\t”+name+“\t\t”+tax_income+“\t\t”++ tax);
}
void calc()
{
if(tax_income<=100000)
tax=0;
else if(tax_income>100000 && tax_income<=150000) tax=10/100.0*(tax_income-
100000);
else if(tax_income>150001 && tax_income<=250000)
tax=5000+20/100.0*(tax_income-150000); else
tax=25000+30/100.0*(tax_income-250000);
}}
5. Define a class called Mobike with the following description: Instance variables/ Data
members:
bno : to store the bike’s number
void withdraw(int a)
{
void print()
{
System.out.println(“Name:”+name);
System.out.println(“Account No.:”+acno);
System.out.println(“Balance:”+bal);
System.out.println(“Type of Account:”+type);
}
public static void main(String args[])
{
Bank ob=new Bank();
Scanner sc=new Scanner(System.in);
ob.initialise();
char c;int a;
System.out.println(“Enter (D)eposit/(W)ithdraw:”);
c=sc.next().charAt(0);
if(c==‘D’)
{
System.out.println(“Enter the amount to deposit:”); a=sc.nextInt();
ob.depo(a);
}
else if(c==‘W’)
{
System.out.println(“Enter the amount to withdraw:”); a=sc.nextInt();
ob.withdraw(a);
}
else
System.out.println(“Invalid input”);
ob.print();
}
}
8. Define a class Bill as described below:
Data members are:
name : to store the name of the consumer
consumerno : to store the consumer number
unitconsumed : to store the unit cosumed
void datainput()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the name:”); name=sc.nextLine();
System.out.println(“Enter the consumer no.:”); consumerno=sc.nextLong();
System.out.println(“Enter the unit consumed:”); unitconsumed=sc.nextInt();
}
float compute()
{
float bill=0;
if(unitconsumed<=100)
bill=unitconsumed*1.2f; else if(unitconsumed>100
&& unitconsumed<=200) bill=unitconsumed*2.2f;
else if(unitconsumed>200 && unitconsumed<=300)
bill=unitconsumed*3.2f; else
bill=unitconsumed*4.0f;
return bill;
}
void Display()
{
System.out.println(“Consumer Name\t\tConsumer No\t\tUnit Consumed\t\tBill Amount”);
>=20,000 53 12 10 8
< 10,000 40 8 14 7
Gross Salary = ( Basic Salary + DA + TA + HRA ) – PF display ( ) :
To display the following data in given format:
EMPLOYEE No. NAME GROSS SALARY PF
Write a main method to create the object of the above class and call the above method to calculate and
print the Employee No., Name, Gross Salary and PF of an employee.
Ans.
import java.util.*;
class Empl
{
int Emp_No; String
Name;
float Basic,DA,HRA,TA,PF,Gross;
void get()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter your employee no.:”);
void Checkin()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the Room no:”);
Rno=sc.nextInt();
System.out.println(“Enter the Name:”);
Name=sc.nextLine();
System.out.println(“Enter the Tarrif:”);
Tarrif=sc.nextFloat();
System.out.println(“Enter the No. of Days:”);
NOD=sc.nextInt();
}
void Checkout()
{
System.out.println(“Room no:”+Rno);
System.out.println(“Name:”+Name);
System.out.println(“Tarrif:”+Tarrif);
System.out.println(“No. of days:”+NOD);
System.out.println(“Amount:”+CALC());
}
public static void main(String args[])
{
hotel ob=new hotel();
ob.Checkin();
ob.Checkout();
}}
15. Define a class Telephone having the following description:
Instance Variables / Data Members: int prv, pre - to store the
previous and present meter reading int call - to store the calls
made (i.e. pre – prv) String name - to store name of the customer
double amt - to store the amount double total - to store the
total amount to be paid
Member Methods:
void input ( ) - t o input the previous reading, present reading and name of the
void display()
{
System.out.println(“Name\t\tCalls Made\t\tAmount\t\tTotal Amount”);
First_AC 700
Second_AC 500
Third_AC 250
Sleeper None
• void display() - T o 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 member methods. Ans.
import java.util.*; class
RailwayTicket
{
String name, coach;
long mobno; int
amt,totalamt;
void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the name:”); name=sc.nextLine();
System.out.println(“Enter the type of coach:”); coach=sc.nextLine();
System.out.println(“Enter the mobile number:”); mobno=sc.nextLong();
System.out.println(“Enter the amount:”);
amt=sc.nextInt();
}
void update()
{
double rate=0;
if(coach.equals(“First_AC”))
totalamt=amt+700;
else if(coach.equals(“Second_AC”))
totalamt=amt+500;
else if(coach.equals(“Third_AC”)) totalamt=amt+250; else
if(coach.equals(“Sleeper”)) totalamt=amt;
}
void print()
1. What is a method?
Ans. A Java method is a collection of statements that are grouped together to perform an operation.
2. Write two advantages of using functions in a program.
Ans. Reduces complexity and Reusability.
4. If a function contains several return statements, how many of them will be executed?
Ans. The first one.
5. Name the keyword that causes the control to transfer back to the method call.
Ans. return
Parameter list in the function prototype. Parameter list in the function invocation.
11. State the difference between Call by Value and Call by Reference.
Ans.
Using this technique a copy of the values in Using this technique a reference to the values
the actual parameter is made in the formal in the actual parameter is made by the formal
parameters. parameters.
Any changes made to the formal Any changes made to the formal parameters is
parameters is not reflected back in the reflected back in the actual parameters.
actual parameters.
Usually primitive data type is used during Usually arrays and objects are used during call
call by value. by reference.
12. How are the following passed?
Pure functions are such functions which do Impure functions are such functions which
not change the state of an object. changes the state of an object.
It doesn’t have any side effects as the state It does have side effects as the state of the
of the object is not changed, rather only object is changed, and therefore one should be
accessed. careful using it.
14. Explain function overloading with an example.
Ans.
Example of function overloading:
class Overload
{
static void num_calc(int num,char ch)
{ if(ch==’s’)
System.out.println(“Square:”+(num*num)); else
System.out.println(“Square:”+(num*num*num));
}
static void num_calc(int a,int b,char ch)
{
19. How are static methods of one class called by methods in other classes?
Ans. The function invocation should be preceded with the name of the class followed by the dot
operator.
4. Protected access method largest which accepts a float type, int type and double type data as
parameters and have a byte type as return type.
C. Answer as directed:
SECTION B
Write programs for the following:
1. Create a method which accepts two int type variable a and b as parameter and evaluate the
following expression:
4 52. a b+ 2
and return it.
a b− Ans.
class Sol1
{
static double method(int a,int b)
{
double c; c=(4.2*a+b*b)/(a-
b);
return c;
}}
2. Create a function which accepts an integer as parameter and return true if it is a prime number
otherwise return false. In the main() method input an integer and using the above method
check whether it is a prime number or not.
Ans.
import java.util.*; class
Sol2
{
static boolean isPrime(int n)
{
int i,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
if(c==2)
return true; else
return false;
}
(ii) double series(double x,double n) with two double arguments and returns the sum of the
series
x2 x3 x4 xn S x= + + + +...
2! 3! 4! n!
Ans.
class Sol35
{
static double series(double n)
{
double s=0,i,j,f;
for(i=1;i<=n;i++)
{
f=1;
for(j=1;i<=i;j++)
{
f=f*j;
}
s+=1/f;
}
return s;
}
static double series(double x,double n)
{
double s=0,i,j,f;
for(i=1;i<=n;i++)
{
f=1;
for(j=1;i<=i;j++)
{
f=f*j;
}
s+=Math.pow(x,i)/f;
}
return s;
}}
36. Write a menu driven program to accept a number from the user and check whether is a ‘BUZZ’
number or to accept any two numbers and print ‘GCD’ of them.
a. A BUZZ number is the number which either ends with 7 or divisible by 7.
163 Constructors
Ans. a. Copy constructor
7. Categorise the type of object that can be created without any name or identifier.
a. Temporary object b. Anonymous
object
c. Both a and b d. None of these
Ans. c. Both a and b
8. Predict the output of the following program:
class T
{
int t = 20;
T()
{
t = 40;
}
public static void main(String args[])
{
T t1 = new T();
System.out.println(t1.t);
}
}
a. 20 b. 40
c. Compiler Error d. None of these
Ans. b. 40
9. The following code contains one compilation error, find it?
public class Test { Test() { } //
line 1
static void Test() { this(); } // line 2
public static void main(String[] args) { // line 3
Test(); // line 4
}
}
a. At line 1, constructor Tester must be marked public like its class
b. At line 2, constructor call
c. At line 3, compilation error, ambiguity problem, compiler can’t determine whether a constructor
d. At line 4
Ans. b. At line 2, constructor call
10. Which of the following is not true for static block?
a. It is used to initialise static variables.
SECTION A
1. What is a constructor? Why is it needed in a program?
Ans. A constructor in Java is a block of code similar to a method that is called when an instance of an
object is created. A constructor is needed to initialise data members with legal initial values.
165 Constructors
7. What are the different types of constructors available in Java?
Ans. Parameterised constructor and Non-parameterised constructor.
8. What is a default constructor?
Ans. When we do not explicitly define a constructor for a class, then java creates a default constructor for
the class. It is essentially a non-parameterized constructor, i.e. it doesn’t accept any arguments. The
default constructor’s job is to call the super class constructor and initialize all instance variables.
9. Point out the difference between implicit and explicit default constructors.
Ans. Implicit default constructor is the default constructor created by java if the user do not create a
constructor. Explicit default constructor is a non-parameterised constructor defined by the user to
initialise data members with legal initial values.
10. What are temporary objects? How are they created, explain with the help of an example?
Ans. Temporary or anonymous objects or instances are the ones that live in the memory as long as it is
being used or referenced in an expression and after that it dies. Temporary objects are created by
explicit call to a constructor, preceded with the new command. For example,
public class temp
{
int a,b;
temp(int x, int y)
{
a=x;
b=y;
}
void show()
{
System.out.println(a+“,”+b);
}
static void test( )
{
new temp(1,2).show( );
}
}
Here the statement new temp(1,2) of the statement new temp(1,2).show(); creates an anonymous
temporary object and lives in the memory as long as show() of the statement new
temp(1,2).show(); is being executed. Upon completion of the execution of the show() function, the
temporary object gets wiped out of the memory.
167 Constructors
a=b;
b=t;
}
}
15. What is the default initial value of a boolean variable data type?
Ans. the default initial value is ‘false’.
B. Consider the following code and answer the questions that follow:
class Myclass
{
int a,b;
void Myclass(int x, int y)
{
a=x;
b=y;
}
int Myclass(int x)
{
a=b=x;
}
void show( )
{
System.out.println(a+ “ “+y);
}
public static void main(String args[])
{
Myclass ob1=new Myclass();
Myclass ob2=new Myclass(12.3,14.6,15);
Myclass ob3=new Myclass(7);
ob1.ob2.ob3.show();
}
}
169 Constructors
char c=(char)(a+b);
System.out.println(c);
}
public static void main()
{
Today t=new Today();
t.input();
t.convert();
}
}
Based on the above given piece of code, answer that questions the follow: i. Name the instance,
class and local variables.
ii. What is the name of the constructor of the above class?
iii. Explain the line: Today t=new Today();Ans.
Output:
n
i. Instance variable: b Class variable: a Local
variable: c ii. Today() iii. An object named t is being created of ‘Today’
type.
E. In the program given below, state the name and value of the
i. method argument or argument variable ii. class variable iii.
local variable iv. instance variable class Myclass
{
static int x=7;
int y=2;
public static void main(String args[])
{
Myclass obj=new Myclass(); System.out.println(x);
obj.sampleMethod(5);
int a=6;
System.out.pritnln(a);
}
void sampleMethod(int n)
{
System.out.println(n);
System.out.println(y);
}
}
Ans.
SECTION B
Write programs for the following:
171 Constructors
{
String Name,Address,hobby;
Friend(String n,String a,String h)
{
Name=n; Address=a;
hobby=h;
}
void display()
{
System.out.println(“Name:”+Name);
System.out.println(“Address:”+Address);
System.out.println(“Favourite hobby:”+hobby);
}
public static void main(String args[])
{
Friend ob1=new Friend(“Soumen”,“Delhi”,“Philately”);
Friend ob2=new Friend(“Sujit”,“Patna”,“Guitar”);
ob1.display(); ob2.display();
}
}
3. Define a class named four Side, having members as:
Data members: length, breadth Member
Functions:
i. Overloaded constructor to initialise the dimension of the four-sided figure with a square and a
rectangle.
ii. Compute the area and display it.
Also create the main() method to show the implementation of the above methods. Ans.
class FourSide
{
int length,breadth;
FourSide(int s)
{
length=breadth=s;
}
FourSide(int l,int b)
{
length=l; breadth=b;
}
void compute()
{ int area;
area=length*breadth;
1
Create a class named Natural, which will contain the following members:
Data members: n and s of int data type.
Member functions:
i. Parametrised constructor to initialise n.
ii. void compute( ) to calculate the sum of first n natural numbers using the above formula and
store it in s.
iii. void display( ) to show the sum. Ans.
class Natural
{
int n,s;
Natural(int t)
{ n=t;
}
void compute()
{ int i; s=0;
for(i=1;i<=n;i++)
s+=i;
}
void display()
{
System.out.println(“Sum:”+s);
}}
5. Define a class named Conversion having the following static methods:
i. int mTocm(int m ), which converts metre(m) to centimeter and return it.
ii. int multiply(int x, int y ), which returns the product of x and y.
Define another class named Rectangle which contains the following data members:
• length of int type which holds the length of a rectangle in metre.
• breadth of int type which holds the breadth of a rectangle in centimeter.
173 Constructors
Create member functions:
i. Constructor to initialise the data members.
ii. Convert the length to centimetre by calling the relevant method of the above
class.
iii. Compute the area by calling the relevant method of the above class and display
the result. Ans.
class Conversion
{ int n,s;
int mTocm(int m)
{
return m*100;
}
int multiply(int x,int y)
{
return x*y;
}
}
public class Rectangle
{
int length,breadth; Rectangle(int
m,int cm)
{
length=m;
breadth=cm;
}
void convert()
{
length=new Conversion().mTocm(length);
}
void compute()
{ int area;
convert();
area=new
Conversion().multip
ly(length,breadth);
System.out.println(“Area:”+area);
}}
6. A class Palin has been defined to check whether a positive number is a Palindrome number or not.
The number ‘N’ is palindrome if the original number and its reverse are same. Some of the members of
the class are given below:
Classname :
175 Constructors
}
public static void main(String args[])
{
Palin ob=new Palin();
ob.accept();
ob.check();
}}
7. Design a class named Numbers, which will contain the following members:
Data Members: a, b and c of int data type.
Member Functions:
i. Parameterised constructor to initialise a and b. ii.
void show( ) to display the contents of a, b and c. iii. void
compute( ) to add a and b and store it in c.
In the main( ) create an object and initialise a and b with any value and add a and b by invoking
the compute( ) function and display the contents of a, b and c using show( ) function. Ans. class
Numbers
{
int a,b,c;
Numbers(int x,int y)
{ a=x;
b=y;
}
void show()
{
System.out.println(a+” “+b+” “+c);
}
void compute()
{
c=a+b;
}
9. You are to print the telephone bill of a subscriber. Create a class having the following data members:
Phone Number of long data type (for storing the phone number).
Name of String type (for storing the name of a the subscriber).
Hire Charge a symbolic constant of int type (to store monthly hire charge say `. 200).
Units Consumed of int type (to store the monthly units consumed by the subscriber).
Bill Amount of float type (to store the bill amount that is payable).
177 Constructors
Create member functions for the following:
i. Constructor to initialise all data members except Hire Charge and Bill Amount.
ii. Calculate the bill amount payable which is Hire Charge+(`. 1 per unit for the first 100 units, `. 1.50
per unit for the next 100 units and `. 2.00 per unit there after. iii. To display the Bill for the
subscriber.
Ans.
import java.util.*;
class Telephone
{
long pno; String
name; int hire;
int units; float bill;
Telephone(long p,String n,int u)
{
pno=p; name=n;
units=u;
}
void calculate()
{
hire=200; bill=0;
if(units<=100)
bill=hire+units*1;
else if(units>100 &&
units<=200)
bill=hire+100*1+(units-100)*1.50f; else
bill=hire+100*1+100*1.50f+(units-200)*2;
}
void show()
{
System.out.println(“BILL”);
System.out.println(“Phone No.:”+pno);
System.out.println(“Name:”+name);
System.out.println(“Hire Charge:”+hire);
System.out.println(“Units consumed:”+units);
System.out.println(“Bill:”+bill);
}
}
10. Define a class Taximeter having the following description:
Data members/instance variables: int taxino - to store taxi
number String name - to store passenger’s name int km -
to store number of kilometers travelled
179 Constructors
System.out.println(“Taxino\t\tName\t\tKilomtres travelled\t\tBill amount”);
System.out.println(taxino+“\t\t”+name+“\t\t”+km+“\t\t”+calculate());
}
}
11. Create a class which will contain the following components:
Data Members: a and b of int type.
Member Functions:
i. Constructor to initialise a and b.
ii. Return the sum of a and b. iii. To display the value of a and b.
Also create a static function which accepts two objects as parameters and print a and b of the
object whose sum is the maximum.
In the main() create two objects, initialise them and display the data members of that object
whose sum of the data-members is the maximum.
Ans.
import java.util.*;
class Numbers
{ int a,b;
Numbers(int x,int y)
{ a=x; b=y;
}
int sum()
{
return a+b;
}
void display()
{
System.out.println(“a=”+a+“b=”+b);
}
static void compare(Numbers ob1,Numbers ob2)
{
if(ob1.sum()>ob2.sum()) ob1.display();
else
ob2.display();
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in); int x,y;
System.out.println(“Enter 2 numbers:”);
x=sc.nextInt(); y=sc.nextInt();
Numbers ob1=new Numbers(x,y); System.out.println(“Enter 2 numbers:”);
x=sc.nextInt(); y=sc.nextInt();
181 Constructors
{
product_price-=10;
}
void display()
{
System.out.println(“Product code:”+product_code);
System.out.println(“Flavour:”+flavour);
System.out.println(“Pack type:”+pack_type);
System.out.println(“Pack size:”+pack_size);
System.out.println(“Product price:”+product_price);
}
public static void main(String args[])
{
FruitJuice ob=new FruitJuice();
ob.input(); ob.discount();
ob.display();
}}
13. Create a class SalaryCalculation that is described as below:
Class Name : SalaryCalculation
Data members : name (String type data)
basicPay, specialAlw, conveyanceAlw, gross, pf, netSalary AnnualSal (All double type data) Member
methods :
i. SalaryCalculation( ) - A constructor to assign name of employee (name), basic salary (basicPay) of
your choice and conveyance allowance (conveyanceAlw) As ` 1000.00
ii. void SalaryCal( ) - to calculate other allowances and salaries as given: specialAlw = 25%
of basic salary. gross = basicPay + specialAlw + conveyanceAlw. netSalary = gross - pf.
AnnualSal = 12 months netSalary. iii. void display( ) - to print the name and other calculations
with suitable headings.
Write a program in Java to calculate all the details mentioned above and print them all. Ans.
import java.util.*;
class SalaryCalculation
{
String name;
double basicPay, specialAlw, conveyanceAlw, gross, pf, netSalary, AnnualSal;
SalaryCalculation()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the name:”); name=sc.nextLine();
System.out.println(“Enter the basic pay:”); basicPay=sc.nextDouble();
conveyanceAlw=1000.00;
}
r
CI = P = 1+ 100 1
−P where P - is the Principal amount, r - rate of interest and t-time
period in years.
Data memebers of class: pamt, rate (double data type to store principal amount and rate of interest),
time (integer to store time period) Functions of the class:
i. Compound()-constructor to assign default values to all the data memebers.
ii. void input()-to input the principal, rate and time from the user. iii. double findInterest()-to
find and return compound interest using the given formula. iv. void printData()-to print the
principal, rate and time.
Write a main function to input required data and by invoking suitable functions print the entered data
and compound interest.
Ans.
import java.util.*;
class Compound
{
double pamt, rate; int time;
183 Constructors
Compound()
{
pamt=rate=0.0;
time=0;
}
void input()
{
Scanner sc=new Scanner(System.in); System.out.println(“Enter the principal:”);
pamt=sc.nextDouble();
System.out.println(“Enter the rate:”); rate=sc.nextDouble();
System.out.println(“Enter the time:”);
time=sc.nextInt();
}
double findInterest()
{
double ci;
ci=pamt*Math.pow(1+rate/100.0,time)-pamt; return ci;
}
void printData()
{
System.out.println(“Principal:”+pamt);
System.out.println(“Rate:”+rate);
System.out.println(“Time:”+time);
}
public static void main(String args[])
{
Compound ob=new Compound();
ob.input(); ob.printData();
System.out.println(“Compound Interest:”+ob.findInterest());
}
}
15. Define a class PhoneBill with the following descriptions.
Data members: customerName of type character array phoneNumber
of type long no_of_units of type int rent of type int
amount of type float.
Member Functions:
i. calculate( ) T his member function should calculate the value of amount as rent+ cost for the
units.
where cost for the units can be calculated according to the following conditions.
No_of_units Cost First 50 calls
Free
void Display()
{
185 Constructors
System.out.println(“Customer name:”+customerName);
System.out.println(“Phone number:”+phoneNumber);
System.out.println(“No. of units:”+no_of_units);
System.out.println(“Rent:”+rent);
System.out.println(“Amount:”+amount);
}
public static void main(String args[])
{
PhoneBill ob=new PhoneBill();
ob.accept(); ob.calculate();
ob.Display();
}
}
16. Define a class Sports with the following descriptions:
Data members: s_code of
type long s_name of type
(String) fees of type integer
duration of type integer
Member Functions:
i Constructor to assign initial values of s_code as 1001, s_name as “Cricket”, fees as 500,
duration as 70.
ii A function newSports() which allows user to enter s_code, s_name and duration. Also assign
the values to fees as per the following conditions:
s_name Fees
Table Tennis 2000
Swimming 4000
Football 3000
iii A function displaySports() to display all the details. Ans.
import java.util.*;
class Sports
{
String s_name; long
s_code; int
fees,duration;
Sports()
{
s_name=“Cricket”;
s_code=1001; fees=500;
duration=70;
}
void newSports()
187 Constructors
if(c==2)
return true; else
return false;
}
void display()
{
int i=0,p=2;
while(i<n)
{
if(isPrime(p)==true)
{
System.out.println(p);
i++;
} p++;
}
}}
18. Create a class called PrimeDigits to find the sum of the prime digits in an integer. The class should
have the following members.
Data Members: n of int
data type. Member
Functions:
i. Parameterised constructor to initialise the value of n.
ii. Method called isPrime() which accepts an integer as a parameter and return true if it is a prime
number otherwise return false.
Method called sumOfPrimeDigits() which accepts an integer as a parameter and find the sum of
prime digits only. Ans.
import java.util.*;
class PrimeDigits
{ int n;
PrimeDigits(int a)
{ n=a;
}
boolean isPrime(int n)
{ int i,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
void sumOfPrimeDigits(int n)
{
int i=n,d,s=0;
while(i>0)
{
d=i%10;
if(isPrime(d)==true)
s=s+d;
i/=10;
}
System.out.println(“Sum of prime digits:”+s);
}}
19. Create a class called Series which will contain the following members:
Data Members: x of
double type n of int
type Member
Functions:
i. Parameterised constructor to initialise the data members. ii. To calculate and print
the sum of the following series: x+x/2!+x/3!+x/4!+...+x/n!
To calculate and print the sum of the following series:
x/2!+x2/3!+x3/4!+x4/5!+…+xn/(n+1)!
To calculate and print the sum of the following series: x/2! - x2/3!+x3/4! -
x4/5!+…±xn/(n+1)!
where the symbol ! stands for factorial eg. 5!=5*4*3*2*1, 3!=3*2*1 Ans.
import java.util.*; class Series
{ double x; int n;
Series(double x,int n)
{ this.x=x; this.n=n;
}
void sumSeries1()
{
double s=0; long i,p,j;
for(i=1;i<=n;i++)
{ p=1;
for(j=1;j<=i;j++)
189 Constructors
{ p=p*j;
}
s=s+x/p;
}
System.out.println(“Sum=”+s);
}
void sumSeries2()
{
double s=0; long i,p,j;
for(i=1;i<=n;i++) { p=1;
for(j=1;j<=i+1;j++)
{ p=p*j;
}
s=s+x*i/p;
}
System.out.println(“Sum=”+s);
}
void sumSeries3()
{
double s=0; long i,p,j;
for(i=1;i<=n;i++)
{ p=1;
for(j=1;j<=i+1;j++)
{ p=p*j;
}
if(i%2!=0) s=s+x*i/p; else
s=s-x*i/p;
}
System.out.println(“Sum=”+s);
}}
20. Create a class named Rounding which contains the following members:
Data members: n and r of double type Member
Functions:
i. Constructor to read a real number from the keyboard into n. ii. to round off n to two
places of decimal and store it in r.
iii. to display the value of the data members. Ans.
import java.util.*;
class Rounding
{ double n,r; Rounding()
{
void roundOff()
{
r=Math.round(n*100)/100.0;
}
void display()
{
System.out.println(“n=”+n+“r=”+r);
}
}
191 Constructors
Tick () the correct option.
1. Which of the following is a composite data type?
a. int b. String
c. char d. float
Ans. b. String
2. Which of the following is not a wrapper class?
a. Byte b. Int
c. Long d. Float
Ans. b. Int
3. Which of the following is valid method of initialising?
a. Integer a=new (5); b. Integer a=Integer(5);
c. Integer a=new Integer(5); d. Integer a=new (“5”);
Ans. d. Integer a=new (“5”);
4. If s=“123”, which among the following will convert it to an integer?
a. int a=Integer(s); b. int a=(int)s;
c. int a=parseInt(s); d. int
a=Integer.parseInt(a);
Ans. d. int a=Integer.parseInt(a);
5. Which among the following is valid character initialisation?
a. Character c=new Character(‘c’); b. Character c=new Character(“c”);
c. Both a and b d. None of these
Ans. a. Character c=new Character(‘c’);
6. Which among the following methods return a true or a false?
a. toLowerCase() b. toUpperCase()
c. parseInt() d. isUpperCase()
Ans. d. isUpperCase()
7. What package is a part of the wrapper class which is imported by default into all Java programs?
a. java.util b. java.lang
c. java.awt d. None of these
193 Constructors
8. Which class is inherited by the Character and Boolean wrapper classes?
a. Object b. Number
c. Both a and b d. None of
these
Ans. a. Object
9. What is, converting a primitive value into an object of the corresponding wrapper class called?
a. Autoboxing b. Unboxing
c. Type Casting d. All of
these
Ans. a. Autoboxing
10. Which among the following function is used to check whether a given character is a tab space
or not?
a. isTab() b. isTabSpace()
c. isSpace() d. isWhitespace()
Ans. d. isWhitespace()
SECTION A
A. Answer the following questions.
Primitives are the fundamental data types Composite data types are user defined types
that are represented by keywords namely and may have any name defined by the user.
byte, short, int, long, char and boolean.
Variables of primitive data type stores values Variables of composite data type stores
of corresponding data type. reference to an object.
It can store only one type of value. It can store data of multiple data type.
6. Show with an example, how wrapper class object can be created and initialised?
Ans. Example:
Byte b=new Byte(byte) 10):
7. Explain autoboxing and unboxing in java.
12. Name the package that contain the wrapper classes. Ans. java.lang
1. Answer as directed:
a. Assign a integer 123 to an int variable a.
b. Convert the variable a to a String and store it in the variable s.
Ans. a. int a=123;
b. String s=Integer.toString(a);
2. Answer as directed:
a. Assign an string “123” to a String variable a.
b. Convert the variable a to an integer and store it in the variable s.
Ans. a. String a=”123”;
b. int s=Integer.parseInt(a);
Section A
Answer the following questions.
1. What is encapsulation?
Ans. Wrapping up of data and methods into a single unit is called encapsulation.
2. What are access specifiers used for? Name the access specifiers used in Java.
Ans. Access modifiers (or access specifiers) are keywords in object-oriented languages that set the
accessibility of classes, methods, and other members. Access modifiers are a specific part of
programming language syntax used to facilitate the encapsulation of components.
213 Encapsulation
Access obj=new Access(5,6);
obj.show();
}
}
public class MainClass
{
public static void main(String args[ ])
{
/*Access obj=new Access(5,6);Error constructor has private
access specifier.*/
Access.createObject();
Access obj=new Access(7); /*Correct as the default access
version of the constructor is being called.*/
}
}
6. What is Inheritance? Which keyword is used to implement inheritance?
Ans. Inheritance is a mechanism wherein a new class is derived from an existing class. The ‘extends’
keyword is used to implement inheritance.
215 Encapsulation
• A function ENTER() to allow user to enter values for Rno, Name, Score and call function
AssignRem() to assign grade.
• A function DISPLAY() to allow user to view the content of all data members.
Also create a main() method to create an object and show its implementation by calling the above
methods. Ans.
import java.util.*;
class Candidate
{
private long Rno; private
String Name; private float
Score; private String
Remarks;
private void AssignRem()
{
if(Score>=50)
Remarks=“Selected”;
else
Remarks=“Not Selected”;
}
public void ENTER()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the reg. no.:”);
Rno=sc.nextLong();
System.out.println(“Enter the name:”);
Name=sc.nextLine();
System.out.println(“Enter the score:”);
Score=sc.nextFloat();
AssignRem();
}
public void DISPLAY()
{
System.out.println(“Reg. no.:”+Rno);
System.out.println(“Name:”+Name);
System.out.println(“Score:”+Score);
System.out.println(“Remarks:”+Remarks);
}
217 Encapsulation
Food=sc.nextLine();
System.out.println(“Enter the Food Type:”);
FType=sc.nextLine();
GetSticker();
}
public void ShowFood()
{
System.out.println(“FoodCode:”+FoodCode);
System.out.println(“Food:”+Food);
System.out.println(“Food Type:”+FType);
System.out.println(“Sticker:”+Sticker);
}
219 Encapsulation
• GType of type String
• GSize of type integer
• GFabric of type String
• GPrice of type String
• A function Assign() which calculates and assigns the value of GPrice as follows: For the GFabric
as “COTTON”
GType GPrice
TROUSER 1300
SHIRT 1100
For GFabric other than “COTTON” the above mentioned GPrice gets reduced by 10%.
Public Members:
• A constructor to assign initial values of GCode, GType and GFabric with the words “NOT
ALLOTED” and GSize and GPrice with 0.
• A function input() to input the values of the data members of GCode, GType, GFabric, GSize and
invoke the Assign function.
• A function Display() which displays the content of all the data members for a Garment.
Also create a main() method to create an object and show its implementation by calling the above
methods. Ans.
import java.util.*;
class Garments
{
private String GCode,GType,GFabric;
private int GSize; private
float GPrice;
private void Assign()
{
if(GType.equalsIgnoreCase(“TROUSER”))
GPrice=1300;
else if(GType.equalsIgnoreCase(“SHIRT”))
GPrice=1100;
if(!(GFabric.equalsIgnoreCase(“COTTON”)))
GPrice=GPrice-10/100f*GPrice;
}
public Garments()
{
GCode=GType=GFabric=”NOT ALLOTED”;
GPrice=GSize=0;
}
public void input()
{
221 Encapsulation
• A constructor function to initialise Type as ‘O’ and Fare as 500.
• A function Allocate() to allow user to enter values for BusNo, From, To, Type and Distance. Also this
function should call CalcFare() to calculate Fare.
• A function Show() to display the content of all the data members on the screen.
Also create a main() method to create an object and show its implementation by calling the above
methods. Ans.
import java.util.*; class Bus
{
private String From,To;
private char Type; private int
BusNo; private float
Distance,Fare;
private void CalcFare()
{
if(Type==’O’)
Fare=15*Distance; else
if(Type==’E’)
Fare=20*Distance; else
if(Type==’L’)
Fare=24*Distance;
}
public Bus()
{
Type=’O’;
Fare=500;
}
public void Allocate()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the bus no.:”);
BusNo=sc.nextInt();
System.out.println(“Enter the origin:”);
From=sc.nextLine();
System.out.println(“Enter the destination:”);
To=sc.nextLine();
System.out.println(“Enter the Type of bus:”);
Type=sc.next().charAt(0);
System.out.println(“Enter the Distance:”);
Distance=sc.nextFloat();
CalcFare();
}
public void Show()
223 Encapsulation
public CABS()
{
Type=’A’;
CNo=1111;
}
private void Charges()
{
if(Type==’A’) PKM=25; else if(Type==’B’)
PKM=20; else if(Type==’L’)
PKM=15;
}
(ii)
import Number.Armstrong; import
java.util.Scanner; class Check
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in); int
n;
System.out.println(“Enter a number:”);
225 Encapsulation
n=sc.nextInt();
Armstrong ob=new Armstrong(n);
if (ob.isArmstrong())
System.out.println(“Armstrong No.”); else
System.out.println(“Not an Armstrong No.”);
}
}
227 Encapsulation
System.out.println(“Enter monthly salary:”); mSal=sc.nextDouble();
}
void display()
{
System.out.println(“Name:”+Name);
System.out.println(“Address:”+Address);
System.out.println(“Subject Specialization:”+subSpe);
System.out.println(“Phone No.:”+ phone);
System.out.println(“Monthly salary:”+mSal);
}
void calc()
{
double aSal; aSal=12*mSal;
if(aSal>175000)
it=5/100.0*(aSal-175000);
else
it=0;
}
229 Encapsulation
Ans. Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the
same type.
4. How do you initialise single and 2-dimensional arrays? Explain with examples.
Ans. The general form of Initialisation of single dimensional array is:
type array-name[ ]={ list of values }; For
example,
int n [ ] = {5, 12, 7};
The general form of Initialisation of two dimensional array is:
type array-name[ ][ ]={ {list of values},{list of values},{list of values}... }; For
example,
int a[][]={{5,1,3},{7,2,6}};
5. With the help of an example, show how arrays in Java are dynamic in nature.
Ans. Java arrays are dynamic in nature:
For example, int n;
Scanner sc=new Scanner (System.in);
System.out.println(“Enter the size;”); n=sc.nextInt(); //Enter
the size from the user int arr [ ]=new int[n]; //declare an array
of size (dynamic)
As you can see the memory for the array arr is created only after taking the size ‘n’ from the user.
8. Explain:
i. Linear Searchii. Binary Search Ans.
i. Linear search or sequential search is a method for finding a particular value in a list, that
consists of checking everyone of its elements, one at a time and in sequence, until the
desired one is found.
ii. Binary search in Java using divide and conquer technique. A binary search or half-interval
search algorithm finds the position of a specified value(the input“key”) within a sorted
array.
9. Compare Selection Sorting and Bubble sorting.
231 Arrays
Ans.
Selection Sorting Bubble Sorting
In this technique, each element is checked In this technique, every element is checked
with the remaining elements after it. with the adjacent element.
The sorting occurs from the front end of the The sorting occurs from the rear end of the
array. array.
There is only one interchange that occurs with There may be multiple interchanges that
each pass. might occur with each pass.
It is not possible at the middle of the iteration It is possible at the middle of the iteration
after a pass, whether the array got sorted or after a pass, whether the array got sorted or
not. not.
10. What is the difference between one-dimensional and two-dimensional arrays?
Ans. A one-dimensional array is a list of variables with the same datatype, whereas the
twoDimensional array is ‘array of arrays’ having similar data types.
11. With the help of an example, show how a two-dimensional float type array of size 3x4 can be
initialised.
Ans. float a[]=new float[3][4];
12. Why do you think in most cases nested loops are required to access the individual elements of
a 2-dimensional array?
Ans. This is to traverse through each element of a 2D array through each row and column.
233 Arrays
Output:
1
2
3
4
5
6
6. What will be the output of the following program:
class First
{
public static void main(String args[])
{
int a[]={5,1,15,20,25};
int i,j; int m;
i=++a[1];
j=a[2]++;
m=a[i++];
System.out.print(i+“ ”+j+“ ”+m);
}
}
Ans. Output:
3 15 16
7. What will be the output of the following program, when Method invoke() is called:
public class StringArray
{
void change(String arr[])
{
for(int i=0;i<arr.length;i++)
{
arr[i]=arr[i].substring(0,1).toUpperCase()+arr[i].substring(1);
}
}
void invoke()
{
String ar[]={“kolkata”,“gangtok”,“banglore”};
for(int i=0;i<ar.length;i++)
System.out.println(ar[i]); change(ar);
for(int i=0;i<ar.length;i++)
System.out.println(ar[i]);
}
}
235 Arrays
{
for(j=0;j<=3;j++)
{
System.out.print(sum[i][j]+“ ”);
}
}
}
}
10. Identify error(s), if any, in the following program.
class First
{
public static void main(String args[])
{
int i;
int a[6]={0,1,8,7,6,4}; for(i=0;i<=a.length();i++)
System.out.println(a[i]);
}
}
Ans.
class First
{
public static void main(String args[])
{
int i;
int a[]={0,1,8,7,6,4}; for(i=0;i<a.length;i++)
System.out.println(a[i]);
}
}
SECTION B
1. Write a program to input 10 numbers into an integer array and find the sum of all numbers in it.
Ans.
import java.util.*; class
Sol1
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,s=0;
for(i=0;i<10;i++)
s+=a[i];
System.out.println(“Sum=”+s);
}}
2. Write a program to input 10 numbers into an integer array and find the sum of even and odd
numbers separately.
Ans.
import java.util.*; class
Sol2
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,se=0,so=0;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<10;i++)
{
if(a[i]%2==0)
se+=a[i]; else
so+=a[i];
}
System.out.println(“Sum of even numbers=”+se);
System.out.println(“Sum of odd numbers=”+so);
}}
3. Write a program to input 10 numbers into an integer array and print those numbers which are
less than its average.
Ans.
import java.util.*; class
Sol3
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,s=0;
237 Arrays
float av;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<10;i++)
{
if(a[i]%2==0)
s+=a[i];
}
av=(float)s/10;
System.out.println(“Numbers less than average:”);
for(i=0;i<10;i++)
{
if(a[i]<av)
System.out.print(a[i]+“ ”);
}
}}
4. Write a program to input 10 numbers into an integer array and find the sum of prime numbers
only.
Ans.
import java.util.*; class
Sol4
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,s=0,j,c;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<10;i++)
{
c=0;
for(j=1;j<=a[i];j++)
{
if(a[i]%j==0)
c++;
5. Write a program to input 10 numbers into an integer array and check whether all numbers are 3-
digit numbers or not.
Ans. import java.util.*; class
Sol5
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i;
boolean f=true;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<10;i++)
{
if(!(a[i]>=100 && a[i]<=999))
f=false;
}
if(f)
System.out.println(“All are 3 digit numbers”);
else
System.out.println(“All are not 3 digit numbers”);
}
}
6. Write a program to input 10 numbers into an integer array and check whether all numbers in it
are same or not.
Ans.
239 Arrays
import java.util.*; class
Sol6
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i;
boolean f=true;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<10;i++)
{
if(a[i]!=a[0])
f=false;
}
if(f)
System.out.println(“All are same”);
else
System.out.println(“All are not same”);
}
}
7. Write a program to input 10 numbers into an integer array and check whether they are in
ascending order or not.
Ans.
import java.util.*; class
Sol7
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i;
boolean f=true;
System.out.println(“Enter 10
numbers:”); for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<9;i++)
{
8. Write a program to input 10 numbers into an integer array and find the position of the largest and
the smallest number.
Ans.
import java.util.*; class
Sol8
{ static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,l=0,s=0;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=sc.nextInt();
l=s=a[0]; for(i=1;i<10;i++)
{
if(a[i]>l)
l=a[i];
if(a[i]<s)
s=a[i];
}
for(i=0;i<10;i++)
{
if(a[i]==l)
System.out.println(“Position of largest number:”+i);
if(a[i]==s)
System.out.println(“Position of smallest number:”+i);
}
}
}
241 Arrays
9. Write a program to input 10 numbers into an integer array and interchange the largest number
with the smallest number within the array and print the modified array. Assume that there is
only one largest and smallest number.
for(i=0;i<10;i++)
{
c=0;
for(j=1;j<=a[i];j++)
{
if(a[i]%j==0)
c++;
}
if(c==2)
a[i]=0;
}
System.out.println(“Modified Array:”);
for(i=0;i<10;i++)
{
System.out.print(a[i]+“ ”);
}
}
}
243 Arrays
11. Write a program to input 10 numbers into an integer array and print the smallest prime number
in the array. import java.util.*; class Sol11
{ static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,j,c,s=0;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=sc.nextInt();
for(i=0;i<10;i++)
{ c=0;
for(j=1;j<=a[i];j++)
{
if(a[i]%j==0)
c++;
}
if(c==2)
{
if(s==0)
s=a[i];
if(a[i]<s)
s=a[i];
}
}
if(s>0)
System.out.println(“Smallest prime number:”+s);
else
System.out.println(“No prime number found”);
}
}
12. Write a program to input 10 numbers into an integer array and print the position of the second
largest number in it. import java.util.*;
class Sol12
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,l=0,sl=0,p=0;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=sc.nextInt();
l=a[0];
for(i=1;i<10;i++)
for(i=0;i<10;i++)
{
if(a[i]!=l)
{
if(sl==0)
{
sl=a[i];
p=i; }
if(a[i]>sl)
{
sl=a[i];
p=i;
}
}
}
System.out.println(“Position of second largest:”+p);
}
}
13. Write a program to input 10 numbers into an integer array and arrange the numbers in
descending order using Linear Sorting technique.
import java.util.*;
class Sol13
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,j,t;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=sc.nextInt();
for(i=0;i<9;i++)
{
for(j=i+1;j<10;j++)
{
if(a[i]<a[j])
{
t=a[i];
245 Arrays
a[i]=a[j];
a[j]=t;
}
}
}
System.out.println(“Sorted Array:”);
for(i=0;i<10;i++)
{
System.out.print(a[i]+“ ”);
}
}
}
14. Write a program to input 10 numbers into a float type array and arrange the numbers in
descending order using Bubble Sorting technique.
import java.util.*;
class Sol14
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,j,t;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=sc.nextInt();
for(i=9;i>0;i--)
{
for(j=0;j<i;j++)
{
if(a[j]<a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
System.out.println(“Sorted Array:”);
for(i=0;i<10;i++)
{
System.out.print(a[i]+“ ”);
15. Write a program to input 10 numbers into an integer array and reverse the array and print the
modified array.
For example, if array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 3 7 89 34 15 16 67 25
Ans.
import java.util.*;
class Sol15
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,t;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=sc.nextInt();
for(i=0;i<5;i++)
{ t=a[i];
a[i]=a[9-i];
a[9-i]=t;
}
System.out.println(“Modified Array:”);
for(i=0;i<10;i++)
{
System.out.print(a[i]+” “);
}
}}
16. Write a program to input 10 numbers into an integer array and interchange the consecutive
elements in it. That is, interchange a[0] with a[1], a[2] with a[3], a[4] with a[5] … For example,
if array contains
247 Arrays
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 3 7 89 34 15 16 67 25
for(i=p;i<9;i++)
{
249 Arrays
a[i]=a[i+1];
}
a[9]=0;
System.out.println(“Modified Array:”);
for(i=0;i<10;i++)
{
System.out.print(a[i]+“ ”);
}
}}
19. Write a program to input 10 numbers into an integer array and input a number and a position.
Now insert the number at that position by shifting the rest of the numbers to the right. The
last element is therefore removed from the array. For example, if array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 3 7 89 34 15 16 67 25
for(i=9;i>p;i--)
{
251 Arrays
}
System.out.println(“Modified Array:”);
for(i=0;i<10;i++)
{
System.out.print(a[i]+“ ”);
}
}
}
21. Write a program to input 10 numbers into an integer array and shift all even numbers to the
beginning of the array and odd numbers to the end of the array; without changing the order of
the numbers.
For example, if array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 3 7 89 34 15 16 67 24
After shifting the resultant array should be:
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
12 34 16 24 9 3 7 89 15 67
Ans.
import java.util.*;
class Sol21
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,j,t;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=sc.nextInt();
for(i=9;i>0;i--)
{
for(j=0;j<i;j++)
{
if(a[j]%2!=0 && a[j+1]%2==0)
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
22. Write a program to input 10 numbers into an integer array and print those single-digit positive
numbers which are not present in the array. For example, if array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 3 7 89 34 9 16 8 24
Output should be:
1, 2, 4, 5, 6
Ans.
import java.util.*;
class Sol22
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,j;
boolean f;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<=9;i++)
{
f=false;
for(j=0;j<10;j++)
{
if(a[j]==i)
f=true;
}
if(f==false)
System.out.println(i);
}
}}
253 Arrays
23. Write a program to input 10 numbers into an integer array and find the frequency of each two-
digit numbers present in it.
For example, if array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
99 12 34 7 99 34 12 16 12 24
Output should be:
Frequency of 12 = 3
Frequency of 16 = 1
Frequency of 24 = 1
Frequency of 34 = 2
Frequency of 99 = 2 Ans.
import java.util.*;
class Sol23
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,j,f;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=sc.nextInt();
for(i=10;i<=99;i++)
{
f=0;
for(j=0;j<10;j++)
{
if(a[j]==i)
f++;
}
if(f>0)
System.out.println(“Frequency of “+i+” is=”+f);
}
}}
24. Write a program to input 10 numbers into an integer array and find the frequency of each
number present in it.
Ans. import java.util.*; class
Sol24
{
static void main()
{
Scanner sc=new Scanner(System.in);
255 Arrays
if(a[i]==a[j])
c++;
}
if(c>max)
{
max=c;
n=a[i];
}
}
System.out.println(“Number having maximum frequency=”+n);
}}
26. Write a program to input 10 numbers into an integer array and store only the even numbers into
another array and display it.
For example, if the given array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
99 12 34 7 99 36 12 16 14 123
The resultant array should be:
b[0] b[1] b[2] b[3] b[4] b[5]
12 34 36 12 16 14
Ans.
import java.util.*; class
Sol26
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,b[]=new int[10],c=0;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=sc.nextInt();
for(i=0;i<10;i++)
{
if(a[i]%2==0)
b[c++]=a[i];
}
System.out.println(“Resultant Array:”);
for(i=0;i<c;i++)
{
System.out.print(b[i]+ “ ”);
}
}}
257 Arrays
The resultant array should be:
b[0] b[1] b[2] b[3] b[4] b[5] b[6]
99 12 34 7 36 16 14
import java.util.*;
class Sol28
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,b[]=new int[10],c=0,j,p=0;
System.out.println(“Enter 10 numbers:”);
for(i=0;i<10;i++) a[i]=sc.nextInt();
for(i=0;i<10;i++)
{
p=0;
for(j=i+1;j<10;j++)
{
if(a[i]==a[j])
p++;
}
if(p==0)
b[c++]=a[i];
}
System.out.println(“Resultant Array:”);
for(i=0;i<c;i++)
{
System.out.print(b[i]+“ ”);
}
}
}
29. Write a program to input 10 numbers into an integer array and store all even numbers into one
array and all odd numbers into another array. Display all the three arrays.
For example, if the given array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
99 12 34 7 87 36 94 16 14 45
The resultant arrays should be:
b[0] b[1] b[2] b[3] b[4] b[5]
12 34 36 94 16 14
259 Arrays
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
s+=a[i][j];
}
}
System.out.print(“Sum=”+s);
}}
31. Write a program to input numbers into a 5×5 integer matrix and print the largest and smallest
number from it.
Ans. import java.util.*; class
Sol31
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,l=0,s=0;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(i==0 && j==0)
l=s=a[i][j]; else
{ if(a[i][j]>l)
l=a[i][j];
if(a[i][j]<s)
s=a[i][j];
261 Arrays
if(i==0 && j==0) l=s=a[i][j]; else {
if(a[i][j]>l) l=a[i][j]; if(a[i][j]<s)
s=a[i][j];
}
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{ if(a[i][j]==l) a[i][j]=s; else
if(a[i][j]==s) a[i][j]=l;
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
System.out.print(“\t”+a[i][j]);
}
System.out.println();
}
}}
33. Write a program to input numbers into a 5×5 integer matrix and find the sum of each row
separately.
For example, if the given matrix is:
1 2 3 5 2
7 6 8 9 2
1 7 11 3 4
3 2 5 9 8
5 5 3 2 1
Output:
Sum of row 1 = 13
Sum of row 2 = 32
Sum of row 3 = 26
Sum of row 4 = 27
Sum of row 5 = 16
Ans.
import java.util.*;
263 Arrays
import java.util.*;
class Sol34
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,s=0;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(i=0;i<5;i++)
{
s=0;
for(j=0;j<5;j++)
{
s+=a[j][i];
}
System.out.println(“Sum of column” +(i+1)+ “= “+s);
}
}}
35. Write a program to input numbers into a 5×5 integer matrix and check whether all numbers in it
are even numbers or not.
Example 1:
If the given matrix is:
6 12 14 46 22
18 66 48 18 2
100 16 10 128 80
8 28 156 60 64
72 30 38 58 72
Output:
All are even numbers.
Example 2:
If the given matrix is:
6 12 14 45 22
265 Arrays
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,l=0,s=0;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
l=s=a[0][0];
for(i=0;i<5;i++)
{
if(a[i][i]>l)
l=a[i][i]; if(a[i][i]<s)
s=a[i][i];
if(a[i][4-i]>l)
l=a[i][4-i]; if(a[i][4-
i]<s) s=a[i][4-i];
}
System.out.println(“Largest=”+l);
System.out.println(“Smallest=”+s);
}}
37. Write a program to input numbers into a 5×5 integer matrix and sort the major diagonal
elements in descending order.
Ans.
import java.util.*;
class Sol37
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,t;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
267 Arrays
{
for(j=i+1;j<5;j++)
{
if(a[i][4-i]<a[j][4-j])
{
t=a[i][4-i]; a[i][4-
i]=a[j][4-j]; a[j][4-j]=t;
}
}
}
System.out.println(“Sorted Array:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
System.out.print(“\t”+a[i][j]);
}
System.out.println();
}
}
}
39. Write a program to input numbers into a 5×5 integer matrix and sort elements of each row
in ascending order.
Ans.
import java.util.*;
class Sol39
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,t,r;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(r=0;r<5;r++)
{
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
if(a[r][i]>a[r][j])
{
t=a[r][i];
a[r][i]=a[r][j];
a[r][j]=t;
}
}
}
}
System.out.println(“Sorted Array:”);
for(i=0;i<5;i++)
269 Arrays
{
for(j=0;j<5;j++)
{
System.out.print(“\t”+a[i][j]);
}
System.out.println();
}
}
}
40. Write a program to input numbers into a 5×5 integer matrix and sort elements of each
column in descending order.
Ans.
import java.util.*;
class Sol40
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,t,c;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(c=0;c<5;c++)
{
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
if(a[i][c]<a[j][c])
{
t=a[i][c];
a[i][c]=a[j][c];
a[j][c]=t;
}
}
}
}
System.out.println(“Sorted Array:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
System.out.print(“\t”+a[i][j]);
}
System.out.println();
}
}
}
41. Write a program to input numbers into a 5×5 integer matrix and print the number having
maximum frequency.
Ans.
import java.util.*;
class Sol41
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,t,r,c,p,max=0,n=0;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(r=0;r<5;r++)
{
for(c=0;c<5;c++)
{
p=0;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(a[r][c]==a[i][j])
p++;
271 Arrays
}
}
if(p>max)
{
max=p;
n=a[r][c];
}
}
}
System.out.println(“No. having maximum frquency=:”+n);
}
}
42. Write a program to input numbers into a 5×5 integer matrix and print the frequency of each
number.
Ans.
import java.util.*;
class Sol42
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,l=0,s=0,x,c;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(i==0 &&
j==0)
l=s=a[i][j]; else
{ if(a[i][j]>l)
l=a[i][j];
if(a[i][j]<s)
s=a[i][j];
}
}
}
for(x=s;x<=l;x++)
{ c=0;
for(i=0;i<5;i++)
for(j=0;j<5;j++)
{
if(x==a[i][j])
c++;
}
}
if(c>0)
System.out.println(“Frequency of”+x+“is=”+c);
}
}
}
43. Write a program to read in a 5×5 matrix and then ask for an input of a number and search its
position in the matrix. If found, print the indices where it is found, otherwise print “Not
Found”.
Ans.
import java.util.*;
class Sol43
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,f=0,n;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
System.out.println(“Enter the number to search:”);
n=sc.nextInt();
for(i=0;i<5;i++)
273 Arrays
{
for(j=0;j<5;j++)
{
if(a[i][j]==n)
{
System.out.println(“Position present at i=”+i+ “j=”+j);
f=1;
}
}
}
if(f==0)
System.out.println(“Not Found”);
}
}
44. Write a program to input numbers into a 5×5 integer matrix and check whether it is a unit
matrix or not. Unit matrix is such a matrix whose major diagonal elements are 1 and the
rest are 0.
Ans. import java.util.*;
class Sol44
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,f=0;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(i==j)
{
if(a[i][j]!=1)
f=1;
}
else
{
if(a[i][j]!=0)
f=1;
}
}
}
if(f==0)
System.out.println(“Unit Matrix”);
else
System.out.println(“Not a Unit Matrix”);
}
}
275 Arrays
45. Write a program to input numbers into a 5×5 integer matrix and check whether it is a
diagonal matrix or not. Diagonal matrix is such a matrix whose major diagonal elements are
non-zeroes and rest of the elements are zeroes.
Ans. import java.util.*;
class Sol45
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,f=0;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(i==j)
{
if(a[i][j]==0)
f=1;
}
else
{
if(a[i][j]!=0)
f=1;
}
}
}
if(f==0)
System.out.println(“Diagonal Matrix”);
else
System.out.println(“Not a Diagonal Matrix”);
}
}
277 Arrays
47. Write a program to input numbers into a 5×5 integer matrix and check whether it is a
symmetric matrix or not. Symmetric matrix is such a square matrix whose row elements are
exactly same as column elements. Thus a symmetric matrix is a square matrix that is equal
to its transpose.
Ans.
import java.util.*;
class Sol47
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,f=0;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(a[i][j]!=a[j][i])
f=1;
}
}
if(f==0)
System.out.println(“Symmetric Matrix”);
else
System.out.println(“Not a Symmetric Matrix”);
}
}
48. Write a program to input numbers into a 5×5 integer matrix and check whether it is a Lower
Triangular Matrix or not. Lower Triangular Matrix is such a matrix whose elements above
the major diagonal are zeroes and below the major diagonal are non-zeroes.
Ans.
import java.util.*;
class Sol48
{
279 Arrays
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[3][3],b[][]=new int[3][3],c[][]=new int[3][3],i,j;
System.out.println(“Enter the first matrix:”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a[i][j]=sc.nextInt();
}
}
System.out.println(“Enter the second matrix:”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
b[i][j]=sc.nextInt();
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(c[i][j]+“\t”);
}
System.out.println();
}
}
}
50. Write a program to input numbers into a 5×5 integer matrix and check whether it is zero or
null matrix or not. A null matrix is a matrix, whose all elements are zero.
Ans.
import java.util.*;
class Sol50
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[5][5],i,j,f=0;
System.out.println(“Enter 25 numbers:”);
for(i=0;i<5;i++)
{
281 Arrays
for(j=0;j<5;j++)
{
a[i][j]=sc.nextInt();
}
}
for(i=0;i<5;i++)
{
if(a[i][i]!=a[0][0])
f=1;
}
if(f==0)
System.out.println(“Scalar Matrix”);
else
System.out.println(“Not a Scalar Matrix”);
}
}
52. Create a class named Student containing the following instance variables:
Instance Variables:
roll[ ] of int type array reference.
name[ ] of String type array reference.
Member functions:
i. Parameterized constructor to initialize the data members.
ii. To accept a roll as parameter and search for it in roll[]. If found, the corresponding name should
be displayed otherwise a relevant message should be displayed.
Ans.
import java.util.*;
class Student
{ int
roll[];
String name[];
Student(int r[],String n[])
{
roll=r;
name=n;
}
void search(int r)
{ int
i,f=0;
for(i=0;i<roll.length;i++)
{
if (roll[i]==r)
283 Arrays
}
}
if(f==0)
System.out.println(“All no.s of the minor diagonal are prime”);
else
System.out.println(“All no.s of the minor diagonal are not prime”);
}
}
54. Write a program to input and sort the weight of ten people. Sort and display them in
descending order using the selection sort technique.
Ans.
import java.util.*;
class Sol54
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,j,s,p;
System.out.println(“Enter 10
numbers:”); for(i=0;i<10;i++)
a[i]=sc.nextInt();
for(i=0;i<9;i++)
{
s=a[i];p=i;
for(j=i+1;j<10;j++)
{
if(a[j]<s)
{
s=a[j];
p=j;
}
}
a[p]=a[i];
a[i]=s;
}
System.out.println(“Sorted Array:”);
for(i=0;i<10;i++)
{
System.out.print(a[i]+“ ”);
}
}
Write a program to read the data, calculate and display the following:
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.
import java.util.*;
class Sol55
{
static void main()
{
Scanner sc=new Scanner(System.in);
int roll[]=new int[50],i;
int m1[]=new int[50],m2[]=new int[50],m3[]=new int[50];
float av[]=new float[50];
System.out.println(“Enter the roll and marks:”);
for(i=0;i<50;i++)
{
roll[i]=sc.nextInt();
m1[i]=sc.nextInt();
m2[i]=sc.nextInt();
m3[i]=sc.nextInt();
av[i]=(float)(m1[i]+m2[i]+m3[i])/3;
}
System.out.println(“Average marks obtained by each student:”);
System.out.println(“Roll\t\tAverage”);
for(i=0;i<50;i++)
{
System.out.println(roll[i]+“\t\t”+av[i]);
}
System.out.println(“Average marks above 80 obtained by each student:”);
System.out.println(“Roll\t\tAverage”);
for(i=0;i<50;i++)
{
if(av[i]>80)
System.out.println(roll[i]+“\t\t”+av[i]);
}
285 Arrays
System.out.println(“Average marks below 40 obtained by each student:”);
System.out.println(“Roll\t\tAverage”);
for(i=0;i<50;i++)
{
if(av[i]<40)
System.out.println(roll[i]+“\t\t”+av[i]);
}
}
}
56. Write a program to store 6 element in an array P, and 4 elements in an array Q and produce
a third array R, containing all elements of array P and Q. Display the resultant array.
Ans.
class Sol56
{
static void main()
{
int
P[]={4,12,23,34,45,56};
int Q[]={17,15,12,23}; int
R[]=new int[10],i,c=0;
for(i=0;i<6;i++)
{
R[c++]=P[i];
}
for(i=0;i<4;i++)
{
R[c++]=Q[i];
}
System.out.println(“Resultant Array:”);
for(i=0;i<10;i++)
{
System.out.print(R[i]+“\t”);
}
}
}
57. 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”.
287 Arrays
static void main()
{
Scanner sc=new Scanner(System.in);
int N,i,s=0;
System.out.println(“Enter the no. of students:”);
N=sc.nextInt();
String name[]=new String[N];
int totalmarks[]=new int[N];
float avg,dev;
System.out.println(“Enter the name and total marks:”);
for(i=0;i<N;i++)
{
name[i]=sc.nextLine();
totalmarks[i]=sc.nextInt();
s+=totalmarks[i];
}
avg=(float)s/N;
System.out.println(“Average marks obtained by the students:”+avg);
System.out.println(“Deviation of each student’s total marks with the average”);
for(i=0;i<N;i++)
{
dev=totalmarks[i]-avg;
System.out.println(name[i]+“\t\t”+dev);
}
}
}
3. Write a program to input a sentence and count the number of vowels in it.
Ans. import java.util.*; class Sol3
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s;
int i,c=0;
System.out.println(“Enter a sentence:”);
s=sc.nextLine(); s=s.toUpperCase();
for(i=0;i<s.length();i++)
{
char x=s.charAt(i);
if (x==‘A’ || x==‘E’ || x==‘I’ || x==‘O’ || x==‘U’) c++;
}
System.out.println(“No. of vowels:”+c);
}
}
4. Write a method to accept a word and print it in the following way:
Parameter-> TRIAL
Output-> L
AL
IAL
RIAL
TRIAL
16. In a set of 50 names, it is intended to find the total number of names which contains at least one
pair of consecutive letters, e.g., SURABHI. In this ‘A’ and ‘B’ are consecutive letters and ‘H’ and
‘I’ are consecutive letters. Write a program for the above program.
Ans.
import java.util.*; class
Sol16
{ static void main()
{
Scanner sc=new Scanner(System.in);
String s[]=new String[50]; int i,c=0,j;
System.out.println(“Enter 50 names:”);
for(i=0;i<50;i++) s[i]=sc.nextLine();
for(i=0;i<50;i++)
{
for(j=0;j<s[i].length()-1;j++)
{
if((char)(s[i].charAt(j)+1)==s[i].charAt(j))
{
c++;
break;
}
}
}
System.out.println(“No. of words :”+c);
}
}
for(i=0;i<s.length()-1;i++)
{
if((char)(s.charAt(i)+1)== s.charAt(i+1))
c++; }
System.out.println(“Pairs of consecutive letter :”+c);
}}
19. Pig Latin is a language game of alterations played in English. To form the Pig Latin form of an
English word the initial consonant sound is transposed to the end of the word and an ay is
affixed (for example, trash yields ash-tray and plunder yields under-play). Write a program to
input a word and change it to Pig Latin.
Ans.
import java.util.*;
class Sol19
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s,n;
int i;
System.out.println(“Enter a word:”);
s=sc.nextLine().toUpperCase();
for(i=0;i<s.length();i++)
{
char x=s.charAt(i);
if(x==‘A’ || x==‘E’ || x==‘I’ || x==‘O’ || x==‘U’)
break;
}
Question 1
(a) Differentiate between class variable and instance variable.
(b) Mention two difference between Binary search and Linear search.
(c) Define wrapper class.
Question 7
Write a menu driven program using function overloading (the function name is display) to perform
the following:
(a) To find the sum of the series up to the limit given by user i.e 2+3+5+7+11+……………..
(b) To print the following pattern:
000
001
010
011
100
101
110
111
Ans. class Q7
{
static void display(int n)
{ int i,j,s=0,c; for(i=1;i<=n;i++)
{ c=0; for(j=0;j<=i;j++)
{ if (i%j==0) c++;
} if(c==2) s+=i;
Question 9
(a) WAP to calculate the sum of the following series.
S = 1/2! – 2/5! – 4/10! + 8/17! – 16/26! – 32/37! + 64/50! ……..n terms (b)
WAP to display the chain of 5 consecutive composite numbers within 1 to 100.
e.g 24, 25, 26, 27, 28
62, 63, 64, 65, 66
*******************************
Ans.
(a) import java.util.*; class Q9a
{
static void main()
{
Scanner sc=new Scanner(System.in); int n,i,p,m=2,c=3,v=1,j,b=0; double
s=0;
System.out.println(“Enter the no. of terms:”); n=sc.nextInt(); for(i=1;i<=n;i++)
{ p=1; for(j=1;j<=m;j++) p=p*j; m=m+c;
c=c+2; if(b%3==0) s=s+(double)v/p; else s=s-
(double)v/p; v=2*v;b++;
}
System.out.println(“Sum=”+s);
}
}
}
}
(c) The switch statement is a multi-way branch statement. The switch statement of Java is
another selection statement that defines multiple paths of execution of a program. It
provides a better alternative than a large series of if-else-if statements.
(d) Set of numbers: 23, 45, -33, 533, 100
Ascending Order: -33, 23, 45, 100, 533
Lower limit Upper limit Mid Check
0 4 2 45<500
3 4 3 100<500
4 4 4 533>500
4 3 --- Not found
(e) A control variable in computer programming is a program variable that is used to regulate
the flow of control of the program. In definite iteration, control variables are variables
which are successively assigned (or bound to) values from a predetermined sequence of
values.
Question 2
(a) Why is a class known as composite data type?
(b) What is Recursive method?
(c) What is Function Signature?
(d) Differentiate a constructor from a destructor.
(e) Which unit of a class gets called when the object of the class is created?
Ans.
(a) A composite data type is one which is composed with various primitive data type. A class
defined with various primitive data types such as int, double etc; so it is known as a
composite data type; and it is used to create objects which hold similar types of values and
behaviours (functions).
(b) Recursion is a basic programming technique you can use in Java, in which a method calls
itself to solve some problem. A method that uses this technique is recursive method.
(c) A function signature (or type signature, or method signature) defines input and output of
functions or methods. A signature can include: parameters and their types. a return value
and type. exceptions that might be thrown or passed back.
Question 4
(a) Read the following overloaded method prototypes and answer the question that follow:
void calculate ( int x, double y ); void calculate ( double x, double y, double z);
(i) Write the java statement to invoke the method “calculate” using actual parameters a = 20, b =
45.52.
Question 5
Binomial co-efficient can be calculated by using the following formula:
n!
nCm = ---------------- [where! sign represents the factorial of a number]
m! (n – m)!
>=20,000 53 12 10 8
< 10,000 40 8 14 7
void display()
{
System.out.println(“EMPLOYEE No.\t\tNAME\t\tGROSS SALARY\t\tPF”);
System.out.println(Emp_No+“\t\t”+Name+“\t\t”+gross+“\t\t”+PF);
}
} else
System.out.println(“Nearest Prime:”+n);
}
}
Question 8
Write a menu driven program in java to perform the following ( using switch case ):
(i) to print the value of S where
S = 1/1! + ( 1 + 2 )/( 1! + 2! ) + ( 1 + 2 + 3 ) / ( 1! + 2! + 3! ) + …….… upto n terms.
(ii) to print the value of S where
S = 1n + 2(n-1) + ...…………………………….……….. + (n-1)2 + n1 Ans.
import java.util.*; class Q8
{
static long fact(long k)
{
long i,f=1; for(i=1;i<=k;i++)
k=k*i;
return k;
}
System.out.println(“Sum=”+s);
break; case 2:
System.out.println(“Enter the value of n:”);
n=sc.nextInt();
for(i=1,j=n;i<=n;i++,j--)
{
b=b+i*j;
}
System.out.println(“Sum=”+b);
break; default:
System.out.println(“Invalid choice”);
}
}
}
Question 9
WAP in java to accept the NAME and TOTAL MARKS obtained in an exam of a class having N number
of students and display the NAME and TOTAL MARKS of the students according to the rank 1st,
2nd and 3rd.
Ans.
import java.util.*;
class Q9
{
Question 1
(a) What is the difference between an object and a class?
(b) What does the token ‘keyword’ refer to, in the context of Java? Give an example for keyword.
(c) What is the difference between entry controlled and exit controlled loop?
(d) What are the two ways of invoking functions?
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.
(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.
(c) Give the output of the following:
String n=“Computer Kowledge”;
String m=“Computer Applications”;
System.out.println(n.substring(0,8).concat(m.substring(9)));
System.out.println(n.endsWith(“e”)); (d)
Write the output of the following:
(i) System.out.println(Character.isUpperCase(‘R’));
(ii) System.out.println(Character.toUpperCase(‘j’));
(e) What is the role of keyword void in declaring functions?
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?
int p=200;
while(true)
{
if(p<100)
break;
p=p-20;
}
System.out.println(p);
(b) What will be the output of the following code?
(i) int k=5, j=9; k+ = k++ - ++j + k;
System.out.println(“k=”+k);
System.out.println(“j=”+j);
(ii) double b=-15.6;
double a=Math.rint(Math.abs(b));
System.out.println(“a=”+a);
(c) Explain the concept of constructor overloading with an example.
(d) Give the prototype of a function search which receives a sentence sentnc and a word wrd and
returns 1 or 0.
(e) Write an expression in Java for
(f) Write a statement each to perform the following task on a string:
(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.
(g) Name the keyword that
(i) informs that an error has occurred in an input/output operation.
Question 4
Define a class called mobike with the following description:
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 compute() - to compute the rental charge.
The rent for a mobike is charged on the following rental basis:
First five days ` 500 per day.
Next five days ` 400 per day
Rest of the days ` 200 per day.
void display() to display the details in the following format:
Bike No. Phone No. Name No. of days Charge
_______ ________ _________ ________ _______
Ans.
import java.util.*;
class mobike
{
int bno,phno,days,charge;
String name;
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the details:”);
Question 5
Write a program to input and store the weight of ten people. Sort and display them in descending
order using the selection sort technique.
Ans.
import java.util.*;
class Q5
{
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 special number, if the sum of the factorial of the digits of the number is
same as the original number).
Example: 145 is a special number, because 1!+4!+5!=1+24+120=145
(Where ! stands for factorial of the number and the factorial value of a number is the product of
all integers from 1 to that number, example 5!=1*2*3*4*5=120).
Ans.
import java.util.*;
class Q6
{ static int fact(int
k)
{ int i,f=1;
for(i=1;i<=k;i++)
k=k*i; return k;
}
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.
Example:
Sample Input: ComPuter
Sample output: cpmpvtfr
Ans.
import java.util.*;
class Q7
{ static void
main()
{
int i;
String w,n=“ ”;
Scanner sc=new
Scanner(System.in);
System.out.println(“Enter a word:”);
w=sc.nextLine();
w=w.toLowerCase();
for(i=0;i<w.length();i++)
{
char x=w.charAt(i); if(x==‘a’ ||
x==‘e’ || x==‘i’ || x==‘o’ || x==‘u’)
n=n+(char)(x+1); else n=n+x;
}
System.out.println(“New word:”+n);
}
}
Question 9
Write a menu driven program to perform the following: (Use switch-case statement) (i) To print
the series 0,3,8,15,24… n terms(value of ‘n’ is to be an input by the user.) (ii) To find the sum of
the series given below:
S=1/2+3/4+5/6+7/8+--------19/20 Ans.
The loop do not execute if the condition is The loop executes at least once even if the
false. condition is false.
(d) A Wrapper class is a class whose object wraps or contains a primitive data types. When we
create an object to a wrapper class, it contains a field and in this field, we can store a
primitive data types. In other words, we can wrap a primitive value into a wrapper class
object. Example- Integer, Character Float, Short etc.
(e) (i) 2 bytes
(ii) 8 bytes
(iii) 8 bytes
(iv) 2 bytes
Question 5
Write a Java program to print the first 15 numbers of the Pell series.
In mathematics, the Pell numbers are an infinite sequence of integers. The Sequence of Pell
numbers starts with 0 and 1, and then each Pell number is the sum of twice the previous Pell
number and the Pell number before that.: thus, 70 is the companion to 29, and 70 = 2 x 29 +
12 = 58 + 12. The first few terms of the sequences are: 0, 1, 2, 5, 12, 29, 70, 169, 408, 985, 2378,
5741, 13860…
Question 6
Maharashtra State Electricity board charges their consumers according to the units consumed (per
month) as per the given tariff: UNITS CONSUMED CHARGES Up to 100 units 80 paise / unit
More than 100 upto 200 units `. 1 / unit More than 200 units ` 1.25 / unit
In addition to the above mentioned charges, every consumer has to pay ` 50 as Service Charge per
month and calculate the Electricity Bill. Write a program to create the object of the class and
call the member methods.
Ans.
import java.util.*;
class Q6
{
void calc()
{
Scanner sc=new
Scanner(System.in); int units;
double charge;
System.out.println(“Enter the no. of
units:”); units=sc.nextInt();
if(units<=100) charge=units*0.80; else
if(units<=200)
charge=100*0.80+(units-100)*1.00;
else
charge=100*0.80+100*1.00+(units-200)*1.25;
charge=50+charge; System.out.println(“Charge:”+charge);
Question 8
Design a class to overload a function prStr() are as follows: void prStr(String s1, String s2) – Print
the string that has more number of vowels from amongst s1 and s2.
void prStr(String s, char ch) – Replace all blank spaces from String s with ch and print the String
s. void prStr(String s) – Print the first and last position of letter ‘G’ in String s.
Ans.
class Overload
{
void prStr(String s1, String s2)
{
int i,c1=0,c2=0;
s1=s1.toUpperCase();
s2=s2.toUpperCase();
for(i=0;i<s1.length();i++)
{
char x=s1.charAt(i);
if (x==‘A’ || x==‘E’ || x==‘I’ || x==‘O’ || x==‘U’)
c1++;
}
for(i=0;i<s2.length();i++)
{
char x=s2.charAt(i);
if (x==‘A’ || x==‘E’ || x==‘I’ || x==‘O’ || x==‘U’)
c2++;
}
if(c1>c2)
System.out.println(s1);
else
System.out.println(s2);
}
void prStr(String s, char ch)
{
Question 9
Write a program using switch-case statements: 1. input an string array of size 10 and sort them in
descending order using bubble sort technique. 2. initialize an array of size 9 Indian currency
notes and initialize another array with their respective currency serial numbers. Search for a
currency note input by the user, in the list.
If found, display “Search Successful” and print the currency along with the serial number, otherwise
display “Search unsuccessful Name not enlisted.” Write an appropriate message for incorrect
option.
Ans.
import java.util.*;
class Q9
{
(d) A stream can be defined as a sequence of data. The InputStream is used to read data from a
source and the OutputStream is used for writing data to a destination.
(e) Strings are immutable in Java it means once created you cannot modify content of String. If
you modify it by using toLowerCase(), toUpperCase() or any other method, It always result in
new String. Since String is final there is no way anyone can extend String or override any of
String functionality.
(f) anytine
Java is Funamytime
(g) if(n%2==0 && n>35 && n<67)
a=a+4;
if(n%2==0 && n>35 && n<67)
n=n/a;
if(n%2==0 && n>35 && n<67)
rem=n%10;
Question 6
Write a program to accept numbers in a 4×4 matrix, then print the all prime numbers present in the
matrix with array Index value.
SAMPLE DATA: INPUT:
Question 8
Write a menu driven class to accept a number and check whether it is
(a) Palprime number – [a number is a palindrome and a prime number Eg. 101]
Ans.
import java.util.*;
class Q8
{
Question 9
Write a program to input a word in uppercase and rearrange the characters of the word in
alphabetical order.
Ans.
import java.util.*; class
Q9
{
static void main()
{
String w,n=“ ”; char x;
int i;
Scanner sc=new Scanner(System.in); System.out.println(“Enter a word:”); w=sc.nextLine();
w=w.toUpperCase();
for(x=‘A’;x<=‘Z’;x++)
{
for(i=0;i<w.length();i++)
{
if(w.charAt(i)==x) n+=x;
}
}
System.out.println(n);
}
}