to print possible combinations of numbers (234, 243,324,342,etc)


import java.util.*;
class permutationDigits
{
int count = 0;
void input()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a digit: ");
int a= sc.nextInt();
String s=String.valueOf(a); //converting int into string
System.out.println("The Anagrams are : ");
compute("",s);
System.out.println("Total Number of Anagrams = "+count);
}
void compute(String s1, String s2)
{
if(s2.length()<=1)
{
count++;
System.out.println(s1+s2);
}
else
{
for(int i=0; i<s2.length(); i++)
{
String a = s2.substring(i, i+1);
String b = s2.substring(0, i);
String c = s2.substring(i+1);
compute(s1+a, b+c);
}
}
}
public static void main(String args[])
{
permutationDigits ob=new permutationDigits();
ob.input();
}
}

Output:

Enter a digit: 234
The Anagrams are :
234
243
324
342
423
432
Total Number of Anagrams = 6

Unique Number program by methods


How to write a program with methods?
Unique Number program by methods.

Each program has different parts
1. importing package
2. define class with instance variables
3. constructor to initialize variables
4. input method – to read an input
5. calculate method- processing
6. display method – to display the processed data
7. main method- invoke above mentioned methods by creating an object

import java.util.*;
public class UniqueNumber
{
    // instance variables - 
    int n;
    String s;
    int flag,i, j,l;
    /**
     * Constructor for objects of class UniqueNumber
     */
    public UniqueNumber()
    {
        // initialise instance variables
        n = 0;
        flag=0;
        s=" ";
    }
    public void input() // to input an integer
    {
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a number :");

        n=sc.nextInt();
    }
   public void calculate()
    {
       s= Integer.toString(n); // converting the given number into String datatype
// Int datatype is converting to String,
// String helps to extract the character by charAt() and check each character is matching with the rest.
        l=s.length();
//Loops to check the digits are repeated     
    for(i=0;i<l-1;i++)
    {
       for(j=i+1;j<l;j++)
        {
            if(s.charAt(i)==s.charAt(j)) // if any digits are repeated, then it is not a UniqueNumber
            { flag=1;
                break; 
            }
         }
    }
    }
    public void display()
    {
     calculate(); //invoke calculate() 
    if(flag ==0)
    System.out.println(" It is an UniqueNumber");
    else
    System.out.println(" It is not an UniqueNumber");
     }  
      public static void main(String args[]) throws Exception
      {   
    UniqueNumber un=new UniqueNumber(); //creating object 
    un.input();  //calling input() to main()
    un.display(); //calling display() to main()
       }
    }

Output:

Enter a number: 5673

It is an UniqueNumber

Enter a number: 5675

It is not an UniqueNumber

Scalar matrix program in java


Write a Program in Java to input a 2-D square matrix and check whether it is a Scalar Matrix or not.

Scalar Matrix : A square matrix is said to be scalar matrix if all the main diagonal elements are equal and other elements except main diagonal are zero. Scalar matrix can also be written in form of n * I, where n is any real number and I is the identity matrix.

import java.util.*;
class ScalarMatrix
{
	public static void main(String args[])throws Exception
	{
		Scanner sc=new Scanner(System.in);
		System.out.print("Enter the size of the matrix : ");
		int m=sc.nextInt();
		int A[][]=new int[m][m];
		
		/* Inputting the matrix */
		for(int i=0;i<m;i++)
		{
			for(int j=0;j<m;j++)
			{
				System.out.print("Enter an element :("+i+","+j+") ");
				A[i][j]=sc.nextInt();
			}
		}

		/* Printing the matrix */
		
		System.out.println("The Matrix is : ");
		for(int i=0;i<m;i++)
		{
			for(int j=0;j<m;j++)
			{
				System.out.print(A[i][j]+"\t");
			}
			System.out.println();
		}
		
		
		int p = 0, q = 0, x = A[0][0]; // 'x' is storing the 1st main diagonal element
		
		for(int i=0;i<m;i++)
		{
			for(int j=0;j<m;j++)
			{
			    /* Checking that the matrix is diagonal or not */
				if(i!=j && A[i][j]!=0) // All non-diagonal elements must be zero
				{
					p=1;
					break;
				}
				/* Checking the matrix for scalarity */
				// All main diagonal elements must be equal to 'x' and non-zero
				if(i==j && (A[i][j]==0 || A[i][j]!=x)) 
				{
					q=1;
					break;
				}
		    }
		}
		
		if(p==0 && q==0)
			System.out.println("The matrix is scalar");
		else
			System.out.println("The matrix is not scalar");
	}
}

