Perfect number Program (ISC 2018)- recursive technique


Design a class Perfect to check if a given number is a perfect number or not. (A number is said to be perfect if sum of the factors of the number excluding itself is equal to the original number.)
Example : 6= 1+2+3 ( where 1, 2 and 3 are the factors of 6, excluding itself)

Class name    : Perfect
Data members:
num         : to store the number
Member  methods:
Perfect(int nn)     :  initialize the data member num=nn
int sumofFact(int i) : return the sum of the factors of the number, excluding itself, using recursive technique.
void check()       : checks whether the given number is perfect by invoking the function sumofFact()   and  displays the result with an appropriate message.
Specify the class  and define main() to create an object and call the functions accordingly to enable the task.

Program:
import java.util.*;
class Perfect
{
int num;
Perfect(int nn)
{
num=nn;
}
public int sumofFact(int i)
{
int n=num;
if(i>n/2)
return 1;
else
{
if(n %i==0)
return i +sumofFact(i+1);
else
return sumofFact(i+1);
}
}
public void check()
{
int s=sumofFact(2);
if(s==num)
System.out.println(num+”is a perfect number”);
else
System.out.println(num+”is not a perfect number”);
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a number”);
int n= sc.nextInt();
Perfect obj=new Perfect(n);
obj.check();
}
}

Output:

Enter a number
28
28 is a perfect number
Enter a number
8128
8128 is a perfect number
Enter a number
46
46 is not a perfect number

Subtraction of matrix (object)


A class matrix  contains a @d integer array of order[m * n]. The maximum value possible for both m and n is 10. Design a class matrix to find the difference of the two matrices. the details of the members of the class are given below:
Class name     : matrix
Data members:
atm[][]      : to store the matrix
m, n          :  integer to store the number of rows and columns
Member functions:
Matrix(…..)   : initialize m, n  and to allocate memory to member array
void fnGet()   : to fill the member array
void fnDisplay() : to show the member matrix
Matrix fnSub(Matrix A)  : Subtract the current object from the matrix of parameterized object and return the resulting object.
Specify the class Matrix,  Define main(), giving the details of the above member data and methods only.

Program:

import java.util.*;
class Matrix
{
int atm[][];
int m,n;

public Matrix(int r, int c)
{m=r;
n=c;
atm= new int [m][n];

}
void fnGet()
{
Scanner sc=new Scanner(System.in);
int i,j;
System.out.println(“Enter the elements:”);
for(i=0;i<m;i++){
System.out.println(“Enter the elements of row:”+(i+1));
{for(j=0;j<n;j++)
{
atm[i][j]=sc.nextInt();
}
System.out.println();
}}
}
void fnDisplay()
{
System.out.println(“The array elements:”);
int i,j;
for(i=0;i<m;i++)
{for(j=0;j<n;j++)
{
System.out.print(atm[i][j]+”\t”);
}
System.out.println();
}
}
public Matrix1 fnSub(Matrix1 o1)
{
int i, j;
Matrix1 o3=new Matrix1(m,n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
o3.atm[i][j]=o1.atm[i][j]-atm[i][j];
return o3;
}

public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the values of row and columns:”);
int r=sc.nextInt();
int c=sc.nextInt();
Matrix m1=new Matrix(r,c);
Matrix m2=new Matrix(r,c);
Matrix m3=new Matrix(r,c);
System.out.println(“Enter the 1st array:”);
m1.fnGet();
System.out.println(“Enter the 2nd array”);
m2.fnGet();

System.out.println(“\u000c”);
System.out.println(“array1 elements:”);
m1.fnDisplay();
System.out.println(“array2 elements:”);
m2.fnDisplay();
m3=m2.fnSub(m1);

System.out.println(“Subtracted” );
m3.fnDisplay();
}
}

Output:

Enter the values of row and columns:
2
3
Enter the 1st array:
Enter the elements:
Enter the elements of row:1
9
8
7

Enter the elements of row:2
6
5
4

Enter the 2nd array
Enter the elements:
Enter the elements of row:1
6
5
4

Enter the elements of row:2
4
3
2

array1 elements:
The array elements:
9 8 7
6 5 4
array2 elements:
The array elements:
6 5 4
4 3 2
Subtracted
The array elements:
3 3 3
2 2 2

 

 

Anti clockwise spiral matrix / anti clockwise circular matrix – java


import java.util.*;
class anticlockwise
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements : ");
int n = sc.nextInt();

int A[][] = new int[n][n];
int k=n*n, c1=0, c2=n-1, r1=0, r2=n-1;

while(k>=1)
{
for(int i=c1;i<=c2;i++)
{
A[r1][i]=k--;
}

for(int j=r1+1;j<=r2;j++)
{
A[j][c2]=k--;
}

for(int i=c2-1;i>=c1;i--)
{
A[r2][i]=k--;
}

for(int j=r2-1;j>=r1+1;j--)
{
A[j][c1]=k--;
}
c1++;
c2--;
r1++;
r2--;
}

/* Printing the Circular matrix */
System.out.println("The Circular Matrix is:");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(A[i][j]+ "\t");
}
System.out.println();
}
}
}

Output:

Enter the number of elements : 4
The Circular Matrix is:
16 15 14 13
5 4 3 12
6 1 2 11
7 8 9 10

Transpose of a matrix using object


The transpose of a matrix is found by interchanging the elements of rows and columns.
Design a class matrix that contains a 2D array of order [n * n ]. The maximum value possible for n is 20. The details of some of the members of the class are given below
Class name    : matrix
Data members:
int t[][]                   : to store the matrix
int n                        : integer to store the number of rows and columns
Member functions:
matrix(…..)             : parameterized constructor to initialize n and to allocate memory to member array
void fnGet()       :  to fill the member array
void fnDisplay() : to show the member matrix
matrix fnTrans(matrix A)  : to store the transpose of the argument matrix in the current object and return that.
Specify the class matrix giving the details of the above member data and methods only.

 

Program:

import java.util.*;
class matrix
{
int t[][];
int n;

public matrix(int n1)
{n=n1;
t= new int [n][n];

}
void get()
{
Scanner sc=new Scanner(System.in);
int i,j;
for(i=0;i<n;i++)
{for(j=0;j<n;j++)
{
t[i][j]=sc.nextInt();
}
}
}
void disp()
{
int i,j;
for(i=0;i<n;i++)
{for(j=0;j<n;j++)
{
System.out.print(t[i][j]+”\t”);
}
System.out.println();
}
}
public matrix Trans(matrix o1)
{
int i, j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
t[i][j]=o1.t[j][i];
return this;
}

public static void main(String args[])
{
matrix m1=new matrix(3);
matrix o1=new matrix(3);
matrix o2=new matrix(3);
m1.get();
m1.disp();
o2=o2.Trans(m1);

System.out.println(“Transpose of matrix”);
o2.disp();
}
}

 

Output:

Enter the elements:
9
8
7
6
5
4
3
2
1
9 8 7
6 5 4
3 2 1
Transpose of matrix
9 6 3
8 5 2
7 4 1

Object as parameter


Money is an unit that has 2 parts, Rupees and Paise, where 100 Paise=1 Rupee.
Design a  class named Money whose details are as follows:
Class Name : Money
Data member:
int rs, ps  : integer to store the value of Rupees and paise.
Member methods:
Money(…..)     : parameterized constructor to initialize member data
void fnShow()  : to show the member data as Money [Rs 819.75]
Money fnAdd(Money m1, Money m2) :
Add m1 and m2. Store the result in corresponding member data and return it.

Specify the class Money, giving the details of the above member data and methods. Also write the main() to create objects and call the other methods accordingly to enable the task of the adding 2 units on Money.

Program:

