Time in words


write a program to convert time in numbers to time in words.

import java.io.*;
public class timeinwords
{
    
     public static void main(String args[]) throws IOException
    {
     InputStreamReader read = new InputStreamReader(System.in);
    BufferedReader x=new BufferedReader (read);
     System.out.println("enter hours");
     int h=Integer.parseInt(x.readLine());
      System.out.println("enter minutes");
     int m=Integer.parseInt(x.readLine());
     if((h>=1&&h<=12)&&(m>=0&&m<=59))
     {
         String word[]={"","one ","two ","three ","four ","five ","six ","seven ","eight ","nine ","ten "," eleven "," twelwe "," thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty","twenty one","twenty two","twenty three","twenty four","twenty five","twenty six","twenty seven","twenty eight","twenty nine"};
         String plu,a;
         if(m==1||m==59)
         plu="minute";
         else
         plu="minutes";
         if(h==12)
         a=word[1];
         else
         a=word[h+1];
          System.out.print("output: "\n+h+":"+m+"-----");
          if(m==0)
            System.out.println(word[h]+"o'clock");
            else  if(m==15)
            System.out.println("quarter past"+word[h]);
     else  if(m==30)
            System.out.println("half past"+word[h]);
            else  if(m==45)
            System.out.println("quarter to"+a);
            else  if(m<30)
            System.out.println(word[m]+" "+plu+" past+words[h] ");
            else
            System.out.println(word[60-m]+" "+plu+" to "+a);
        }
        else 
        System.out.println("invalid input!");
    }
}

output:

enter hours
10
enter minutes
55
output:
10:55—–five minutes to eleven

Reverse the string



import java.io.*;
import java.util.*;
class revstr
{
    public void main()throws IOException
    {
        Scanner sc=new Scanner(System.in);
        String str="",word;
        int l,l1,i;
        String a[]=new String[20];
        System.out.println("enter string");
        str=sc.nextLine();
        StringTokenizer data=new StringTokenizer(str);
        l=data.countTokens();
        for(i=0;i<l;i++)
        {
           word=data.nextToken();
           a[i]=word;
        }
        for(i=l-1;i>=0;i--)
        {
           System.out.print(a[i]+" ");
        }
    }
}

OUTPUT:

enter string
one important thing to know, seattle delivered his speech in his native language.
language. native his in speech his delivered seattle know, to thing important one

Exercise 1 :. Write a java program to check Prime Triplets


The consecutive Prime numbers are known as Prime Triplets if they satisfy the follows;
(n,n+2,n+6) are all Prime or (n,n+4,n+6) are all Prime . Where n is an integer number >0

if n=5,then 5,7,11 are all Prime so they arre Prime Triplets.

If n=7, then (7,7+2, 7+6) 7,9,13 all are not primes so they are not the Prime Triplets.

But if n=7, then (7,7+4,7+6) 7,11,13 all are Prime and they are Prime Triplets.

Write a program to input a start limit S>0 and a last limit L>0. Print all the Prime Triplets between S and L with sutiable message . The Prime Triplets may be greater or be greater or lesser than L depending upon the conditions used for generating Prime combinations. Print the total number of primer Triplets at the end.

Input
s=3, l=15

Output
Prime Triplets
5 7 11
7 11 13
11 13 17
13 17 19
Total Prime Triplet combinations are =4

Write a program.

Twin prime number program in java


A Twin prime are those numbers which are prime and having a difference of two ( 2 ) between the two prime numbers.

In other words, a twin prime is a prime that has a prime gap of two. Sometimes the term twin prime is used for a pair of twin primes; an alternative name for this is prime twin or prime pair.

3, 5), (5, 7), (11, 13), (17, 19), (29, 31), 
import java.io.*;
class TwinPrime
{        
     boolean isPrime(int n) //funton for checking prime
        {
            int count=0;
            for(int i=1; i<=n; i++)
                {
                    if(n%i == 0)
                        count++;
                }
            if(count == 2)
                return true;
             else
                return false;
        }
  