Output:

Enter the size of the matrix : 3
Enter an element :(0,0) 1
Enter an element :(0,1) 2
Enter an element :(0,2) 1
Enter an element :(1,0) 3
Enter an element :(1,1) 1
Enter an element :(1,2) 3
Enter an element :(2,0) 1
Enter an element :(2,1) 1
Enter an element :(2,2) 3
The Matrix is :
1 2 1
3 1 3
1 1 3
The matrix is not scalar
Enter the size of the matrix : 3
Enter an element :(0,0) 1
Enter an element :(0,1) 0
Enter an element :(0,2) 0
Enter an element :(1,0) 0
Enter an element :(1,1) 1
Enter an element :(1,2) 0
Enter an element :(2,0) 0
Enter an element :(2,1) 0
Enter an element :(2,2) 1
The Matrix is :
1 0 0
0 1 0
0 0 1
The matrix is scalar

Disarium number program in java


A Disarium number is a number defined by the following process:

Sum of its digits powered with their respective position is equal to the original number. Some other DISARIUM are 89, 135,175, 518 etc

Input   : n = 135Output  : Yes 1^1 + 3^2 + 5^3 = 135Therefore, 135 is a Disarium number
import java.io.*;
class DisariumNumber
    {
    public static void main(String[] args)throws IOException
        {
            BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
            System.out.print("Enter a number : ");
            int n = Integer.parseInt(br.readLine());
            int copy = n, rem = 0, sum = 0;
            String s = Integer.toString(n); //converting the number into a String
            int len = s.length(); //finding the length of the number 
             
            while(copy>0)
            {
                rem = copy % 10; //extracting the last digit
                sum = sum + (int)Math.pow(rem,len);
                len--;
                copy = copy / 10;
            }
              if(sum == n)
                System.out.println(n+" is a Disarium Number.");
            else
                System.out.println(n+" is not a Disarium Number.");
        }
    }

Output:

Enter a number : 135
135 is a Disarium Number.
Enter a number : 121
121 is not a Disarium Number.

Java program – Factorial using recursion


import java.util.*;    
class factRec
{  
        int factorial(int n) //5 ! =5*4*3*2*1 =120 
     {    
      if (n == 0)       // 0!=1 so when given number is 0, it returns 1
        return 1;    
      else          // finding factorial by n * factorial(n-1)
        return(n * factorial(n-1));    
     }    
     public static void main(String args[])
     {  
         Scanner sc=new Scanner(System.in);
         factRec fr=new factRec();   //creating object fr
         System.out.println("Enter the number to find the factorial");
         int number=sc.nextInt();//It is the number to calculate factorial
         int fact=1;  
         fact = fr.factorial(number);   //method invocation factorial(number)
                                        // calling recursive method
         System.out.println("Factorial of "+number+" is: "+fact);    
     }  
    }  

Output:

Enter the number to find the factorial
5
Factorial of 5 is: 120
Enter the number to find the factorial
8
Factorial of 8 is: 40320

Fibonacci series using recursion in java


Fibonacci series is series of natural number where next number is equivalent to the sum of previous two number e.g. fn = fn-1 + fn-2. The first two numbers of Fibonacci series is always 0, 1.


In fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc.