import java.util.*;
class Money
{
    int rs, ps;
    public Money(int rs1, int ps1)
    {
        rs=rs1;
        ps=ps1; }
        public Money()
        {
            rs=0;
            ps=0;
        }
        void fnShow()
        {
           System.out.println("Rs"+rs+"."+ps);
        }
        Money fnAdd(Money m1, Money m2)
        {
            rs=m1.rs+m2.rs;
            ps=m1.ps+m2.ps;
            if(ps>=100)
            {
                rs++;
                ps-=100;
            }
         return this;
        }

    public static void main(String args[])
    {   
        Money Am =new Money(200, 50);
        Money bm=new Money(200,50);
        Money sm=new Money();
        sm.fnAdd(Am,bm);
        System.out.print("\n Money 1: ");
        Am.fnShow();
        System.out.print("\n Money 2: ");
        bm.fnShow();
        System.out.print("\n Money 1 + Money 2: ");
        sm.fnShow();
    }

}



Output:

Money 1:  Rs200.50

Money 2:  Rs200.50

Money 1 + Money 2   :     Rs401.0

Model Question Paper June 2018-ISC Computer Science


Model Question Paper ISC Computer Science 2018

PART – I (20 Marks)
Answer all questions.
While answering questions in this Part, indicate briefly your working and
reasoning, wherever required.

Question 1

  1. Write the distributive laws. Prove anyone using truth table.
  2. Simplify the expression using Boolean laws
    F1=(a+c’).(a’+b’+c’)
  3. Find the complement of :
    F 2 =ab’ + a’ + a’b+b’
  1. Verify using truth table ( ~p ^ q) V (p^q) = q.
  2. Write the dual of F3 = (p +1).(q’ + 0)

Question 2

  1. An array D [-2…10][3…8] contains double type elements. If the base address is 4110, find the address of D[4][5], when the array is stored in Column Major Wise
  2. I) Name the keyword it is used for memory allocation.                                          
  3. Write the syntax of a character input.
  4. If (~P => Q) then write its:
  5. Inverse ii)         Converse
  6. Differentiate between a method and a constructor of a class.
  7. State De Morgan’s laws. Verify anyone using a truth table                                         

Question 3

  1. Given the following method

void fnM(int p)

{

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

for( int j=1; j<=RM.length-1; j++)

{

RM[j-1] = RM[j-1] +RM[j];

RM[j] = RM[j-1] *2;

}

System.out.print(“OUTCOME=” +RM[p]);

}

  • What will be the output if p=1?
  • What will be the output if p=4?
  • Which token finds the size of the array?

                                                     PART II (50 Marks)

          Answer six questions in this part, choosing two questions from Section A,
                              two from Section B and two from Section C.
SECTION – A
                                               Answer any two questions

Question 4

  • Given the Boolean function : F(A,B,C,D) =Ʃ(0,2,3,6,7,8,10,12,13,14,15)

  • Reduce the above expression by using 4 variable Karnaugh map, showing
    the various groups (i.e., octal, quads, pairs).
  • Draw the logic gate diagram for the reduced expression. Assume that the
    variables and their complements are available as inputs.
  • Given the Boolean function : F(P, Q,R,S) =Π (0, 1, 2, 4, 5, 6, 8, 10)
  • Reduce the above expression by using 4 variable Karnaugh map, showing
    the various groups (i.e., octal, quads, pairs).
  • Draw the logic gate diagram for the reduced expression. Assume that the
    variables and their complements are available as inputs.

Question 5

  • Given the Boolean function: F(A,B,C,D)= Π (0,1,2,3,5,7,8,9,10,11)
    Reduce  the above expression by using 4-variable K map, showing the various groups (i.e., octet, quads and pairs)
  • Given the Boolean function : F(A,B,C,D) =ABC’D’ +A’BC’D’ + A’BC’D + ABC’D+ A’BCD+ABCD
    Reduce the above expression by using 4 variable K map showing the various groups ( octet, quads and pairs).

Question 6

A school intends to select candidates for an inter-school essay competition as per the criteria given below:

The student has participated in an earlier competition and is very creative.
OR
The student is very creative and has excellent general awareness, but has not participated in any competition earlier.

 OR

The student has excellent general awareness and has won prize in an inter-house competition.

The inputs are:

INPUTS
A                     participated in a competition earlier
B                      is very creative
C                     won prize in an inter-house competition
D                     has excellent general awareness
(in all the above cases 1 indicates yes and 0 indicates no for all cases)

Output: X [1 indicates yes, 0 indicates no for all cases]
Draw the truth table for the inputs and outputs given above and write the POS expression for X(A,B,C,D).

  • Write the idempotence law and verify using truth table.
  • Convert the following Boolean expression into its Canonical POS form:            F(A,B,C) = (B+C’).(A’+B)

                                            SECTION – B

                             Answer any two questions.

Each program should be written in such a way that it clearly depicts the logic of the problem. This can be achieved by using mnemonic names and comments in the program.
(Flowcharts and Algorithms are
not required.)
The programs must be written in Java.

Question 7

A Special is a number in which the sum of the factorial of its digits is equal                  to the number. Example  1!+4!+5! =145. Thus 145 is a special number.
Design a class Special to check if the number is a Special number or not. Some of the members of the class are given below:

Class Name                :                                   Special
Data member/Instance Variables:   n :          integer  to store the number
Member functions:
Special()                                   : constructor to initialize data members with legal initial values
void accept()                            : to accept the number
int factorial(int x)                       : returns the factorial of a number using recursive technique.
boolean isSpecial()                   : checks for the special number by invoking the function factorial() and returns true if Special, otherwise returns false.
void display()                            : to display the result with an appropriate message.

Specify the class Special, giving the details of the above member data and methods only. Define the main() function to create an object and call the member function accordingly to enable the task.

Question 8                                                                                                                              [10]

A beam number is a number in which the sum of the square of the digits of the number is larger than the number itself.

For example  :  N= 25 Sum of square of digits = 22 + 52 = 4 +25 = 29
Number 25 is a Beam Number
For example  : N = 34 Sum  of square of digits = 32+ 42  = 9 + 16 = 25
Number 34 is Not a Beam Number
Design a class BEAM to check if a given number is a beam number.

Class Name                                        : BEAM
Data Member/Instance Variables    :
int m                                                     : integer
Member Functions:
BEAM()                                               : Constructor to initialize member data to null
void fnGet( int mm)                               : To input value for the member data
int fnSqSum (int d)                                : To return the sum of the square of the digits of the argument
For example : d= 69
Final method return 62 + 9 2 = 36 +81 = 117
boolean isBeam()                                  : To  verify whether the member data is a Beam Number or not as per the criteria given above.
Specify the class
BEAM, giving details of the above member data and methods only. Also define the main() to create an object and call the other methods accordingly to enable the task.

Question 9                                                                                                                              [10]

Write a class called Numbers with following specifications:

ArmStrong Number = 407= 43+03+73

ArmStrongLike Numbers = 165033 = 163+503+333

Class Name                                        : Numbers
Data Member/Instance Variables    :
number                                     : long type
Member Functions:
boolean isArmStrong()              : checks whether the number is Armstrong or not.
boolean isArmStrongLike()                   : checks whether the number is ArmstrongLike numbers or not.
void genArmStrongNos()                      : generates Armstrong number

void genArmStrongLikeNo()                : generates Armstrong number Like

Specify the class Numbers, giving the details of the above member data and methods only. Define the main() function to create an object and call the member function accordingly to enable the task.

SECTION – C

Answer any two questions.

Each program should be written in such a way that it clearly depicts the logic of the problem. This can be achieved by using mnemonic names and comments in the program.
(Flowcharts and Algorithms are
not required.)
The programs must be written in Java.

Question 10                                                                                                                [5]

Show the output of the following code;

public class BreakDemo

{

   public static void main(String[] args)