    public static void main(String args[]) throws IOException
        {
            TwinPrime tw= new TwinPrime();
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 
            System.out.print("Enter the lower range : ");
            int p = Integer.parseInt(br.readLine());
            System.out.print("Enter the upper range : ");
            int q = Integer.parseInt(br.readLine());
             
            if(p>q)
                System.out.println("Invalid Range !");
            else
            {
                System.out.println("nThe Twin Prime Numbers within the given range are : ");
                for(int i=p; i<=(q-2); i++)
                {
                    if(tw.isPrime(i) == true && tw.isPrime(i+2) == true)
                    {
                        System.out.print("("+i+","+(i+2)+") ");
                    }
                }
            }                 
        }
    }

Output:

Enter the lower range : 12
Enter the upper range : 24
The Twin Prime Numbers within the given range are :
(17,19)

Mobius Function in java


The MOBIUS function M(N) for a natural number N is defined as follows:

  1. M(N) = 1                          if N = 1

2. M(N) = 0                          if  any prime factor of N is contained in N more than once

3. M(N) = (-1)p                    if N is a product of ‘p’ distinct prime factors

Example :

M(78) = -1                ( for 78 = 2 * 3 * 13     M(78) = ( -1)3 = -1 )

M(34) = 1                 ( for 34 = 2 * 17           M(34) = ( -1)2 = 1 )

M(12) = 0                 ( for 12 = 2 * 2 * 3       M(12) = 0 for 2 appears two times)

M(17) = -1                ( for 17 = 17                 M(17) = ( -1)1 = -1 )

import java.util.*;
class MobiusFun
{
    int n;
     
    MobiusFun()
    {
        n = 0;
    }
     
    void input()
    {
        Scanner sc = new Scanner(System.in);    
        System.out.print("Enter a number : ");
        n = sc.nextInt();
    }
     
    /*  The function primefac() either returns '0' if prime factors are repeated
     *  or returns the no.of prime factors */
    int primeFac()
    {
        int a=n, i=2, m=0, c=0, f=0;
             
        while(a > 1) // loop to generate prime factors
        {
            c = 0; // variable to store frequency of every prime factor
            while(a%i == 0) // if 'i' is a prime factor
            {
                c++; // counting frequency of 'i'
                f++; // counting no of prime factors
                a=a/i;
            }
                i++;
 
            if(c > 1) // returning '0' if prime factors are repeated
                return 0;
        }
        return f; // returning no. of prime factors
    }
     
    void display() // function to display value of mobius function
    {
        int mob,x;
        if(n == 1) // condition 1
            mob = 1;
        else
        {
            x = primeFac();
            if(x == 0) // condition 2
                mob = 0;
            else // condition 3
                mob = (int)Math.pow(-1,x);
        }
        System.out.println("Value of Mobius Function : "+mob);
    }
     public static void main(String args[])
    {
        MobiusFun ob = new MobiusFun();     
        ob.input();
        ob.display();     
    }
}

Output:

Enter a number : 56
Value of Mobius Function : 0
Enter a number : 78
Value of Mobius Function : -1
Enter a number : 34
Value of Mobius Function : 1

MagicComposite


A Composite Magic number is a positive integer which is composite as well as a magic number.

Composite number:
A composite number is a number that has more than two factors.
For example: 10
Factors are: 1, 2, 5, 10

Magic number:
A magic number is a number in which the eventual sum of the digits is equal to 1
For example: 28=2+8=10=1+0=1

Accept two positive integers m and n, where m is less than n as user input. Display the number of Composite magic integers that are in the range between m and n (both inclusive) and output them along with the frequency, in the format specified below.

Example 1:

INPUT:

m = 100
n = 200

OUTPUT:      

The Composite Magic Integers are:
100, 118, 136, 145, 154, 172, 190
The frequency of Composite Magic Integers is : 7