import java.util.*;
class fibo
{  
int fib(int n) 
{ 
    int a=0,b=1;
if (n <= 1) 
   return a;
   else if(n==2)
   return b; 
   else
return fib(n-1) + fib(n-2); 
} 
void genSeries()
{   Scanner sc=new Scanner(System.in);
    int n ,c; 
    System.out.println("Enter the limit:");
    n=sc.nextInt();
    System.out.println("The Fibonacci series is:");
    for(int i=1;i<=n;i++)
    {
        c=fib(i);
        System.out.print(c +" ");
    }
}

public static void main (String args[]) 
{ 
    fibo f=new fibo();

  f.genSeries();
} 
}

Output:

Enter the limit:
6
The Fibonacci series is:
0 1 1 2 3 5

Harshad /Niven number program in java


Write a Program in Java to input a number and check whether it is a Harshad Numberor Niven Number or not..

Harshad Number : A Harshad number (or Niven number), is an integer (in base 10) that is divisible by the sum of its digits.

import java.util.*;
class HarshadNumber
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
         
        System.out.print("Enter a number : ");
        int n = sc.nextInt();
        int c = n, d, sum = 0;
         
        //finding sum of digits
        while(c>0)
        {
            d = c%10;
            sum = sum + d;
            c = c/10;
        }
         
        if(n%sum == 0)
            System.out.println(n+" is a Harshad Number.");
        else
            System.out.println(n+" is not a Harshad Number.");      
    }
}

Output:

Enter a number : 99
99 is not a Harshad Number.
Enter a number : 110
110 is a Harshad Number.
Enter a number : 21
21 is a Harshad Number.

String program using StringTokenizer


ISC – Model Question Paper -October 2018

Design a class Chord that accepts a string and prints the number of vowels present in each word of the string. Also note that a string is considered valid if it does not contain any repeated spaces. For example : String : “SUMMER IN AUSTRALIA IS IN DECEMBER.
Output: SUMMER : 2
IN : 1
AUSTRALIA : 5
IS : 1
IN : 1
DECEMBER : 3
Some of the members of the class Chord are given below:
Class Name : Chord
Data members
cd : the string
Member functions:
Chord() : to initialize the member string to null
void fnInput() : to input the member string
void fnOperate() : to print “invalid Sting “ if the string is not valid, otherwise print the words of the member string along with the number of vowels present in them.

boolean isValid() : to verify whether the given string is valid or not and return true or false.
int fnVowel(String w) : to count and return the no. of vowels present in argument ‘w’.

import java.util.*;
class cord
{
String cd;
cord()
{
cd=””;
}
void fnInput()
{
Scanner sc=new Scanner(System.in);
System.out.println(“enter the string:”);
cd=sc.nextLine();
}

//Check the String is valid
boolean isValid()
{
for(int j=0;j<=cd.length()-2;j++)
{
if(cd.charAt(j)==’ ‘ && cd.charAt(j+1)==’ ‘) // checking repeated space
{
return false; //if repeated space, String is invalid
}
}
return true;

}
void fnOperate()
{
fnInput();
if(isValid() == false)
{
System.out.println(“Invalid string”);
return;
}
StringTokenizer st=new StringTokenizer(cd);
int ct=st.countTokens();
for(int j=1;j<=ct;j++)
{
String wrd=st.nextToken();
int cw=fnVowel(wrd);
System.out.println(wrd +” ” +cw);

}
}

//counting the vowels in the argument ‘w’
int fnVowel(String w)
{
int c=0;
w=w.toUpperCase();
for(int j=0; j<=w.length()-1;j++)
{
if(w.charAt(j)==’A’||w.charAt(j)==’E’||w.charAt(j)==’I’||w.charAt(j)==’O’||w.charAt(j)==’U’)
c++;
}
return c;
}
public static void main(String args[])
{
cord c1=new cord();
c1.fnOperate();
}

}

ISC – Model Question Paper -October 2018