   {

      for (int i = 1; i <= 10; i++)

      {

         if (i == 5)

         {

            break;   

         }

    System.out.print(i + ” “);

      }

  System.out.println(“Loop is over.”);

   }

          }

 Question 11                                                                                                                [5]

The following function is a part of some class. Assume n is a positive integer. Answer the given questions along with dry run/working.

int unknown(int n)

{

int I, K;

if(n%2==0)

{
I=n/2;

            K=1;

}

else

{

K=n;

n–;

I= n/2;

}

while(I >0)

{

K=K*I*n;

I–;

n–;

}

return k;

}

  • What will be returned by unknown(5) ?
  • What will be returned by unknown(7) ?

Question 12                                                                                                                [5]

Briefly describe static and instance member with example.

 

 

Model Question Paper – ISC computer science -July 2018


PART – I (20 Marks)
Answer all questions.
While answering questions in this Part, indicate briefly your working and
reasoning, wherever required.

Question 1

  1. State the involution law. Prove anyone using truth table.                       [1]
  2. Simplify expression using Boolean laws
    F1=a.b’ + a’ + a’.b +b’                                                                                                [1]
  3. Find the complement of :

F 2 =(a’ +c’ +d)(b +c+d’)(a+b’+c)                                                                                        [1]

  1. Verify using truth table ( ~p ^ q) V (p^q) = q.                                                  [1]
  2. Write the dual of F3 = p’.0 + q.1 +r’                                                                     [1]

Question 2

  1. An array D [-2…10][3…8] contains double type elements. If the base address is
    4110, find the address of D[5][5], when the array is stored in Column Major Wise. [2]
  2. I) What do you understand by the keyword : Integer                                          [2]      
  3. Write the syntax of a string input.
  4. From the premises p àq and q àp, conclude q’ +pq                                               [2]
  5. What are wrapper classes? Give two examples.                                                    [2]
  6. State De Morgan’s laws. Verify anyone using truth table                                    [2]

 

 


Question 3

  1. Given the following method                                                                                          [5]

void fnM(int p)

{

int RM[]={3,6,9,12,15};

for( int j=1; j<=RM.length-1; j++)

{

RM[j-1] = RM[j-1] +RM[j];

RM[j] = RM[j-1] *3;

}

System.out.print(“OUTCOME=” +RM[p]);

}
i)What will be the output if p=2?
ii)What will be the output if p=4?
iii)Which token finds the size of the array?
PART II (50 Marks)
Answer six questions in this part, choosing two questions from Section A,
                               two from Section B and two from Section C.
SECTION – A
                                    Answer any two questions

Question 4

  • Given the Boolean function : F(A,B,C,D) =Ʃ(0,2,4,5,8,9,10,12,13)
    i)  Reduce the above expression by using 4 variable Karnaugh map, showing                                                                                                                                 [4]
    the various groups (i.e., octal, quads, pairs).
    ii) Draw the logic gate diagram for the reduced expression. Assume that the                                                                                                                                           [1]
    variables and their complements are available as inputs.
  • Given the Boolean function : F(P, Q,R,S) =Π (0, 1, 3, 5,7, 8, 9,10,11,14,15)
  • Reduce the above expression by using 4 variable Karnaugh map, showing   [4]
    the various groups (i.e., octal, quads, pairs).
  • Draw the logic gate diagram for the reduced expression. Assume that the        [1]
    variables and their complements are available as inputs.

Question 5

  • Given the Boolean function: F(A,B,C,D)=  Ʃ(5,6,7,8,9,10,14)
    a. Reduce  the above expression by using 4-variable K map, showing the various groups   (i.e., octet, quads and pairs)                                                                                                                                         [4]
  1. b. Draw the logic gate diagram for the reduced expression. Assume that the  [1]
    variables and their complements are available as inputs.

 

  • Given the Boolean function: F (A, B, C, D) =(A+B+C+D)(A+B+C+D’)(A+B+C’+D’)(A+B+C’+D)(A+B’+C+D’)(A+B’+C’+D)(A’+B+C+D)(A’+B+C’+D)
    Reduce the above expression by using 4 variable K map showing the various     groups (i.e., octet, quads and pairs).             
  1. Draw the logic gate diagram for the reduced expression. Assume that the
    variables and their complements are available as inputs                                                             

Question 6

A person is allowed to travel in a reserved coach of the train, if he/she satisfies any one of the criteria given below:

The person has a valid reservation ticket and a valid ID, proof.

The person does not have a valid reservation ticket, but holds a valid pass issued by the Railway department with a valid ID proof.

The person is a senior citizen and holds a valid pass issued by the Railway department along with a valid ID proof.
The inputs are:

INPUTS
R                     The person has a valid reservation ticket

P                      The person holds a valid pass issued by the Railway department

D                     The person has a valid ID proof.

S                      The person is a senior citizen
(in all the above cases 1 indicates yes and 0 indicates no for all cases)

Output:            T – Denotes allowed to travel [1 indicates yes and 0 indicates no.]
Draw the truth table for the inputs and outputs given above and write the SOP expression for T(R, P, D and S).                                                                                                    

What is redundant group?                                                   [2]
Convert the following Boolean expression into its Canonical SOP form:             [3]
XY’ + X’Y + X’Z’                

                                              SECTION – B

                                      Answer any two questions.

Each program should be written in such a way that it clearly depicts the logic of the problem. This can be achieved by using mnemonic names and comments in the program.
(Flowcharts and Algorithms are
not required.)
The programs must be written in Java.

Question 7

A class SeriesSum is desgined to calculate the sum of the following series:                         [10]
Sum = x2/1! + x4/3! + x6/5! + xn/(n-1)!
Some of the members of the class are given below:
class name                   :           SeriesSum
Data members/ instance variables :
x                      :           to store an integer number
n                      :           to store number of terms
sum                  :           double variable to store the sum of the series

Member functions:
SeriesSum(int xx, int nm)       : constructor to assign x=xx and n=nn
double findfact(int m)                        : to return the factorial of m using recursive technique
double findpower(int x, int y) : to return x raised to the power of y using recursive technique
void calculate()                       : to calculate the sum of the series by invoking the recursive functions respectively.
void display()                          : to display the sum of the series.
Specify the class
SeriesSum, giving the details of the above member data and methods only. Define the main() function to create an object and call the member function accordingly to enable the task.

Question 8                                                                                                                             

  1. Write a program in Java to perform Bubble Sort in a given array of integers in ascending order.
  2. Write a program to obtain maximum and minimum element in an array using
    maximum( int[] t) and minimum( int[] t). Also define a main() and call the
    methods to enable the task.

Question 9                                                                                                                              [10]

A class Binary defines a recursive function to convert a binary number into its equivalent decimal form.
Example: Let Binary number 1101, its equivalent decimal 1*23 + 1*22 +0*21 + 1*20= 8+4+0+1=13.
The details of the class are given below:
class name                  :           Binary
Data members/ instance variables :
bin                               :           long integer data to store binary number
de                                :           long integer data to store decimal number
Member functions/methods:
Binary()                       :           default constructor
void readBin()             :           to read a binary number in bin.
long convertDec(long):           to convert the binary number stored in
bin into its equivalent decimal using Recursive technique. Store the decimal number into dec and return.
void Show()                :           to display the binary number and its equivalent decimal number stored in
dec by invoking the recursive function.

Specify the class Binary, giving the details of the above member data and methods only. Define the main() function to create an object and call the member function accordingly to enable the task.

SECTION – C

Answer any two questions.

Each program should be written in such a way that it clearly depicts the logic of the problem. This can be achieved by using mnemonic names and comments in the program.
(Flowcharts and Algorithms are
not required.)
The programs must be written in Java.

Question 10                                                                                                                            [5]

Show the output of the following code;