import java.io.*;
class MagicComposite
{  
    boolean isComposite(int n) // Function to check for Composite number
    {
        int count=0;
        for(int i=1;i<=n;i++)
        {
            if(n%i==0)
                count++;
        }
        if(count>2)
            return true;
        else
            return false;
    }
 
    int sumDig(int n) // Function to return sum of digits of a number
    {
        int s = 0;
        while(n>0)
        {
            s = s + n%10;
            n = n/10;
        }
        return s;
    }
     
    boolean isMagic(int n) // Function to check for Magic number
    {
        int a = sumDig(n);
        while(a>9)
        {
            a = sumDig(a);
        }
                     
        if(a == 1)
            return true;
        else
            return false;
    }
 
    public static void main(String args[])throws IOException
    {
        MagicComposite mc = new MagicComposite();
        BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
         
        System.out.print("Enter the lower limit(m) : ");
        int m=Integer.parseInt(br.readLine());
        System.out.print("Enter the upper limit(n) : ");
        int n=Integer.parseInt(br.readLine());
         
        int c=0;
        if (m<n)
        {
            System.out.println("The Composite Magic Integers are: ");
            for(int i=m; i<=n; i++)
            {
                if(mc.isComposite(i)==true && mc.isMagic(i)==true)
                {
                    if (c==0) // Printing the first number without any comma
                        System.out.print(i);
                    else
                        System.out.print(", "+i);
                    c++;
                }
            }
            System.out.println("\nThe frequency of Composite Magic Integers is : "+c);
        }
         else
            System.out.println("INVALID RANGE");
    }
}

Output:

Enter the lower limit(m) : 123
Enter the upper limit(n) : 567
The Composite Magic Integers are:
136, 145, 154, 172, 190, 208, 217, 226, 235, 244, 253, 262, 280, 289, 298, 316, 325, 334, 343, 352, 361, 370, 388, 406, 415, 424, 442, 451, 460, 469, 478, 496, 505, 514, 532, 550, 559
The frequency of Composite Magic Integers is : 37

Magic number


A number is said to be a Magic number if the sum of its digits are calculated till a single digit is obtained by recursively adding the sum of its digits. If the single digit comes to be 1 then the number is a magic number.


import java.util.*;
class MagicNum
{ 
   public static boolean isMagic(int n) 
   { 
       int sum = 0; 
       
       // Note that the loop continues  
       // if n is 0 and sum is non-zero. 
       // It stops when n becomes 0 and 
       // sum becomes single digit. 
       while (n > 0 || sum > 9) 
       { 
           if (n == 0) 
           { 
               n = sum; 
               sum = 0; 
           } 
           sum += n % 10; 
           n /= 10; 
       } 
       
       // Return true if sum becomes 1. 
       return (sum == 1); 
   } 
     
   public static void main(String args[]) 
    { 
      Scanner sc=new Scanner(System.in);
        int n ,c; 
        System.out.println("Enter the number:");
        n=sc.nextInt();
     if (isMagic(n)) 
        System.out.println("Magic Number"); 
           
     else
        System.out.println("Not a magic Number"); 
    } 
} 

Output:

Enter the number:
123
Not a magic Number
Enter the number:
1234
Magic Number

Java program to convert from octal to decimal


Program to  convert  octal  to decimal

import java.util.*;
public class Oct2Decimal{

//method definition to convert octal numbers into decimal

public static int getDecimal(int octal){
int decimal = 0;
//Declaring variable to use in power
int ct = 0;
while(true){
if(octal == 0){
break;
} else {
int temp = octal % 10;
decimal += temp*Math.pow(8, ct); //
octal = octal/10;
ct++;
}
}
return decimal;
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter an octal number:");
int num=sc.nextInt();
Oct2Decimal od=new Oct2Decimal();

System.out.println("Decimal of given octal is: "+ od.getDecimal(num));
}
}                         


Enter an octal number:
11
Decimal of given octal is: 9
Enter an octal number:
2
Decimal of given octal is: 2
Enter an octal number:
134
Decimal of given octal is: 92