Question 1

  1. Draw the truth table and logic diagram for the 2 inputs XOR gate. [1]
  2. Using the truth table, verify the following expression. X+(Y+Z) = (X+Y)+Z [1]
  3. If F(A,B,C)=A.B’+A’+A’.B+B’, then find F’.                                                 [1]
  4. Verify using truth table ( A ^ ~B ) V (~A ^ B) V A = AVB                                     [1]
  5. Simply the given expression using Boolean laws: F1=(a+c’).(a’+b’+c’) [1]

Question 2

  1. An array DR[-2…2,-3…3] stores elements in Col major wise, with address DR[0][0] as 2500. If each element requires 2 bytes of storage, find the base address.     [2]
  2. Write a java statement for the following:
    i) write data to a file “emp.dat” in binary form.
    ii) Read data from a file “story.txt” in text form.                             [2]
  3. Convert the following infix to postfix form:
    ((M/N-P) * (Q+R)) /(C+D)     [2]
  4. State one case when the error “Queue Overflow” occur.                                                  [2]
  5. Convert from infix to prefix form P*Q/R*(S+T/(U-V))                                            [2]

 

Question 3                                                                                                                                   [5]

The following function witty() is a part of some class. What will be the output of the function witty() when the value of n is “SCIENCE” the value of p is 5. Show the dry run/working.
void witty(String n, int p) {
if (p<0)
System.out.println(“”);
else{
System.out.println(n.charAt(p) +”.”};
witty(n, p-1);
System.out.println(n.charAt(p));
}
}

                                             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,5,7,8,10,11,13,14,15)
    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 using NAND gates only.    [1]
    Assume that the variables and their complements are available as inputs.
  • Given the Boolean function : F(P, Q,R,S) =Π (2,3,6,7,9,11,12,13,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 using NOR gates only. [1]
    Assume that the  variables and their complements are available as inputs.

Question 5

  1. The person is not an Indian citizen but has taken active part in activities for the upliftment of the nation. The inputs are:
    Inputs
          A         The person is/was an Indian citizen
    B          Has a continuous service of more than 20 years.

C         lost his/her life in a war.
D   Taken part in activities for upliftment of the nation.

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

  1. Write the cardinal form of P(A,B,C) = ABC’ +A’BC +A’BC’+ABC                     [2]

                      

Question 6

  1. Using a truth table, verify the following proposition is valid or invalid [3]
    (a
    àb) ^(bàc) =(aàc)
  2. Draw the truth table representing a 2 input XNOR gate and derive its SOP expression and draw its logic gate diagram. [2]
  3. What is a multiplexer? Draw the truth table and logic diagram of 8*1 multiplexer. [5]                                                                                                

                                                                                   

            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 Admission contains the admission numbers of 100 students. Some of the data members/ functions are given below:
Class name       :           Admission
Data members:
Adno[]             : integer array to store admission numbers
Member functions:
Admission()      : constructor to initialize the array elements
void fillArray(): to accept the elements of the array in ascending order
int binSearch(int l, int u, int v): to search for a particular admission number(v) using binary search and recursive technique and returns 1 if found otherwise returns -1.

Specify the class Admission, giving details of the constructor , void fillArray(), and
int binSeacrh(int, int, int). Define the main() to create an object and call the function accordingly to enable the task.

Question 8                                                                                                                             

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
matrixfnTrans(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

Question 9                                                                                                                              [10]

Design a class Chord that accepts a string and prints the number of vowels present in each word of the string. Also note that a string is considered valid if it does not contain any repeated spaces. For example : String   : “SUMMER IN AUSTRALIA IS IN DECEMBER.
Output:   SUMMER    :  2
IN   :           1
AUSTRALIA   :  5
IS         : 1
IN        : 1
DECEMBER   :   3
Some of the members of the class Chord are given below:
Class Name      : Chord
Data members
cd                    : the string
Member functions:
Chord()            : to initialize the member string to null
void fnIn()        : to input the member string
void fnOp()      : to print “invalid Sting “ if the string  is not valid, otherwise print the words of the member string along with the number of vowels present in them.

                                                            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]

A super class Circle has a sub class Circumference. The details of both the classes are given below.

The details of the base class:
Class name                   : Circle

Data member/ instance variable :

int rad               : an integer to store the  radius

Member functions/methods

Circle (….)                   : parameterized constructor to initialize the data members.

void show()                  : to display the  member data.

 

The details of the derived class:

Class name                   : Circumference

Data member                :

double cir                     : to store the Circumference

Member functions

Circumference (…)                   : parameterized constructor to initialize the data members of the base and current class

void calCirum               : calculates the circumference by using the formula (2*pi*r) (pi=3.14)
void show()                  : to display the details of both the classes with proper messages(apply method overriding).
Specify the class Circumference giving the details of its mentioned methods. Assume that class Circle is already present. Write the main ().

Specify the base class, derived class and write the main() and call above member methods.

 

Question 11                                                                                                                            [5]

A class  Flow allows that a user to add and delete names in a list from the same end(top). The following details of the class Flow are given below:
Class name                   :Flow

Data members :
names[]                        : a string array to hold a maximum of 10 names
top                               : stores the position of the topmost element.
Member methods:
Flow(….)                     : initialize the data member top=-1 and to create the string array
void pushName(String n): to push a name into the stack at position top, if possible, else display the message “Overflow”.
String popName()         : to remove and return element from the top. If the list is empty then return “Underflow”.

Armstrong number using recursive method (Q7- Model QP)


Model Question Paper -ISC Computer Science – Oct 2018

Question 7

An Armstrong number is such that the sum of the cube of the digits of the number is the number itself. Example 153= 13+53+33
Design  a class Arm to perform the given task. Some of the members of the class are given below:

Class name                              : Arm
Data member/Instance variables         :
no                                            : integer to store the number
sum                                          : integer to store the sum of the cube of the digits
Member methods:
Arm(….)                                 : to initialize member data
no, and assign 0 to sum.
long fnPower(int a, int b)        : to calculate a^b using recursive function
void fnPerform()                     : to verify and print whether the member data is an Armstrong number or not.
Specify the class Arm, giving the details of the above member data and methods. Also define the main() to create an object and call the relevant methods accordingly to enable the task

Program

import java.util.*;
class Arm
{
int no, sum;
Arm(int n1)
{
no=n1;
sum=0;
}

long fnPower(int a, int b)
{
if(b==0)
return 1;
else
return a*fnPower(a,b-1);
} // recursive ()

void fnPerform()
{
int an=no,r;
long sum1=(long) sum;
while(an>0)
{
r=an%10;
an=an/10;
sum1=sum1+fnPower(r,3);                                // recursive fnPower() invoked here
}
if(no==sum1)
System.out.println(“Armstrong number”);
else
System.out.println(“Not an Armstrong number”);
}

public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print(“Enter the number:”);
int num=sc.nextInt();
Arm a1=new Arm(num);
a1.fnPerform();
}
}