( In all output questions you must give dry run/ working and after that final output should be written.)

void fnCheck(int n)

{

int s=0,t=1;
do
{

n=n/t++;

System.out.println(“n =”+ n+ “t =” +t);

} while(n>0);

}

  1. What will be the output if n=25?

 

Question 11                                                                                                                            [5]

The following is a public member function of some class which finds whether an integer number ‘n’ is a perfect number or not. There are five places in the code marked as ?1?, ?2?, ?3?, ?4?, ?5? which must be replaced by the expressions or statements so that the program works correctly. Answer the questions given after function.

void Check_Number(int a)

{

int s = ?1? ;

for (int q=1; q <n; q++)

{

if(a% ?2? ==0)

s=s+ ?3?;

}

if( ?4? === ?5?)

System.out.println(n+ “is a perfect number”);

else

System.out.println(n+ “is not a perfect number”);

}

  1. What is the expression or statement at ?1?
  2. What is the expression or statement at ?2?
  3. What is the expression or statement at ?3?
  4. What is the expression or statement at ?4?
  5. What is the expression or statement at ?5?

Question 12                                                                                                                            [5]

The following is a function of some class which sorts an array arr[] in descending order using the bubble sort technique. There are five places in the code marked by ?1?, ?2? , ?3? , ?4? , ?5? which must be replaced by an expression or statement so the function works correctly.

void bubblesort(int arr[])  {

int i, j, k, temp;

for(i=0;i < ?1? ; i++)

{

for( j=0; j< ?2? ; j++)

{

if(?4??3?){

temp=arr[j];

arr[j]=arr[j+1];

arr[j+1]= ?5? ;

}

}

  1. What is the expression or statement at ?1?
  2. What is the expression or statement at ?2?
  3. What is the expression or statement at ?3?
  4. What is the expression or statement at ?4?
  5. What is the expression or statement at ?5?

 

Model Question Paper ISC Computer Science 2018


PART – I (20 Marks)
Answer all questions.
While answering questions in this Part, indicate briefly your working and
reasoning, wherever required.

Question 1

  1. State the involution law. Prove anyone using truth table.                   [1]
  2. Convert the following expression into its canonical POS form:                                     F(X,Y,Z)=(X+Y’).(Y’+Z)                                                                                    [1]
  3. If F(A,B,C)=A’(BC’+B’C), then find F’.                                                          [1]
  4. Verify using truth table ( P ^ Q) V (P ^ ~Q) = P.                                        [1]
  5. Write the dual of (A’+B).(1+B’)=A’+B                                                          [1]

Question 2

  1. Each element of an array DR[-5..2, -2..5] requires one byte of storage. If the array is stored in column major order beginning location 3500, find the address of DR [0,0].
  2. State the difference between instance member and static member. How to access
    non static members to static method?
  1. What is map rolling? What is redundant group?
  2. What is recursion? Write the types of recursion with example.
  3. A 2D array as X[3..6,-2…2] requires 2 bytes of storage space for each element. If the array is stored in Row major order, determine the address of X[5,1] given the base address as 1200.

 

Question 3                                                                                                                                   [5]

  1. The following function is a part of some class. What will the function Check() return when the values of both ‘m’ and ‘n’ are equal to 5? Show the dry run / working.

int Check(int m, int n)

{ if(n==1)
return – m–;
else
return ++m + Check(m, –n);
}

PART II (50 Marks)
Answer six questions in this part, choosing two questions from Section A,
                               two from Section B and two from Section C.
SECTION – A
Answer any two questions

Question 4

  • Given the Boolean function : F(A,B,C,D) =Ʃ(0,2,4,8,9,10,12,13)
    i)  Reduce the above expression by using 4 variable Karnaugh map, showing               [4]
    the various groups (i.e., octal, quads, pairs).
    ii) Draw the logic gate diagram for the reduced expression. Assume that the              [1]
    variables and their complements are available as inputs.
  • Given the Boolean function : F(P, Q,R,S) =Π (0, 2,4,5,6,7,8,10,13,15)
  • Reduce the above expression by using 4 variable Karnaugh map, showing      [4]
    the various groups (i.e., octal, quads, pairs).
  • Draw the logic gate diagram for the reduced expression. Assume that the        [1]
    variables and their complements are available as inputs.

Question 5

  1. A training institute intends to give scholarship to its students as per the criteria given below:
    The student has excellent academic record but is financially weak.
    OR
    The student does not have an excellent academic record and belongs to a backward class.
    OR
    The student does not have an excellent academic record and is physically impaired.
    The inputs are:
    Inputs
    A         Has excellent academic record
    B         Financially sound
    C         Belongs to a backward class
    I          Is physically impaired
    (In all the above cases 1 indicate yes and 0 indicates no).
    Output: X[1 indicate yes, 0 indicates no for all cases]
    Draw the truth table for the inputs and outputs given above and write the SOP expression for X(A,F,C,I).                                                                                                        [5]
  2. Using the truth table, state whether the following proposition is a tautology, contingency or a contradiction. ~(A ^  B) V ( ~A => B)                                                     [3]
  3. Simplify the following expression, using Boolean laws :
    A. (A’ +B).C.(A+B)

Question 6

  1. Differentiate between Half Adder and Full Adder. Draw the logic circuit diagram for a Full Adder.                                                                                                                            [4]
  2. Describe about universal gates with logic diagram and truth table.                          [3]
  3. Write two inferences rules and inferred using algebraic method.                             [3]

SECTION – B

     Answer any two questions.

Each program should be written in such a way that it clearly depicts the logic of the problem. This can be achieved by using mnemonic names and comments in the program.
(Flowcharts and Algorithms are
not required.)
The programs must be written in Java.

Question 7

A class SeriesSum is desgined to calculate the sum of the following series:                                  [10]
S= 1 + x/1! + x3/2! + x5/3! +…….+ x2n-1/n!
Some of the members of the class are given below:
class name                    :           SeriesSum
Data members/ instance variables :
x                                              :           to store an integer number
n                                              :           to store number of terms
sum                                          :           double variable to store the sum of the series

Member functions:
SeriesSum(int xx, int nm)      : constructor to assign x=xx and n=nn
double findfact(int m) : to return the factorial of m using recursive technique
double findpower(int x, int y) : to return x raised to the power of y using recursive technique
void calculate()                          : to calculate the sum of the series by invoking the recursive functions respectively.
void display()                             : to display the sum of the series.
Specify the class SeriesSum, giving the details of the above member data and methods only. Define the main() function to create an object and call the member function accordingly to enable the task.

Question 8

Two matrices are said to be equal if they have the same dimension and their corresponding elements are equal.
For example, the two matrices A and B given below are equal:

Matrix A                                  Matrix B

1   2   3                                    1    2    3
2   4   5                                    2    4    5
3   5   6                                    3    5    6

Design a class EqMat to check if two matrices are equal or not. Assume that the two matrices have the same dimension. Some of the members of the class are given below:
Class name                 :  EqMat
Data members/Instance variables:
a[][]                             : to store integer elements
m                                 : to store the number of rows
n                                  : to store the number of columns
Member fuctions/Methods:
EqMat( int mm, int nn)                      : parameterized constructor to initialize the data members m=mm and n=nn
void readarray()                                 : to enter elements in the array
int check(EqMat P, EqMat Q)          : checks if the parameterized objects P and Q are equal and returns 1 if true, otherwise returns 0.
void print()                                          : displays the array elements.
Define the class EqMat giving details of the constructor(), void readarray(), int check(EqMat,EqMat) and void print(). Define the main() to create objects and call the functions accordingly to enable the task.

Question 9                                                                                                                              [10]