Duck Number in java


A Duck number is a number which has zeroes present in it, but there should be no zero present in the beginning of the number.

import java.io.*;
class DuckNumber
{
    public static void main(String args[])throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter any number : ");
        String n=br.readLine(); //inputting the number and storing it in a String
 
        int l=n.length(); //finding the length (number of digit) of the number
        int c=0; //variable for counting number of zero digits
        char ch;
 
        for(int i=1;i<l;i++)
        {
            ch=n.charAt(i); //extracting each digit and checking it is a '0' or not
            if(ch=='0')
                c++;
        }
         char f=n.charAt(0); //extracting the first digit 
         if(c>0 && f!='0')
            System.out.println("It is a duck number");
        else
            System.out.println("It is not a duck number");
    }
}

Output:

Enter any number : 234
It is not a duck number
Enter any number : 023
It is not a duck number
Enter any number : 4016
It is a duck 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

Decimal to hexadecimal program in java


Write a program to convert decimal to  hexadecimal

import java.io.*;
class dec2hex

{
    public static void main(String args[])throws IOException
    {
        BufferedReader br=new BufferedReader(new               InputStreamReader(System.in));
        System.out.println("enter a decimal number");
        int n=Integer.parseInt(br.readLine());
        int r;
        String s="";
        char dig[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        while(n>0)
        {
            r=n%16;
            s=dig[r]+s;
            n=n/16;
        }
        System.out.println("output="+s);
    }
}   

Output:

enter a decimal number
123
output=7B
enter a decimal number
129
output=81

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

Decimal to Binary conversion (without array)


Write a program to convert decimal into binary without using array and display the number of 1’sand 0’s.

import java.util.Scanner;
class bintoDec
{
public static void main(String args[])
{
int n, a, count0 = 0, count1=0;
String s = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter decimal number ");
n = sc.nextInt();
while(n>0)
{
a = n%2;
if(a == 1)
{
count1++;
}
else
count0++;
s = s+" "+a;
n = n/2;

}
System.out.println("Binary number: "+s);
System.out.println("No. of 1s: "+count1);
System.out.println("No. of 0 s: "+count0);
}
}

Output:

Enter decimal number
2
Binary number: 0 1
No. of 1s: 1
No. of 0 s: 1
Enter decimal number
6
Binary number: 0 1 1
No. of 1s: 2
No. of 0 s: 1
Enter decimal number
16
Binary number: 0 0 0 0 1
No. of 1s: 1
No. of 0 s: 4
Enter decimal number

Automorphic number in java


An automorphic number is a number whose square “ends” in the same digits as the number itself. For example, 52 = 25, 62= 36, 762 = 5776

import java.util.*;
class Automorphic
{
  public static void main(String args[]) throws Exception
  {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a Number : "); // Inputting the number
    int n = sc.nextInt();
    int sq = n*n; // Finding the square
 
    String num = Integer.toString(n); // Converting the number to String
    String square = Integer.toString(sq); // Converting the square to String
 
    if(square.endsWith(num)) // If the square ends with the number then it is Automorphic
        System.out.print(n+" is an Automorphic Number.");
    else
        System.out.print(n+" is not an Automorphic Number.");
    }
}

Output:

Enter a Number : 36
36 is not an Automorphic Number.

Enter a Number : 6
6 is an Automorphic Number

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.

Decimal to Binary conversion (using array)


Conversion of decimal to binary using array

import java.io.*;
import java.util.*;

class binaryArray
{
// function to convert decimal to binary
static void decToBinary(int n)
{
// array to store binary number
int[] binaryNum = new int[1000];

// counter for binary array
int i = 0;
while (n > 0)
{
// storing remainder in binary array
binaryNum[i] = n % 2;
n = n / 2;
i++;
}

// printing binary array in reverse order
for (int j = i - 1; j >= 0; j--)
System.out.print(binaryNum[j]);
}

// driver program
public static void main (String[] args)
{ Scanner sc=new Scanner(System.in);
int n ;
System.out.println("Enter a decimal value:");
n=sc.nextInt();
decToBinary(n);
}
}

Output:

Enter a decimal value:
7
111

Hexadecimal to decimal program in java


Write a java program to convert hexadecimal to decimal.

Hexadecimal – base 16(0 to 9,A to F)

Here, Multiplying the given hexadecimal Digits with base 16 to the power starts from 0.

 

 

public class HexToDecimal {

public static int getDecimal(String hex){
String digits = "0123456789ABCDEF"; hex = hex.toUpperCase();
int val = 0;
for (int i = 0; i < hex.length(); i++)
{
char c = hex.charAt(i);
int d = digits.indexOf(c);
val = 16*val + d;
}
return val; }
public static void main(String args[]){
System.out.println("Decimal of 426 is: "+getDecimal("426")); System.out.println("Decimal of f is: "+getDecimal("f")); System.out.println("Decimal of 121 is: "+getDecimal("121"));
}} 

Output:

Decimal of 426 is: 1062
Decimal of f is: 15
Decimal of 121 is: 289

Evil Number/Odious Number in java


An evil number is a non-negative number that has an even number of 1s in its binary expansion. (Binary Expansion – is representation of a number in the binary numeral system or base-2 numeral system which represents numeric values using two different symbols: typically 0 (zero) and 1 (one)).

Odious Numbers: Numbers that are not Evil are called Odious Numbers. Given a number, the task is to check if it is Evil Number or Odious Numbers.

import java.util.*;
class EvilNumber 
{
  String toBinary(int n) // Function to convert a number to Binary
  {
   int r;
   String s=""; //variable for storing the result
   char dig[]={'0','1'}; //array storing the digits (as characters) in a binary number system
   while(n>0)
   {
       r=n%2; //finding remainder by dividing the number by 2
       s=dig[r]+s; //adding the remainder to the result and reversing at the same time
       n=n/2;
    }
    return s;
  }