Output:
Enter the number: 153
Armstrong number

Enter the number: 135
Not an Armstrong number

Model Question Paper -ISC Computer Science – Oct 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. Verify using the truth table, if (x => y).(y =>x) is a tautology, contradiction and contingency.                                                               [1]
  2. State the two Idempotence law. Verify any one using truth table.      [1]
  3. If F(A,B,C)=A’(BC’+B’C), then find F’.                                                        [1]
  4. Verify using truth table ( A ^ ~B ) V (~A ^ B) V A = AVB [1]
  5. Write the dual of (a.b’+0).(a’.b+1)                                                   [1]

Question 2

  1. An array DR[-2…2,-3…3] stores elements in Col major wise, with address DR[0][0] as 2500. If each element requires 2 bytes of storage, find the base address.                                                                [2]
  2. Explain the given keyword in brief: 1) import 2) extends              [2]
  3. State the difference between Function overloading and Function overriding [2]
  4. What is the difference between private and protected access specifier with an example.    [2]
  5. A char array B[7][6] has a base address 1046 at(0,0). If the address at B[2][q] is 1096. Find the value of q, given that the array is stored column major wise. Each char requires 2 bytes of storage. [2]

 Question 3   [5]

Give the output of the following function where x and y are arguments greater than 0. Show the dry run/working.