A Jumbled String contains all type of characters in it. A class JUMBLE is designed to reorganize the characters of a Jumbled String. Some of the members of the class are given below:
Class Name                                        : JUMBLE
Data Member/Instance Variables    :
jum                               :           the jumbled string
Member functions:
JUMBLE()                   :           constructor to initialize member string to null
void fnInput()                :           to input the jumbled string
void fnShow()               :           to show the member string and the modified string with proper messages
String fnOrganize()        :           to return a string that contains the Upper Case alphabets then the Lower case alphabets and then the digits and then the special characters of string jum.
Specify the class JUMBLE, giving the details of the above member data and methods only.

EXAMPLE :
input:    abc234ABC
output: ABCabc234                             SECTION – C
                                                     Answer any two questions.
Each program should be written in such a way that it clearly depicts the logic of the problem. This can be achieved by using mnemonic names and comments in the program.
(Flowcharts and Algorithms are
not required.)
                                       The programs must be written in Java.

Question 10                                                                                                                            [5]

The following function is a part of some class. Assume x and y are positive integers with value greater than 0. Answer the given questions along with dry run/working.
void someFun(int x, int y)    {
if(x > 1 && x>y)     {
System.out.print(“\n SomeFun x=”+x +”y=”+y);
if(x%y==0)   {
System.out.print(“\n”+y+”…”);
SomeFun(x/y7, y);  }
else
someFun(x,y+1);
}          I)          What will be returned by someFun(210,2)?
II)        What will be returned by someFun(77,5)?
III)       What will happen for someFun(5,10)?

Question 11                                                                                                                            [5]

Given the code, answer the questions following it

void fnQ(int p, int q)
{ int mx=Math.max(p,q);
int my=Math.min(p,q);
while(my <=mx)  {

p=p+q;
q=p+q;
System.out.println(“P=”+p+”Q=”+q);
my++;   }  }

  1. What will be the output of fnQ(4,5)?
  2. What will be the output of fnQ(10,8)?

Question 12                                                                                                                            [5]

Write a program in Java to sort an array in ascending order using Selection Sort.

Model Question ICSE Computer Applications 2018


Question 1                                                                                                                              [10]

  1. What is dynamic initialization, with an example?
  2. How are the following passed in Java? i) primitive types ii) reference types
  3. Consider the following class:
    public class myClass {
    public static int x=3, y=5;
    public int a=2, b=3; }
    i)          Name the variables for which each object of the class will have its own
    distinct copy.
  4. ii) Name the variables that are common to all objects of the class.
  5. Create a class with one integer instance variable and one class variable. Initialize the variable using i) default constructor (ii) parameterized constructor
  6. Write a java statement to create an object mp4 of class digital.

Question 2                                                                                                                               [10]

  1. Differentiate between String and Stringbuffer type data.
  2. Here is a skeleton definition of a class
    class Sample {
    int i;
    char c;
    float f;
    } Implement the constructor.
  3. What will be the output of the following code fragment?
    If the input given is i) 7 ii) 5
    if(a=5)
    out.println(“Five”);
    else
    System.out.println(“Not Five”);
  4. Differentiate between
    i) equals() and compareTo() with examples and return value.
  5. ii) throw and throws
  6. Write an expression in Java for  x4+ 6x2 + 25 / x

Question 3                                                                                                                               [10]

  1. What are the values of x and y when the following statements are executed?
    int a=63, b=36;
    boolean x=(a>b) ?a:b;
    int y=(a<b)?a:b;
  2. What will be the result stored in x after evaluating the following expression?
    int x =4;
    x+ = (x++ ) + (++x) +x;
  3. State the method that:
    i) Converts a string to a primitive float data type.
  4. ii) Determines if the specified character is an uppercase characters.
  5. Write the Identifier Naming Rules. (All rules)
  6. Rewrite the following program segment using the if –else statements instead of the ternary operator.

String grade= (mark >= 90)?”A”: (mark >=80)? “B”: “C”;

Question 4                                                                                                                               [10]

  1. Give the output of the following code
    double m=6.25, n=7.45;
    out.println(Math.sqrt(m));

System.out.println(Math.min(m,n));

System.out.println(Math.abs(6.25-7.45));
System.out.println(Math.ceil(m));

  1. Name the type of error (syntax, runtime or logical error) in each case given below:
    i) Division of a variable that contains a value of zero.
    ii) Multiplication operator used when the operation should be division
    iii) Missing semicolon
  2. Write a java statement to input/read the following from the user using the keyboard.
  3. Character ii) String (using scanner class)
  4. Write about the differences between Primitive and Reference data types with example.
  5. What is temporary instance with example?

     Section B (60 Marks)
Attempt any four questions from this Section.

      The answers in this Section should consist of the Programs in either BlueJ

environment or any program environment with Java as the base.

Each program should be written using Variable descriptions/Mnemonic Codes
such that the logic of the program is clearly depicted.
Flow-Charts and Algorithms are not required.

Question 5                                                                                                                              [15]
Given below is a  hypothetical table showing rate of income tax for male citizens below the age of 65 years.
Taxable income(Ti) in Rs.                                                    Income Tax in Rs.
Does not exceed Rs. 1,60,000                                                                        Nil
Is greater than Rs.1,60,000 and less
than or equal to Rs. 5,00,000                                             (Ti-1,60,000)* 10%
Is greater than Rs. 5,00,000 and less than or
equal to Rs. 8,00,000                                                      [(Ti – 5,00,000) * 20%] +34,000
Is greater than Rs. 8,00,000                                                    [(Ti – 8,00,000)* 30%] + 94,000

 

Write a program to input that age, gender (male or female) and taxable income of a person. If the age is more than 65 years or the gender is female, display “Wrong category”. If the age is less than or equal to 65 years and the gender is male, compute and display the income tax payable as per the table given above.
Question 6                                                                                                                              [15]

 

Define a class Library having the following description:

Instance variables/Data members:

int acnum        stores the accession number of the book

String title       stores the title of the book

String author   stores name of the author.

Member Methods:

  1. void input() –           to input and store accession number, title and author.
  2. void compute() –           to accept the number of days late, calculate and display the fine charge at the rate Rs. 2 per day.
  • void display() –           to display the details in the following format:

 

Accession number                             Title                            Author

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

 

Question 7                                                                                                                              [15]

Write a program to accept a word and convert it into lower case if its in uppercase and display the new word by replacing only the vowels with the preceeding characters.

Sample Input : computer
Sample Output : cnmpttdr

 

Question 8                                                                                                                              [15]

Write a program that encodes a word into Piglatin. To translate a word into a Piglatin word, convert the word into upper case and then place the first vowel of the original word as the start of the new word along with the remaining alphabets. The alphabets present before the vowel being shifted towards the end following by  “YZ”.

Sample input : Flowers     Sample Output: OWERSFLYZ
Sample input : Olympics         Sample Output : OLYMPICSYZ
Question 9                                                                                                                              [15]

 

Design a class named FruitJuice with the following description:

Instance variables/Data members:

int product_code         –           stores the product code number

String flavor                –           stores the flavor of the juice (eg: orange, apple etc.)

String pack_Type        –           stores the type oif packaging (eg:tetra-pack, PET bottle etc.)

int pack_size               –           stores package size(eg: 200mL, 400 mL, etc.)

int product_price         –           stores the price of the product.

Member Methods:

  1. FruitJuice() –           deault constructor to initialize integer data members to 0 and String data members to “”
  2. void input() –           to input and store the product code, flavor, pack type, pack size and product price.
  • void discount() –           to reduce the product price by 10%.
  1. void display() –           to display the product code, flavor, pack type, pack size and product price.

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

 

Question 10                                                                                                                            [15]

Design a class to overload a function JoyString() as follows:

  1. void JoyString(String s, char c1, char c2) :  with one string argument and two character arguments that replaces the character argument c1 with the character argument c2 in the given string s and prints the new string with first character as uppercase.