  int countOne(String s) // Function to count no of 1’s in binary number
  {   
      int c = 0, l = s.length();
      char ch;
      for(int i=0; i<l; i++)
      {
          ch=s.charAt(i);
          if(ch=='1')
          {
              c++;
          }

      }
      return c;
  }
  public static void main(String args[])
  {
      EvilNumber ob = new EvilNumber();
      Scanner sc = new Scanner(System.in);
      System.out.print("Enter a positive number : ");
      int n = sc.nextInt();
      String bin = ob.toBinary(n);
      System.out.println("Binary Equivalent = "+bin);
      int x = ob.countOne(bin);
      System.out.println("Number of Ones = "+x);
      if(x%2==0)
        System.out.println(n+" is an Evil Number.");
      else
        System.out.println(n+" is  an Odious Number.");
  }
}

Output:

Enter a positive number : 23
Binary Equivalent = 10111
Number of Ones = 4
23 is an Evil Number.


Enter a positive number : 21
Binary Equivalent = 10101
Number of Ones = 3
21 is an Odious Number.

Java program to check Unique Number


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

( A Unique number is a positive integer (without leading zeros) with no duplicate digits. For example 7, 135, 214 , 5243 are all unique numbers whereas 33, 3121, 200 are not.)

 
import java.util.*;

class UniqueNumber

{

public static void main(String args[] )

{

Scanner sc=new Scanner(System.in);

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

int n=sc.nextInt();

String 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.

int l=s.length();

int flag=0,i, j;

//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; }

}

}

if(flag ==0)

System.out.println(" It is an UniqueNumber");

else

System.out.println(" It is not an UniqueNumber");

}

}

Output:

Enter a number: 5673

It is an UniqueNumber

Enter a number: 5675

It is not an UniqueNumber

Conversion of octal to decimal number