void confusing(int x, int y) 
{
if(x>1)  { 
               if( x%y==0) { 
                               System.out.print(y+””);
                              confusing(x/y, y);
                            }
else   {
confusing(x, y+1); }
}

1) What will be the function confusing(24,2 ) return?
2) What will be the function confusing(84,2) return?
3) In one line, state what is the function is doing, apart from recursion?

                                             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 [10]

  • Given the Boolean function : F(A,B,C,D) =Ʃ(0,1,2,5,8,9,10)
    i)  Reduce the above expression by using 4 variable Karnaugh map, showing     the various groups (i.e., octal, quads, pairs).
    ii) 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) =Π (3,4,6,7,11,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.

Question 5 [10]

  1. 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.
    OR
    The person does not have a valid reservation ticket, but holds a valid pass issued by the Railway department with a valid ID proof.
    OR
    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.
    Output: T denotes allowed to travel [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 T(R,P,D,S).
  2. Verify using truth table, whether the given expression is a contradiction or not.             P(A,B) = A. (A’ +B)      +AB’
  3. Write the cardinal form of P(A,B,C) =ABC’+ A’BC+ A’BC’ +ABC                                 

Question 6 [10]

  1. What is an encoder? Draw the logic circuit of an Octal to Binary encoder.
  2. What is a decoder? Draw the logic gate diagram, block diagram for a 3 to 8 decoder.

            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 [10]

An Armstrong number is such that the sum of the cube of the digits of the number is the number itself. Example 153= 13+53+33
Design  a class Arm to perform the given task. Some of the members of the class are given below:

Class name                              : Arm
Data member/Instance variables         :
no                                            : integer to store the number
sum                                          : integer to store the sum of the cube of the digits
Member methods:
Arm(….)                                 : to initialize member data no, and assign 0 to sum.
long fnPower(int a, int b)        : to calculate a^b using recursive function
void fnPerform()                     : to verify and print whether the member data is an Armstrong number or not.
Specify the class Arm, giving the details of the above member data and methods. Also define the main() to create an object and call the relevant methods accordingly to enable the task.

Question 8                   [10]

Design a class EQUA that contains a 2D integer array of order [m *n]. The maximum value possible for m,n is 10. The details of some of the members of the class are given below:

Class name                              :           EQUA
Data member/Instance variables  :
Tam [] []                                              : to store the matrix
int m,n                                                 : integers to store the number of rows and columns
Member functions  :
EQUA(….)                                         : parameterized constructor to initialize m, n and to allocate memory to member array
void fnGet()                                        : to fill the member array with random integers
void fnDisplay()                                  : to show the member matrix
Boolean fnlsEqual(EQUA M)                        : to compare the matrix of the
argument object and the current matrix for equality. If equal, then return true else return false. [ two matrices are equal if all elements are same in corresponding cells]

Specify the class EQUA, giving the details of the above member data and methods. Also define the main() to create an object and call the other methods accordingly to enable the task.

Question 9                     [10]

Design a class Alpha which enables a word to be arranged in ascending order according to its 10 alphabets. The details of the members of the class are given below:
Class name                                          : Alpha
Data members
Str                                                       : to store a word
Member methods:
Alpha()                                    : default constructor
void readword()                      : to accept the inputted word
void arrange()                          : to arrange the word in alphabetical order using any standard sorting technique.
void disp()                               : displays the word.

Specify the class Alpha giving details of the constructor and the member functions void readword(), void arrange(), void disp() and defining the main() to create an object and call the function in order to execute the class by displaying the original word and the changed word with proper message.

    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]

A super class Tour has a sub class Tourist. The details of both the classes are given below.

The details of the base class:
Class name                  : Tour

Data member/ instance variable :
int budget                    : to store the tour budget
int dist             : to store the proposed distance to travel in kilometer
Member functions/methods
Tour(….)                     : parameterized constructor to initialize the data members.
Void print()                 : to print the member data with proper messages.

The details of the derived class:
Class name                  : Tourist
Data member               :
String Name                 : to store the name of the tourist
double rate                  : to store the rate proposed per kilometer
Member functions
Tourist(…)                  : parameterized constructor to initialize the data members of the base and current class
void modify()              : modifies the rate after giving certain discounts, depending on proposed distance to travel as per the following chart
Distance                                  Discount
>=10000                                  40% of rate
<10000 && >=5000               20% of rate
<5000  && >=1000                10 % of rate
void print()                  : to display the details of both the classes with proper messages. Also note to print the rate proposed and the rate applied.

Specify the base class, derived class and write the main() and call above member methods.

Question 11                                                                                 [5]

Given the following code, answer the questions given below(Show the dry run/working)

void design(int d) {
int k=d, r=0, pw=0;
double b=0.0;
do {
r=k%10;
b=b*0.1 +r;
k/=10;
System.out.println(k+””+b+”*10^”+pw);
pw++;
}while(k!=0);

}

  1. What will be the output if d=2345?
  2. What will be the output if d=46?

Question 12                                                                                                              [5]

A class Admission contains the admission numbers of 100 students. Some of the data members/ functions are given below:
Class name      :           Admission
Data members:
Adno[]                        :
integer array to store admission numbers
Member functions:
Admission()    :
constructor to initialize the array elements
void fillArray():
to accept the elements of the array in ascending order
int binSearch(int l, int u, int v): to search for a particular admission number(v) using binary search and recursive technique and returns 1 if found otherwise returns -1.

Specify the class Admission, giving details of the constructor , void fillArray(), and int binSeacrh(int, int, int). Define the main() to create an object and call the function accordingly to enable the task.

Two matrices are equal( by object) – ISC 2018


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 tow matrices are equal or not. Assume that the two matrices have the same dimension.
Class name            :  EqMat
Data members:
a[][]                                        : to store integer elements
m, n                                        : to store the number of rows and columns
Member functions:
EqMat(int mm, int nn)             :  initialize the data members m=mm and n=nn
void readarray()                        :  to enter the 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 and define main() to create objects and call the functions accordingly to enable the task.

Program:

import java.util.*;
class EqMat{
int a[][], m,n;
EqMat( int mm, int nn)
{
m=mm;
n=nn;
a=new int[m][n];
}
public void readarray()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the elements for the array:”);
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=sc.nextInt();
}
}
}
public int check(EqMat P, EqMat Q)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(P.a[i][j]!=Q.a[i][j])
return 0;
}
}
return 1;
}

public void print()
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]+”\t”);
}
System.out.println();
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the row and column size for the array:”);
int a=sc.nextInt();
int b=sc.nextInt();
EqMat A =new EqMat(a,b);
EqMat B=new EqMat(a,b);
A.readarray();
B.readarray();
A.print();
System.out.println();
B.print();
if(A.check(A,B)==1)
System.out.println(“Both are equal matrix”);
else
System.out.println(“Both are unequal matrix”);
}
}

Output:

Enter the row and column size for the array:
3
3
Enter the elements for the array:
2
3
4
5
6
7
8
9
1
Enter the elements for the array:
2
3
4
5
6
7
8
9
2
First matrix
2 3 4
5 6 7
8 9 1

Second matrix
2 3 4
5 6 7
8 9 2
Both are unequal matrix

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

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:

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