Example:  s=”technology”
c1=’a’, c2=’o’
Output: “Technology”

  1. void JoyString(String s1, String s2) : check and print string having more characters compared to the other one.
  • void JoyString(String s) : prints the position of the first space and last space of the given string s.
    Example :  Input value of= “Cloud computing means Internet based computing”
    Output: First index= 5, Last index = 36

Write the main() and call the above member methods.

 

Sort the array elements in ascending order


A class Collection contains an array of  100 integers. using the following class description create an array with common elements from two integer arrays.

Class name  : Collection
Data members
arr[], len
Member functions:
Collection()   : default constructor
Collection(int) : parameterized constructor to assign the length of the array
void input()    : to accept the array elements
Collection common(Collection) : returns a Collection containing the common elements of current Collection object and the Collection object passed as a parameter.
void arrange()  : sort the array element of the object containing common elements in ascending order using any sorting technique
void display()  : displays the array elements
Define the main() to call above member methods.

Program

import java.util.*;
class Collection
{
int arr[];
int len;
Collection()
{
arr=new int[10];
len=10;
}
Collection(int size)
{
arr=new int [size];
len=size;
}
public void input(){
Scanner sc=new Scanner(System.in);
int val=0;
for(int i=0;i<len;i++)
{
System.out.println(“Enter the elements “+(i+1));
val=sc.nextInt();
arr[i]=val;}
}
private void setLength(int le)
{
len=le;
}
public Collection common(Collection c2)
{
Collection c3=new Collection();
int val, k=0;
for(int i=0;i<len;++i)
{
val=arr[i];
for(int j=0;j<c2.arr.length ; ++j) {
if(val==c2.arr[j]) {
k++;
}
}
}c3.setLength(k);
return c3;
}
public void display()
{
for(int i=0;i<len;i++) {
System.out.print(arr[i]+””);
}
System.out.println();
}
public void arrange()
{
for(int i=len-1;i>=0;i–)
{int highestIndex=i;
for(int j=i;j>=0;j–)
{
if(arr[j]>arr[highestIndex])
highestIndex=j;
}
int temp=arr[i];
arr[i]=arr[highestIndex];
arr[highestIndex]=temp;
}
display();
}

public static void main(String args[])
{
Collection c1=new Collection(10);
Collection c7= new Collection();
c1.input();
System.out.println(“Display the entered matrix”);
c1.display();
System.out.println(“Ascending order”);
c1.arrange();
c7=c7.common(c1);
}
}

Output:

Enter the elementts 1
9
Enter the elements 2
8
Enter the elements 3
7
Enter the elements 4
6
Enter the elements 5
5
Enter the elements 6
4
Enter the elements 7
3
Enter the elements 8
2
Enter the elements 9
1
Enter the elements 10
10
Display the entered matrix
9 8 7 6 5 4 3 2 1 10
Ascending order
1 2 3 4 5 6 7 8 9 10

Shuffle the matrix(2D)(1st row becomes the last, 2nd row becomes the 1st & so on..) — by object


A class Shift contains a 2D array of order (m*n) where the maximum values of both m and n is 5. Design the class Shift to shuffle the matrix (the first row becomes the last, the second row becomes the first and so on.)

Class name                    :Shift
Data members
mat[][], m,n;
Member functions:
Shift(int mm, int nn) : constructor to initialize the data members m=mm and n=nn
void input()                 : enters the elements of the array
void cyclic(Shift P)    : enables the matrix of the object(P) to shift each row upwards in a cyclic manner and store the resultant matrix in the current object.
void display()            : display the matrix elements.
Define the main() to create an object and call the methods accordingly to enable the task of shifting the array elements.

Program:

import java.util.Scanner;
 public class Shift {  
     static Scanner sc=new Scanner(System.in); 
     int mat[][];      
     int m,n;   
     Shift(int mm,int nn)  
     { m=mm;     
         n=nn;   
         mat=new int[m][n];   
        }   
        void input()     
        {  System.out.println("Enter elements");  
            for(int i=0;i<m;i++)    
            for(int j=0;j<n;j++)    
            mat[i][j]=sc.nextInt();  
        }    
        void display()    
        {     
            for(int i=0;i<m;i++) 
            {  System.out.println();  
                for(int j=0;j<n;j++)  
                System.out.print(mat[i][j] +"\t");   
            }     }    
            void cyclic(Shift P)  
            {  for(int i=0;i<m;i++)     
                for(int j =0;j<n;j++)  
                {    if(i!=0)          
                    mat[i-1][j]=P.mat[i][j];   
                    else                      
                    mat[m-1][j]=P.mat[0][j];   
                }    
            }
              static void main()   
              { Shift x=new Shift(2,3);  
                  Shift y=new Shift(2,3);   
                  x.input();     
                  y.cyclic(x);  
                  System.out.println("Initial array is ");
                  x.display(); 
                   System.out.println();
                  System.out.print("Array after the shift ");
                  y.display();   
              } } 

Output:

Clockwise Spiral matrix/circular matrix in java


import java.util.*;
class Circular_Matrix
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements : ");
int n = sc.nextInt();

int A[][] = new int[n][n];
int k=1, c1=0, c2=n-1, r1=0, r2=n-1;

while(k<=n*n)
{
for(int i=c1;i<=c2;i++)
{
A[r1][i]=k++;
}

for(int j=r1+1;j<=r2;j++)
{
A[j][c2]=k++;
}

for(int i=c2-1;i>=c1;i--)
{
A[r2][i]=k++;
}

for(int j=r2-1;j>=r1+1;j--)
{
A[j][c1]=k++;
}

c1++;
c2--;
r1++;
r2--;
}

/* Printing the Circular matrix */
System.out.println("The Circular Matrix is:");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(A[i][j]+ "\t");
}
System.out.println();
}
}
}

Output:

Enter the number of elements : 3
The Circular Matrix is:
1 2 3
8 9 4
7 6 5

Random numbers