import java.util.*;
public class Octal2Decimal{

//method definition to convert octal numbers into decimal

public static int getDecimal(int octal){
int decimal = 0;
//Declaring variable to use in power
int ct = 0;
while(true){
if(octal == 0){
break;
} else {
int temp = octal % 10;
decimal += temp*Math.pow(8, ct); //
octal = octal/10;
ct++;
}
}
return decimal;
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println(“Enter an octal number:”);
int num=sc.nextInt();
Octal2Decimal od=new Octal2Decimal();

System.out.println(“Decimal of given octal is: “+ od.getDecimal(num));
}
}

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”.

ICSE-Computer Applications- October 2018


                                  Section A (40 Marks)
                                Answer all questions.

Question 1                                                                                                                              [10]

  1. Declare a single dimensional array of 10 integer values.
  2. Convert the following while loop to the corresponding for loop.
    int m=5, n=10;

while(n>=1)   {
System.out.println(m*n);
n–;
}

  1. Convert the following segment into an equivalent do loop:

int x,c;

for(x=10, c=20;c>=20;c=c-2)

x++:

  1. What is the final value of ctr when the iteration process given below, executes?

int ctr=0;
for(int j=1;j<=5;j+=2)
++ctr;

  1. If, array[]={1,4,5,6,3,32,23,90}; i) What is array.length?  ii) What is array[10]?

Question 2                                                                                                                                [10]

  1. Which keyword used to acquire the properties of one class to another class?
  2. Here is a skeleton definition of a class
    class Sample {
    int i;
    char c;
    float f;
    } Implement the constructor.
  3. Write a program to check whether the given number is palindrome or not.
  4. Differentiate between public and private modifiers for members of a class.
  5. What type of inheritance does Java here?

Question 3                                                                                                                                [10]

  1. Write a program to print Fibonacci series i.e., 0 1 1 2 3 5 8…..The number of terms required, is to be passed as parameter.
  2. What will be the result stored in x after evaluating the following expression?
    int x =42;
    x+ = (x++ ) + (++x) +x;
  3. What will be the output of the following code?

int m=3;

int n=15;

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

m++;

–n;

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

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

  1. Analyze the following program segment and determine how many times the loop will be executed and what will be the output of the program segment?
    int p=200;

while(true)

{

if(p<100)

break;

p=p-40;

}

System.out.println(p);

  1. The following is a segment of a program

x=1; y=1;
if(n>0)  {

x=x+1;
y=y+1;}

What will be the value of x and y, if n assumes a value  i)1  ii) 0 ?

Question 4                                                                                                                                [10]

  1. Give two differences between the switch statement and if else statement.
  2. Write two difference between linear search and binary search.
  3. Given that in x[][]={{2,4,6},{3,5,7}}, what will be the value of x[1][1] and x[0][2]?
  4. State the total size in bytes, of the arrays a[4] of char data type and p[6] of float data type.
  5. If int x[]={4,3,7,8,9,10}; What are the values of p and q?
    i) p= x.length     ii)   q=x[2] +x[5] * x[1]

   

 

         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]
Designa class to overload a function polygon() as follows:
i)          void polygon(int n, char ch)       : with one integer argument and one character type argument that draws a filled square of side n using the character stored in ch.

  1. ii) void polygon(int x, int y) : with two integer arguments that draws a filled rectangle of length x and breadth y using the symbol ‘@’.

iii)         void polygon()              : with no argument that draws a filled triangle shown below.

Example:

  1. i) Input value of n=2, ch=’O’

Output: OO
OO

  1. ii) Input value of x=2,y=5

Output

@@@@@

@@@@@

 

iii) Output

*

* *

* * *

 
Question 6                                                                                                                              [15]

Write  a menu driven program  to accept a number and check and display whether it is a prime number or not OR an automorphic number or not.

  1. a) Prime number : A number is said to be a prime number if it is divisible only by 1 and itself and not by any other number. Example; 3,5,7,11,13..
  2. b) Automorphic number : An automorphic is the number which is contained in the last digit of the square. Example : 25 is an automorphic number as its square is 625 and 25 is present as the last two digits.

 

