Remove repeated words


write a program in java to remove the repeated strings(words) from the input sentence.

import java.io.*;
class repeatwords
{
     public static void main(String args[]) throws IOException
    {
     InputStreamReader read = new InputStreamReader(System.in);
    BufferedReader x=new BufferedReader (read);
    System.out.println("enter any word");
    String s=x.readLine();
    s=s+" ";
    int l=s.length();
    String ans="";
    char ch1,ch2;
    for(int i=0;i<l-1;i++)
    {
        ch1=s.charAt(i);
        ch2=s.charAt(i+1);
        if(ch1!=ch2)
        {
            ans=ans+ch1;
        }
    }
    System.out.println("word after removing repeated characters="+ans);
}
}

Output:

enter any word
javaaaaaa
word after removing repeated characters=java

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

Prime Triplets


import java.util.*;
class primeTriplets
{ 
    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[]) 
        {
            Scanner sc=new Scanner(System.in);
            System.out.println("Enter the lower and upper range:");
            int m=sc.nextInt();
            int n=sc.nextInt();
            primeTriplets pt=new primeTriplets();
            int prime=0;
            //pt.get();
            if(m>0 && n> 0  && m<n)
            {
                System.out.println("Prime Triplets:");
                for(int i=m;i<n;i++)
                {
                    if(pt.isPrime(i)==true && pt.isPrime(i+2)==true && pt.isPrime(i+6))
                    {System.out.print(i+" " + (i+2) +" " +(i+6)+"\n");
                    prime++;
                }
                    else if(pt.isPrime(i)==true && pt.isPrime(i+4)==true && pt.isPrime(i+6))
                  {  System.out.print(i+" " + (i+4) +" " +(i+6)+"\n");
                      prime++;
                    }
                    
                    else
                    {
                    }
                }
                
            }
            else
            System.out.println("invalid");
            System.out.println("Total prime triplets are:"+prime);
        }
}

Output:

Enter the lower and upper range:
2
17
Prime Triplets:
5 7 11
7 11 13
11 13 17
13 17 19
Total prime triplets are :  4

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

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

Smith number


A Smith Number is a composite number whose sum of digits is equal to the sum of digits of its prime factors obtained as a result of prime factorization (excluding 1). The first few such numbers are 4, 22, 27, 58, 85, 94, 121 ………………..

Examples:

1. Enter a Number : 85
Sum of Digit = 13
Sum of Prime Factor = 13
It is a Smith Number

2. Enter a Number : 666
Sum of Digit = 18
Sum of Prime Factor = 18
It is a Smith Number

3. 999

Enter a Number : 999
Sum of Digit = 27
Sum of Prime Factor = 19
It is Not a Smith Number

Write a program to input a number and display whether the number is a Smith number or not.

import java.util.*;
public class SmithNumbers
{

//Extracting digits and find the sum of the digits
int sumDigit(int n)
{
int s=0;
while(n>0)
{
s=s+n%10;
n=n/10;
}
return s;
}

int sumPrimeFact(int n)
{
int i=2, sum=0;
while(n>1)
{
if(n%i==0)
{
sum=sum+sumDigit(i);
n=n/i;
}
else
{
do{
i++;
}while(!IsPrime(i));
}
}
return sum;
}
boolean IsPrime(int k)
{
boolean b=true;
int d=2;
while(d<Math.sqrt(k))
{
if(k%d==0)
{
b=false;
}
d++;
}
return b;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
SmithNumbers ob=new SmithNumbers();
System.out.print(“Enter a Number : “);
int n=sc.nextInt();
int a=ob.sumDigit(n);
int b=ob.sumPrimeFact(n);
System.out.println(“Sum of Digit = “+a);
System.out.println(“Sum of Prime Factor = “+b);
if(a==b)
System.out.print(“It is a Smith Number”);
else
System.out.print(“It is Not a Smith 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

 

.

ICSE


  1. Define abstraction.
  2. Define escape sequence with examples.
  3. Write a difference between the functions isUpperCase( ) and toUpperCase( ).
  4. How are private members of a class different from public members?
  5. Classify the following as primitive or non-primitive datatypes:
    (i) char(ii) arrays(iii) int(iv) classes