class TEST
{
public static void main(String a[]){
System.out.println(“Random number between 0 and 1 : ” + Math.random());
System.out.println(“Random number between 0 and 1 : ” + Math.random());

// Now let’s get random number between 1 and 10
for(int i=1;i<=6;i++)
{
System.out.println(“Random value between 0 and 6 : ”
+ getRandomInteger(0,6));
}

public static int getRandomInteger(int maximum, int minimum){
return ((int) (Math.random()*(maximum – minimum))) + minimum;
}

Output:

Random value between 0 and 6 : 1
Random value between 0 and 6 : 5
Random value between 0 and 6 : 6
Random value between 0 and 6 : 2
Random value between 0 and 6 : 6
Random value between 0 and 6 : 6

 

Functions/Methods


Function also called as Methods, to perform a specific task.

To easily understand about functions, here categorizing as two parts

  1. Function Definition                        –     defines the task ,
  2. Function Calling Statement          –     calls the defined method where it requires

all function definitions must be inside the class

public class testFunction  {

public void add(int a, int b) {                              // non static method definition

int c= a+b;

System.out.println(“Sum of two integers:”+c);

}

public static void main(String args[]) {

testFunction tf=new testFunction();                     // object creation

System.out.println(“Addition”);

tf.add(5,7);                                                            // method calling statement with object

}}

Output

Addition
Sum of two integers:12

Have a look to this program which explains why we used tf.add(5,7)

  • tf is the object created for the class testFunction
  • void add (int a, int b) is a non static method
  • public static void main() is a static method
  • with object reference,can access a non static method to a static method ,
  • dot operator(.)  used to access the members of class

Lets look into Static and Non static variables.

Static variables / Class variables:

Variables which are declared with a keyword static , is common to all the instances (objects) of the class because it is a class level variable, i.e. only a single copy of static variable is created and shared among all the instances of the class. Memory allocation for such variables only happens once when the class is loaded in the memory.

Static variable can access with class reference.

Syntax

class_name.variable_name;
class_name.method_name();

Non-static variables/ Instance variables:

Non-static variable also known as instance variable while because memory is allocated whenever instance is created.

Non-static variable can access with object reference.

Syntax

obj_reference.variable_name;
obj_reference.method_name();

Parameters

Actual Parameters –  parameters appear in method calling statement

Formal Parameters –  parameters appear in method definition

In the above program,

method name :  add()

5,7                —-  are actual parameters

int a, int b    —  are formal parameters

 

Recursive method


Find the output of the following fragment:

public class st
{

static int strange(int x,int y)
{
if(x>=y)
{
x=x-y;
return strange(x,y);
}
else
return x;
}

}

 

dry run

1    x=20,y=5               strange(20,5)

2.  x=15,y=5                strange (15,5)

3. x=10,y=5                strange (10,5)

4. x=5,y=5                   strange(5,5)

5. x=0,y=5                   strange(0,5)

returns  0;

 

Factorial using loop and using recursive method


Factorial of a number is the product of all descending numbers from the given number n. 

Example 5!  Means 5*4*3*2*1

The product of the descending numbers from 5 is 120.

Let’s look, can write a program using loop and recursion.

Looping statements 3

1. for loop

2. while loop

3. do while loop

I. Using for  loop

class FactorialLoop1
{  
 public static void main(String args[])
{  
  int i,fact=1;  
  int number=5; // to find the factorial of value that assigned to the variable number
  for(i=1;i<=number;i++)
{    
      fact=fact*i;    
  }    
  System.out.println("Factorial of the given number "+number+" is: "+fact);    
 }  
}  

Output

Factorial of the given number 5 is : 120.

2. Using while loop

class FactorialLoop2
{  
 public static void main(String args[])
{  
  int i=1, fact=1;
  int number=5; // to find the factorial of value that assigned to the variable number
while( i<=number)
{    
      fact=fact*i;    
      i++;
  }    
  System.out.println("Factorial of the given number "+number+" is: "+fact);    
 }  
} 

Output

Factorial of the given number 5 is:  120.

III. Using do while loop

class FactorialLoop3
{  
 public static void main(String args[])
{  
  int i=1, fact=1;
  int number=5; // to find the factorial of value that assigned to the variable number
do
{    
      fact=fact*i;    
      i++;
  }   while( i<=number);
  System.out.println("Factorial of the given number "+number+" is: "+fact);    
 }  
} 

Output

Factorial of the given number 5 is : 120.

Using Recursion

class FactorialUsingRecursion 
 static int factorial(int n)
{
  if (n == 0)    
    return 1;    
  else    
    return(n * factorial(n-1));    
 }    
 public static void main(String args[]){  
  int  fact=1;  
  int number=5; //It is the number to calculate factorial    
  fact = factorial(number);   
  System.out.println("Factorial of the given number"+number+" is: "+fact);    
 }  
}  

Output

Factorial of the given number is: 120

Welldone my dear students


Really, I am so glad to share my students results that declared on today at 3 pm from the council. ICSE and ISC results and my students of 66 from ICSE and 3 students from ISC has secured 100% success in all subjects. Especially for computer science one centum in ICSE and with 30 out of 66 scored above 95. ISC students secured 89 as highest marks and one of my computer science student is the school first. Today again I am proud to be as a teacher for my students. God gave me another golden quill to me as the way of my students result. 

To find the sum of the given digits


Write a program in Java to find the sum of the given digits.

import java.io.*;
class Natural
{
public static void main(String args[]) throws IOException
{
int n,sum=0,rem;
BufferedReader br=new BufferedReader(new InputStreamReader (System.in));
System.out.println(“Enter the value of ‘n’ : “);
n=Integer.parseInt(br.readLine());
while(n>0)
{
rem=n%10;
n=n/10;
sum=sum+rem;
}
System.out.println(“The sum of digits : “+sum);
}
}

 

Output:

Enter the value of ‘n’ :
12345
The sum of digits : 15

To find the sum of the first ‘n’ natural numbers – while loop


Write a program in java to find the sum of  the first ‘n’ natural numbers.

import java.io.*;
class Natural
{
public static void main(String args[]) throws IOException
{
int n,sum=0,i=1;
BufferedReader br=new BufferedReader(new InputStreamReader (System.in));
System.out.println(“Enter the value of ‘n’ : “);
n=Integer.parseInt(br.readLine());
while(i<=n)
{
sum=sum+i;
i++;
}
System.out.println(“The sum of  first”+n+ “natural numbers:”+sum);
}
}

Output:

Enter the value of ‘n’ :
15
The sum of  first 15 natural numbers: 120

To check whether a triangle is isoceles, equilateral, scalene.


import java.io.*;
class triangle
{
public static void main(String args[])throws IOException
{
int a,b,c;
BufferedReader zm=new BufferedReader(new InputStreamReader (System.in));
System.out.println(“Enter three sides of a  triangle”);
a=Integer.parseInt(zm.readLine());
b=Integer.parseInt(zm.readLine());
c=Integer.parseInt(zm.readLine());
if(a==b && b==c && c==a)                          //Equilateral triangle – three sides are equal
System.out.println(“it is an equilateral triangle”);
else if(a==b||b==c||c==a)                       //Isoceles triangle  –  any two sides are equal
System.out.println(“it is an isoceles triangle”);
else
System.out.println(“it is a scalene triangle”);
}
}

To check a is divisible by b


Write a program in java to check whether a is divisible by b.

import java.io.*;
class divisibile
{
public static void main(String args[])throws IOException
{
int a,b;
BufferedReader zm=new BufferedReader(new InputStreamReader (System.in));
System.out.println(“Enter the value of a”);
a=Integer.parseInt(zm.readLine());

System.out.println(“Enter the value of b”);
b=Integer.parseInt(zm.readLine());
if(a%b==0)
System.out.println(+a+” is divisible by”+b);
else
System.out.println(+a+” is  not divisible by”+b);
}
}

 

Output:

Enter a,b
12
5
12 is not divisible by 5

To input a Date and print in another format


Write a Program in Java to input a Date in ddmmyyyy 8-digit format and print it in:
1) dd/mm/yyyy format
2) dd, month name, yyyy format

Input: 12012018
Output:
12/01/2018
12 January, 2018

 

import java.io.*;

class Date_DDMMYY

{

public static void main(String args[])throws IOException

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

int l, y, d, m;

String dd, mm, yy;

//array storing the maximum days of every month

int maxdays[]={0,31,28,31,30,31,30,31,31,30,31,30,31};

//array storing the month names

String month[]={ “”, “January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December” };

System.out.print(“Enter any date in 8 digits (ddmmyyyy) format: “);

String date = br.readLine(); //inputting the date in String format

l = date.length(); //finding number of digits in the given input

if(l==8) //performing the task only when number of digits is 8

{

dd = date.substring(0,2); //extracting the day in String format

mm = date.substring(2,4); //extracting the month in String format

yy = date.substring(4); //extracting the year in String format

d = Integer.parseInt(dd); //day in Integer format

m = Integer.parseInt(mm); //month in Integer format

y = Integer.parseInt(yy); //year in Integer format

if((y%400==0) || ((y%100!=0)&&(y%4==0))) // condition for leap year

{

maxdays[2]=29;

}

/* checking whether the day, month and year are within acceptable range

i.e. there cannot be an input like 35012013 because 35/01/2013 is unacceptable*/

if(m<0 || m>12 || d<0 || d>maxdays[m] || y<0 || y>9999) // Performing Date  Validation

{

System.out.println(“The day, month or year are outside acceptable limit”);

}

else

{

/* First Part */

System.out.println(“Date in dd/mm/yyyy format = “+dd+”/”+mm+”/”+yy);

/* Second Part */

System.out.print(“Date in dd, month name, yyyy format = “+dd+” “+month[m]+”, “+yy);

}

}

else

System.out.println(“Wrong Input”);

}

}

 