Question 7                                                                                                                              [15]

Special words are those words which start and end with the same letter.
Examples:  EXISTENCE, COMIC, WINDOW
Palindrome words are those words which read the same from left to right and vice-versa.

Examples: MALAYALAM, MADAM, LEVEL, ROTATOR

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

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

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                                                                                                                             

 1)  Write a program to initialize the given data in an array and find the minimum and maximum    values along with the sum of the given elements.                                                                                                                             [5]

Numbers: 2 5 4 1 3

Output: Minimum value  : 1
Maximum value=5

Sum of the elements=15

 

2) Write a program to accept 15 integers from the keyboard, assuming that no integer entered is a zero. Perform selection sort on the integers and then print them in ascending order.        [10]

 

Question 10                                                                                                                            [15] Define a class and store the given city names in a single dimensional array. Sort these names in alphabetical order using the bubble sort technique only.

Input:  Calcutta, Agra, Mumbai, Bangalore, Delhi

Output: Agra, Bangalore, Calcutta, Delhi, Mumbai

 

.

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.

Perform a right circular shift and a left circular shift on alternate rows of the array — by object


A class Whirl contains a 2D array of order [m * n]. Perform a right circular shift and a left circular shift on alternate rows of the array.
For example:  Input  m=5, n=4
The matrix is:
20 2 24 25
48 18 13 47
43 18 30 32
22 45 30 38
48 12 18 37

Output:
Right circular shift and left circular shift on alternate rows of the matrix:
The matrix is:
25 20 2 24
18 13 47 48
32 43 18 30
45 30 38 22
37 48 12 18

Class name              :Whirl
Data member:
wam[][]            : to store the amtrix
int m, n             : integer to store the number of rows and columns
Member functions:
Whirl(……)        :  initialize m, n and to allocate memory to member array
void fnGet()     : to fill the member array
void fnDisplay() : to show the member matrix
Whirl fnChangeMat()  :  modify the current matrix as per the given criteria and returns it.Specify the class Whirl, and define main() , giving the details of the above member data and methods.
Program:

import java.util.*;
class Whirl
{
int wam[][], m,n;
Whirl(int m1, int n1)
{
m=m1; n=n1;
wam=new int[m][n];
}
void fnGet()
{
for(int r=0;r<=m-1;r++)
{
for(int c=0;c<=n-1;c++)
wam[r][c]=(int)(Math.random()*50);
}
}

void fnDisplay()
{
System.out.println(“The matrix is:”);
for(int r=0;r<=m-1;r++)
{
for(int c=0;c<=n-1;c++)
{
System.out.print(wam[r][c]+”\t”);
}
System.out.println();
}

}
Whirl fnChangeMat()
{ int tmp=0;
for(int r=0;r<=m-1;r++)
{
if(r%2==0)
{
tmp=wam[r][n-1];
for(int c=n-1;c>=1;c–)
{ wam[r][c]=wam[r][c-1];
}
wam[r][0]=tmp;
}
else
{
tmp=wam[r][0];
for(int c=0;c<=n-2;c++)
{
wam[r][c]=wam[r][c+1];
}
wam[r][n-1]=tmp;
}
}
return this;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);

System.out.println(“Enter the value of m:”);
int m1=sc.nextInt();
System.out.println(“Enter the value of n:”);
int n1=sc.nextInt();
Whirl w=new Whirl(m1,n1);
Whirl w1=new Whirl(m1,n1);
w.fnGet();
w.fnDisplay();
w1=w.fnChangeMat();
System.out.println(“Right circular shift and left circular shift on alternate rows of the matrix:”);
w1.fnDisplay();
}
}

Output:
Enter the value of m:
5
Enter the value of n:
4
The matrix is:
20 2 24 25
48 18 13 47
43 18 30 32
22 45 30 38
48 12 18 37
Right circular shift and left circular shift on alternate rows of the matrix:
The matrix is:
25 20 2 24
18 13 47 48
32 43 18 30
45 30 38 22
37 48 12 18