Output:

Enter any date in 8 digits (ddmmyyyy) format: 12012018

Date in dd/mm/yyyy format = 12/01/2018

Date in dd, month name, yyyy format = 12 January, 2018

Frequency of each alphabet


Write a program to input a string (word). Convert it into lowercase letters. Count and print the frequency of each alphabet present in the string. The output should be given as:

Sample Input: Alphabets
Sample Output:
==========================
Alphabet             Frequency
==========================
a                              2
b                              1
e                              1
h                              1
l                               1
p                              1
s                              1
t                               1

import java.io.*;

class AlphaFrequency

{

public static void main(String args[])throws IOException

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.print(“Enter any string: “);

String s = br.readLine();

s=s.toLowerCase();                               //converting the string into lowercase

int l=s.length();                                    //finding the length of the string

char ch;

System.out.println(“Output:”);

System.out.println(“==========================”);

System.out.println(“Alphabet\tFrequency”);

System.out.println(“==========================”);

/* Counting frequency of alphabets begins below */

int count=0;

for(char i=’a’; i<=’z’; i++)

{

count = 0;

for(int j=0; j<l; j++)

{

ch=s.charAt(j);                         //extracting characters of the string one by one

if(ch==i)                               //first checking the whole string for ‘a’, then ‘b’ and so on

count++;            //increasing count of those aplhabets which are present in the string

}

if(count!=0)                    //printing only those alphabets whose count is not ‘0’

{

System.out.println(i+”\t\t”+count);

}

}

}

}

Enter any string: hai how are you

Output:

==========================

Alphabet         Frequency

==========================

a                      2

e                      1

h                      2

i                       1

o                      2

r                       1

u                      1

w                     1

y                      1

Write a program to input a word from the user and remove the duplicate characters present in it.


Write a program to input a word from the user and remove the duplicate characters present in it.

Example:

INPUT – abcabcabc
OUTPUT – abc

INPUT – javaforschool
OUTPUT – javforschl

INPUT – Mississippi
OUTPUT – Misp

Programs:

import java.io.*;

class RemoveDupChar

{

public static void main(String args[])throws IOException

{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.print(“Enter any word : “);

String s = br.readLine();

int l = s.length();

char ch;

String ans=””;

for(int i=0; i<l; i++)

{

ch = s.charAt(i);

if(ch!=’ ‘)

ans = ans + ch;

s = s.replace(ch,’ ‘); //Replacing all occurrence of the current character by a space

}

System.out.println(“Word after removing duplicate characters : ” + ans);

}

}

Output:

Example 1:
Enter any word : Mississippi
Word after removing duplicate characters : Misp

Example 2:
Enter any word : Attitude
Word after removing duplicate characters : Atiude

Evaluate


  1.  int a=10, b=8;

(i) a%b++

(ii) ++a-b–

(iii) a++ – b–

(iv) a– + b++

 

Output:

  1.  a% b= 10 % 8 = 2 (% is to find the remainder)

a%b ++ = 2

2.  11-8= 3

3) 10-8= 2

4) 10 + 8=18

 

 

 

2.  String s1=”Computer”;

String s2=s1.substring(1,5);

Output:

ompu

Encrypt a character


A simple encryption system uses a shifting process to hide a message. The value of the shift can be in the range 1 to 26.

For example a shift of 7 means that A = U, B =V,C = W, etc.i e.

Text : A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Code: U V W X Y Z A B C D E F G H I J K L M N O P Q R S T

Fist an extra space is added to the end of the string. To make things little more difficult, spaces within the original text are replaced with QQ before the text is encrypted. Double Q (QQ) was selected because no English word ends in Q or contains QQ.

Additionally the coded message is printed in blocks of six characters separated by spaces. The last block might not contain six characters. Write a program that takes the coded text (less than 100 characters), the shift value and prints the decoded original text.Your program must reject any non-valid value for shift and display an error message “INVALID SHIFT VALUE)”. Assume all characters are upper case. Test your program for the following data and some data that you have coded, using the rules given above:

 

SAMPLE DATA:

  1. INPUT:
    CODED TEXT : “UHINBY LKKQCH HYLKK”
    SHIFT : 7
    OUTPUT:
    DECODED TEXT : ANOTHER VALUE
  2. INPUT:
    CODED TEXT : “RUIJGG EVGGBK SAGG”
    SHIFT : 11
    OUTPUT:
    DECODED TEST : BEST OF LUCK
  3. INPUT:
    CODED TEXT : “DKSMMW NAMMUK QMM”
    SHIFT : 29
    OUTPUT:
    INVALID SHIFT VAULE

 

import java.io.*;

public class Decode

{

public static void main(String args[])throws IOException

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.print(“Enter Coded Text : “); // inputting coded text

String s = br.readLine();

int l = s.length();

s = s.toUpperCase(); // converting the coded text into Uppercase

s = s + ” “; // adding a space at the end

if(l>=100) // checking whether length of inputted code is less than 100

System.out.println(“!!! Invalid Length of Coded Text !!!”);

else

{

System.out.print(“Enter the Shift Value : “);

int shift = Integer.parseInt(br.readLine());

if(shift<1 || shift>26) // checking whether shift value is between 1 and 26

System.out.println(“!!! Invalid Shift Value !!!”);

else

{

int a, b;

char ch1, ch2;

String dec=””; //new String for storing the decoded text

for(int i=0; i<l; i++)

{

ch1 = s.charAt(i); // extracting characters one by one

ch2 = s.charAt(i+1); // extracting the next character

/*  after finding each character in ch1 and ch2

*Below we are adding shift value to the characters

* if ch1 = ‘A’ and shift = 7,

* then ch1 + shift – 1 will give us: ‘A’+7-1 = 65+7-1 = 71

* which is the ASCII value of ‘G’

*/

a = ch1 + shift – 1; // storing ASCII values after adding shift to the current character

b = ch2 + shift – 1; // storing ASCII values after adding shift to the next character

 

/* If the currrent character and the next character are both ‘Q’ then we have a ‘space’

* hence the ASCII value should be 32

*/

if((char)a == ‘Q’ && (char)b == ‘Q’)

{

a = 32;

i++;

}

 

/* If ASCII value after adding the shift becomes more than 90,

* then we subtract 26 from it, to make it circular,

* eg. ‘U’+7-1 = 85+7-1 = 91, but we want ‘A’ whose ASCII value is 65

* so 91-26 will give us 65

*/

if(a>90)

a = a – 26;

if(ch1 != ‘ ‘)

dec = dec + (char)a; // finally adding the decoded character to the new String

}

System.out.println(“Decoded Text : “+dec);

}

}

}

}

 

Output

Enter Coded Text : anu

Enter the Shift Value : 2

Decoded Text : BOV

Enter Coded Text : anu

Enter the Shift Value : 8

Decoded Text : HUB

Binary Search


import java.util.Scanner;

public class BinSearch

{   public static void main(String args[])

{    int c, first, last, middle, n, search, array[];

Scanner in = new Scanner(System.in);

System.out.println("Enter number of elements");

n = in.nextInt();

array = new int[n];

System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++)

array[c] = in.nextInt();

System.out.println("Enter value to find");

search = in.nextInt();

first  = 0;

last   = n - 1;

middle = (first + last)/2;

while( first <= last )

{

if ( array[middle] < search )

first = middle + 1;

else if ( array[middle] == search )

{

System.out.println(search + "found at location " + (middle + 1) + ".");

break;

}

else

last = middle - 1;

middle = (first + last)/2;

}

if ( first > last )

System.out.println(search + " is not present in the list.\n");

}

}