Create a new string by the common characters present in given two strings ( without repetition)


A class Stricom contains two strings and creates a new string using the common characters present in both the strings(without repetition)
For example:     String1  :  “Chinese”       String 2  :   “Checkers”
New string :  “Ches”
Some of the members of the class are given below:
Class Name   : Stricom
Data members:
stA, stB    : the member strings
Member functions:
Stricom(…)     : to initialize  member string to the arguments
String fnCommon()  :  to create a new string using the common characters of both the member strings and return that(use member method fnLen())
void fnShow()           :  to print the member strings and the new string as per the question [ to use the member method fnCommon]
int fnLen(String s)   : to return the length of the argument string.

Specify the class Stricom, and define main() giving the details of the above member data and methods only.

Program:

import java.util.*;
class Stricom
{
String stA, stB;
Stricom(String s1, String s2)
{
stA=s1;
stB=s2;
}
int fnLen(String s)
{
return s.length();
}
void fnShow()
{
String ns=fnCommon();
System.out.println(“string stA :”+ stA +”\nString stB :”+stB);
System.out.print(“New String :”+ns);
}
String fnCommon()
{
//int count=0;
String ns=””, ans=””;
char ch;
for(int j=0;j<=fnLen(stA)-1;j++)
{
for(int k=0;k<=fnLen(stB)-1;k++)
{
if(stA.charAt(j)==stB.charAt(k))
{
// count++;
ns+=stA.charAt(j);
// if(count>=1)
// break;

}
}
}
// return ns;
String ns1=ns;
for(int i=0;i<ns1.length(); i++)
{
ch=ns1.charAt(i);
if(ch!=’ ‘)
{
ans=ans+ch;
ns1=ns1.replace(ch,’ ‘);
}
}
return ans;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the first string:”);
String st1=sc.next();
System.out.println(“Enter the second string:”);
String st2=sc.next();
Stricom sm=new Stricom(st1,st2);
sm.fnShow();
}
}

Output:
Enter the first string:
chinese
Enter the second string:
checkers
string stA :chinese
String stB :checkers
New String :ches

N1 to create another number N2 by attaching the sum of the digits of N1 behind it.


A class Attach works on a number N1 to create another number N2 by attaching the sum of the digits of N1 behind it.

For example N1= 712          N2=71210
For example  N1= 123          N2= 1236

Design a class  Attach some of the members of the class are given below:
Class Name     : Attach
Data members:
N1,N2           : inegers
Member functions:
Attach()       : constructor to assign null to the member data
void getNum () : input a 3 digit number in N1. If not a 3 digit number, N1 is entered again
void makeNum()  :  to create N2 using N1 as per given criteria ( utilize method addDigits()]
int addDigits(int n)   :   to add the digits of argument ‘n’ and return the sum
Specify the class Attach, 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.

Program:

import java.util.*;
class Attach
{
int N1,N2;
public Attach()
{
N1=0;
N2=0;
}
void getNum()
{
Scanner sc=new Scanner(System.in);
do
{
System.out.print(“\f Enter a 3 digit number:”);
N1=sc.nextInt();
}while(N1<100 || N1>999);
}
int addDigits(int n)
{
int c=n, sum=0;
while(c!=0)
{
sum=sum +c%10;
c/=10;
}
return sum;
}
void makeNum()
{
int sum=addDigits(N1);
int copy=sum, nd=0;
while(copy!=0)
{
nd++;
copy/=10;
}
N2=(int) (N1* Math.pow(10,nd))+sum;
}
public static void main(String args[])
{
Attach obj=new Attach();
obj.getNum();
obj.makeNum();
System.out.println(“N1=”+obj.N1+”\t”+”N2=” +obj.N2);
}
}

Output:

Enter a 3 digit number:   125
N1=125 N2=1258

Enter a 3 digit number:   205
N1=205 N2=2057

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