Wednesday, 30 October 2013

Mersenne Numbers

In mathematics, a Mersenne prime is a prime number of the form . They are named after the French monk Marin Mersenne who studied them in the early 17th century.

If n is a composite number then so is 2n − 1. The definition is therefore unchanged when written where p is assumed prime.

More generally, numbers of the form without the primality requirement are called Mersenne numbers. Mersenne numbers are sometimes defined to have the additional requirement that n be prime, equivalently that they bepernicious Mersenne numbers, namely those pernicious numbers whose binary representation contains no zeros. The smallest composite pernicious Mersenne number arises with p = 11.

A double Mersenne number is a Mersenne number of the form

where p is a Mersenne prime exponent.


import java.util.Scanner;
public class Numbers
{
long number;
Numbers(long n)
{
number=n;
}
boolean isMersenne(){
long n=0;
for(int i=1;i<=20;i++)
{
n=(long)(Math.pow(2,i)-1);
if(n==number){
return true;
}
}
return false;
}
boolean isDoubleMersenne(){
long n=0;long pwr=0;
for(int i=1;i<=20;i++)
{
pwr=(long)Math.pow(2,i)-1;
n=(long)(Math.pow(2,pwr)-1);
if(n==number)
{
return true;
}
}
return false;
}
public void genMersenneNos(){
long num=0;
System.out.println("Generated Mersenne numbers are :");
for(int i=1;i<=10;i++)
{
num=(long)(Math.pow(2,i)-1);
System.out.print(num+" ");
}
System.out.println();
}
public void genDoubleMersenneNos()
{
long num=0;long pwr=0;
System.out.println("Generated double Mersenne Numbers are:");
for(int i=1;i<=6;i++)
{
pwr=(long)Math.pow(2,i)-1;
num=(long)(Math.pow(2,pwr)-1);
System.out.print(num+" ");
}
System.out.println();
}
public static void main(String[]args){
Scanner in=new Scanner(System.in);
long n;
System.out.println("Enter a number");
n=in.nextLong();
Numbers numObject=new Numbers(n);
if(numObject.isDoubleMersenne()==true)
{
System.out.println(n+"is a double Mersenne Number");
numObject.genDoubleMersenneNos();
}
else if(numObject.isMersenne()==true)
{
System.out.println(n+"is a Mersenne Number");
numObject.genMersenneNos();
}
else
System.out.println(n+"is neither a Mersenne Number nor a Double Mersenne Number");
}
}

Catalan Numbers

In combinatorial mathematics, the Catalan numbers form a sequence of natural numbers that occur in various counting problems, often involving recursively defined objects. They are named after the Belgian mathematician Eugène Charles Catalan(1814–1894).

The nth Catalan number is given directly in terms of binomial coefficients by


The first Catalan numbers for n = 0, 1, 2, 3, … are
1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670, 129644790, 477638700, 1767263190, 6564120420, 24466267020, 91482563640, 343059613650, 1289904147324, 4861946401452, …


import java.util.Scanner;
class Catalan
{
public static void main(String[ ] args)
{
Scanner in=new Scanner (System.in);
System.out.println("Enter value of n(1...10):");
int n=in.nextInt();
long n1,n2,a;
long CatNumber;
int cnt=1;
if(n>=1 && n<=10)
{
for(a=1;a<=n;a++)
{
long factofa=1,factof2a=1;
for(long i=1;i<=a;i++)
factofa*=i;
for(long i=1;i<=2*a;i++)
factof2a*=i;
CatNumber=factof2a/((factofa*factofa)*(a+1));
System.out.println(" "+cnt++ +". "+CatNumber);
}
}
}
}

Monday, 28 October 2013

Printing a sentence in reverse order of words

The input in this problem will consist of a number of lines of English text consisting of the letters of the English alphabet, the punctuation marks (‘) apostrophe, (.) full stop, (,) comma, (;) semicolon, (:) colon and white space characters (blank, newline). Your task is to print the words of the text in reverse order without any punctuation marks other than blanks.
For example consider the following input text :
This is a simple piece of text to illustrate this problem.

If you are smart you will solve this right.

The corresponding output would read as:

right this solve will you smart are you If problem this illustrate to text of piece sample a is This

That is, the lines are printed in reverse order.
Note:- Individual words are not reversed.

Input format

The first line of input contains a single integer N (<=20), indicating the number of lines in the input. This is followed by N lines of input text. Each line should accept a maximum of 80 characters.

Output format

Output the text containing the input lines in reverse order without punctuations except blanks as illustrated above.

Test your program for the following data and some random data.

SAMPLE DATA

INPUT :

2
Emotions, controlled and directed to work, is character. By Swami Vivekananda.

OUTPUT :
Vivekananda Swami By character is work to directed and controlled Emotions


INPUT :

1
Do not judge a book by its cover.

OUTPUT :
cover by its book a judge not Do


Answer 2.
import java.io.*;
class Q2_2007
{
  //Data members
  private String para;
  private String newpara;
  int len;
  int n;
  //Constructor
  public Q2_2007()
  {
      para="";
      newpara="";
      len=0;
  }
  //Function to input string
  public void Input()
  throws IOException
  {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     System.out.print("Enter number of lines ::");
     n=Integer.parseInt(br.readLine());
     System.out.println("Enter a paragraph of "+ n + " lines ");
     para=br.readLine();
     para=" "+para;
     len=para.length();
  }
  //Function to reverse para
  public void Reversepara()
  {
      int i;
      String word="";
      char letter;
      for(i=(len-1);i>=0;i--)
      {
          letter = para.charAt(i);
          if(letter!='\'' && letter!='.'&&letter!=','&&letter!=';'&&letter!=':'&&letter!=' ')
            word=letter+word;
          else
          {
              newpara+=word;
              newpara+=" ";
              word="";
            }
        }
        System.out.println("\n new paragraph ::\n"+newpara);
    }
}
 
import java.io.*;
class Q2_2007main
{
   public static void main(String args[])
   throws IOException
    {
        Q2_2007 obj = new Q2_2007();
        obj.Input();
        obj.Reversepara();
    }
}

Output
Enter number of lines ::2
Enter a paragraph of 2 lines
Emotions, controlled and directed to work, is character. By Swami Vivekanda.

 new paragraph ::
 Vivekanda Swami By  character is  work to directed and controlled  Emotions

Enter number of lines ::1
Enter a paragraph of 1 lines
Do not judge a book by its cover.

 new paragraph ::
 cover its by book a judge not Do  

Friday, 25 October 2013

Anagrams

We would like to generate all possible anagrams of a word. For example if the given word is 'TOP', there will be 6 possible anagrams:
       TOP
       TPO
       OPT
       OTP
       PTO
       POT

An anagram must be printed only once. You may output the anagrams in any order. Also output the total number of anagrams. You assume that the number of letter, n, in the word will be 7 at most, i.e. n<= 7
Test your program for the given data and some random data.

SAMPLE DATA:
     INPUT:
                       TO

OUTPUT:
                     TO
                     OT
Total number of anagrams = 2

INPUT :
                     LEAN
OUTPUT:
                     LEAN
                     LENA
                     LAEN
                     LANE
                     LNEA
                     LNAE
                     EALN
                     EANL
                     ELAN
                     ELNA
                     ENLA
                     ENAL
                     ALNE
                     ALEN
                     ANLE
                     ANEL
                     AENL
                     NLEA
                     NLAE
                     NELA
                     NEAL
                     NALE
                     NAEL
Total number of anagrams = 24




import java.io.*;
public class Anagrams
{
    String str;
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    int counter=0;
    public void take()throws Exception
    {
        System.out.println("\nEnter the word:");
        str=br.readLine();
        show("", str);
        System.out.println("Total number of anagrams ="+counter);
    }

    public void show(String s, String str)
    {
        if(str.length()<= 1)
        {
            counter++;
            System.out.println(s+str);
        }
        else
        {
            for(int i = 0; i< str.length(); i++)
            {
                String str1 = str.substring(i, i + 1);
                String str2 = str.substring(0, i);
                String str3 = str.substring(i + 1);
                show(s + str1, str2 + str3);
            }
        }
    }

    public static void main(String args[])throws Exception
    {
        Anagrams ob=new Anagrams();
        ob.take();
    }
}

Binary search using recursion

class binsearchprog
{
    public void main()
    {
        int ar[]={12,23,32,34,45};
        int i,lb=0,ub=4,ser;
        ser=12;
        int f=binsearch(ar,ser,lb,ub);
        if(f == 1)
            System.out.println("Ele found....");
        else
            System.out.println("Ele not found...");
    }

    int binsearch(int ar[],int ser,int lb,int ub)
    {
        int mb=(lb+ub)/2,i=0;
        if(lb>ub)
            return 0;
        if(ser>ar[mb])
        {
            lb=mb+1;
            return binsearch(ar,ser,lb,ub);
        }
        else if(ser<ar[mb])
        {
            ub=mb-1;
            return binsearch(ar,ser,lb,ub);
        }
        else
        return 1;
    }
}

Thursday, 24 October 2013

Login and Logout time

The manager of a company wants to analyse the machine usage from the records to find the utilization of the machine. He wants to know how long the each user used the machine. When the user wants to use the machine he must login to the machine and after finishing the work he must log off the machine.
Each log record consists of:

User Identification number
Login time and date
Logout time and date

Time consists of
Hours
Minutes

Date consists of
Day
Month

You may assume all logins and logouts are in the same year and there are 100 users at most. The time format is 24 hour machine hours and minutes.
Design a program to find:
To find the duration for which each user has logged.
Output all records along with the duration. You may assume no user will login for more than 48 hours.

Test your program for the following data values and some random data values.

Sample data:
INPUT :
Number of users : 3
USER LOGIN LOGOUT
IDENTIFICATION TIME & DATE TIME & DATE

149         20:10 20-12 2:50        21-12
173        12:30   20-12 12:30 21-12
142       16:20  20-12 16:30 20-12

OUTPUT :

USER LOGIN LOGOUT DURATION
IDENTIFICATION TIME & DATE TIME & DATE HOURS:MINS
149 20:10 20-12 2:50 21-12 6:40
173 12:30 20-12 12:30 21-12 24:00
142 16:20 20-12 16:30 20-12 00:0

The user who logged in for the longest duration:-
173 12:30 20-12 12:30 21-12 24:00

Answer 3.
import java.io.*;
class Date
{
 //Data members
 public int day;
 public int month;
 //Constructor
 public Date()
 {
     day=0;
     month=0;
 }
 //Function to input date 
 public void Input()
 throws IOException
  {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       System.out.println("Enter day ::");
       day=Integer.parseInt(br.readLine());
       System.out.println("Enter month ::");
       month=Integer.parseInt(br.readLine());
    }
  //function to display date
  public void display()
  {
      System.out.print(day+"-"+month);
   }
}
import java.io.*;
class Time
{
 //Data members
 public int hour;
 public int minute;
 //Constructor
 public Time()
 {
     hour=0;
     minute=0;
 }
 //Function to input time
 public void Input()
 throws IOException
  {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       System.out.println("Enter hour ::");
       hour=Integer.parseInt(br.readLine());
       System.out.println("Enter minute ::");
       minute=Integer.parseInt(br.readLine());
    }
  //function to display time
  public void display()
  {
      System.out.print(hour+":"+minute);
   }
}
import java.io.*;
class Q3_2004
{
 //Data members
 public Date logindt;
 public Date logoutdt;
 public Time logintm;
 public Time logouttm;
 private int userid;
 //Constructor
 Q3_2004()
 {
     userid=0;
     logindt=new Date();
     logoutdt=new Date();
     logintm=new Time();
     logouttm=new Time();
  }
  //Function to input data
  public void Input()
  throws IOException
  {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       System.out.println("Enter user identification number ::");
       userid=Integer.parseInt(br.readLine());
       System.out.println("Enter login time::");
       logintm.Input();
       System.out.println("Enter login date::");
       logindt.Input();
       System.out.println("Enter logout time::");
       logouttm.Input();
       System.out.println("Enter logout date::");
       logoutdt.Input();       
    }
   //Function to find duration
   public Time Duration()
   {
       Time duration=new Time();
       if(logintm.minute > logouttm.minute)
         duration.minute=(60-logintm.minute)+logouttm.minute;
       else
         duration.minute = logouttm.minute-logintm.minute;
       duration.hour=(24-logintm.hour)+logouttm.hour;
       return duration;
    }
  //Function to display
  public void Display()
  {
      System.out.print(userid+"\t\t"+logintm.hour+":"+logintm.minute+"\t"+logindt.day+"-"+logindt.month+"\t\t"+logouttm.hour+":"+logouttm.minute+"\t"+logoutdt.day+"-"+logoutdt.month);
  }
    
  //Function to find duration
  public void findduration()
  throws IOException
  {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       int n,i,longhour=0;
       
       Q3_2004 longobj=new Q3_2004();
            
       System.out.println("Number of users :;");
       n=Integer.parseInt(br.readLine());
       Time longdur =new Time();
       for(i=1;i<=n;i++)
       {
           System.out.println("\nEnter details for user "+i);
           Q3_2004 obj=new Q3_2004();
           obj.Input();
           obj.Display();
           Time dur=new Time();
           dur=obj.Duration();
           System.out.print("\t\t");
           dur.display();
           System.out.println("\n");
           
           if(dur.hour>longhour)
           {
               longhour=dur.hour;
               longobj=obj;
               longdur=dur;
            }
        }
       
        System.out.println("\nThe user logged in for the longest duration ::");
        longobj.Display();
        System.out.print("\t\t");
        longdur.display();
    }
}
import java.io.*;
class Q3_2004main
{
  public static void main(String args[])
  throws IOException
  {
      Q3_2004 obj=new Q3_2004();
      obj.findduration();
    }
}               

Encoding

The Computer Department of the Agency of International Espionage is trying to decode intercepted messages. The agency’s spies have determined that the enemy encodes messages by first converting all characters to their ASCII values and then reversing the string.
For example consider A_z ( the underscore is just to highlight the space. The ASCII values of A, <space>, z are 65, 32 and 122 respectively. Concatenate them to get 6532122, then reverse this to get 2212356 as the coded message.
Write a program which reads a coded message and decodes it. The coded message will not exceed 200 characters. It will contain only alphabets (A..Z and a..z) and spaces. ASCII values of A…Z are 65 to 90 and those of a..z are 97 to 122.


import java.io.*;
class Q2_2004
{
    //Data Members
    public String msg;
    public String ans;
    public String rev;
    public int len;
    public String newans;
       
    //Methods
    //Default Constructor
    Q2_2004()
    {
        msg="";
        ans="";
        rev="";
        len=0;
        newans="";
    }
   
    //Function to input the encoded message
    public void Input()
    throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       
        int i,len1;
        System.out.println("Enter the encoded message");
        msg=br.readLine();
        len1=msg.length();
        for(i=(len1-1);i>=0;i--)
           rev+=msg.charAt(i);
        len=rev.length();
    }
   
    //Function to extract the digits from the reverse number and decode it
    public void Decode()
    throws IOException
    {
        Input();
        int lwrnum[]={97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122};
        char lwrcas[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
        int uprnum[]={65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90};
        char uprcas[]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
       
        int i,j;
        int digit;
        int number=0;
        for(i=0;i<len;i++)
        {
            digit=Integer.parseInt(rev.substring(i,i+1));
            number=number*10+digit;
           
            if(number>=65 && number <=90)
            {
               for(j=0;j<26;j++)
               {
                   if(number==uprnum[j])
                     ans+=uprcas[j];
                }//j
                number=0;
            }//if
            else
            if(number>=97 && number <=122)
            {
               for(j=0;j<26;j++)
               {
                   if(number==lwrnum[j])
                     ans+=lwrcas[j];
                }//j
                number=0;
            }//if
            else
            if(number==32)
            {
              ans+=" ";
              number=0;
            }
         }//i
         ans=" "+ans;
         ans+=" ";
         len=ans.length();
        
         char ltr;
         for(i=0;i<len;i++)
         {
             ltr=ans.charAt(i);
             if(ltr!=' ')
               newans+=ltr;
             else
             if(ltr==' ')
             {
                 newans+=ltr;
                 ltr=ans.charAt(i+1);
                 for(j=0;j<26;j++)
                 {
                     if(ltr==lwrcas[j])
                        ltr=uprcas[j];
                 }
                 newans+=ltr;
                 i++;
             }//if
         }
    }
   
    //Function to Display the string
    public void Display()
    throws IOException
    {
        Decode();
        System.out.print("The decoded message is :: "+newans);
    }
}
                       
import java.io.*;
class Q2_2004main
{
    public void main()
    throws IOException
    {
        Q2_2004 SM=new Q2_2004();
        SM.Display();
    }
}

 Sample Output
Enter the encoded message
2312179862310199501872379231018117927

The decoded message is ::  Have A Nice Day  

File Handling

A file contains a list of names and telephone numbers in the following form:-
AJIT                                        281050
ANIL                                       462890
RISHIKESH                            524352

The names contain only one word and the names and telephone numbers are separated by
white spaces. Write a interactive program to   :-
  • Create the above file
  • Display the contents of two columns
  • Search a telephone number for a given name( Assure no duplication of name)
  • Exit the program.

The program must create the program for the first time.
Test your program for the following data:-

AJIT                                        281050
ANIL                                       462890
RISHIKESH                            524352
JAVAGAL                              345678
MONGIA                                234561
RAHUL                                   765433
ROBIN                                    543221
SACHIN                                  765433
SAURAV                                8765908
VENKATESH                         7654322

Answer 3
import java.io.*;
class Names_Telephones
{
    public static void main(String args[])
    throws IOException
    {
        String filename="Directory.Txt";
        InputStreamReader isr=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(isr);
        int i,n;
        String search;
       
        System.out.println("How many students");
        n=Integer.parseInt(br.readLine());
        String name,phone;
       
        FileWriter fw=new FileWriter(filename);
        BufferedWriter bw=new BufferedWriter(fw);
        PrintWriter outfile=new PrintWriter(bw);
       
        System.out.println("Enter "+n+" records one by one");
       
        //Writing Records into file
        for(i=1;i<=n;i++)
        {
            System.out.println("Name::");
            name=br.readLine();
            outfile.println(name);
           
            System.out.println("Phone Number::");
            phone=br.readLine();
            outfile.println(phone);
        }
        outfile.close();
       
        //Reading Records into file
        FileReader readfile=new FileReader(filename);
        BufferedReader infile=new BufferedReader(readfile);
       
        System.out.println("Enter name to search");
        search=br.readLine();
       
        while((name=infile.readLine())!=null)
        {
            phone=infile.readLine();
            if(name.compareToIgnoreCase(search)==0)
            {
                System.out.println("Name ::"+name+ " Phone number :: "+phone);
            }
        }
      infile.close();
    }

}

Diamond String

Write a program to print a rectangle with a diamond shape gap exactly at the center of the
Rectangle, using an input string with odd number of characters, not exceeding 20.
For Example:-
INPUT                         :-         HAPPY-HAPPY
OUTPUT:
Enter a word of odd number of characters
HAPPY-HAPPY

HAPPY-HAPPY
HAPPY HAPPY
HAPP       APPY
HAP            PPY
HA                PY
H                     Y
HA                PY
HAP            PPY
HAPP       APPY
HAPPY HAPPY
HAPPY-HAPPY

Answer 1.
import java.io.*;
class Diamond_String
{
    //Data Member  
    public String word;
    public int len;
    public int spc;
   
    //Methods
    //Default Constructor
    Diamond_String()
    {
        word="";
        len=0;
        spc=0;
    }
       
        //Function to Input String
        public void Input()
        throws IOException
        {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            do
            {
                System.out.println("Enter a word of odd number of characters");
                word=br.readLine();
                word=word.toUpperCase();
                len=word.length();
                if(len>=20)
                System.out.println("Word is more than 20 characters.....Try again");
                if(len%2==0)
                System.out.println("Word is of even characters.....Try again");
            }
            while((len%2)==0);
        }
         
         //Function to Display first half of String
         public void Display1()
         {
            int x,i,j,k;
            spc=1;  
            x=(len/2)-1;
            k=0;
            System.out.println(word);
            for(i=1;i<=(len/2);i++)
            {
                //Printing left hand side
                for(j=0;j<=x;j++)
                    System.out.print(word.charAt(j));
                x--;
           
                //Printing spaces
                for(j=1;j<=spc;j++)
                    System.out.print(" ");
                spc+=2;
           
                //Printing right hand side
                for(j=k;j<(len/2);j++)
                    System.out.print(word.charAt(j));
                k++;
               
                System.out.println();
            }
        }
       
        //Function to Display second half of String
        public void Display2()
        {
            int i,j,k,x;
            spc-=4;
            k=(len/2)-2;
            x=1;
           
            for(i=1;i<=((len/2)-1);i++)
            {
                //Printing left hand side
                for(j=0;j<=x;j++)
                    System.out.print(word.charAt(j));
                x++;
                    
                //Printing spaces
                for(j=spc;j>=1;j--)
                    System.out.print(" ");
                spc-=2;
           
                //Printing right hand side
                for(j=k;j<(len/2);j++)
                    System.out.print(word.charAt(j));
                k--;
                System.out.println();
            }
           
            System.out.println(word);   
               
           
        }
    }
       
  import java.io.*;
class Diamond_Example
{
    public void main()
    throws IOException
    {
        Diamond_String DS=new Diamond_String();
        DS.Input();
        DS.Display1();
        DS.Display2();
    }

}

Wednesday, 23 October 2013

Unique Number

import java.io.*;
 class Unique 
public static void main(String args[])throws IOException
 {
 BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
 int check=0,count=0,m,n,j,d,no_of_digits=0,num; 
System.out.println("\nINPUT:\n");
 System.out.print("m=");
 m=Integer.parseInt(in.readLine());
 System.out.print("n=");
 n=Integer.parseInt(in.readLine());
 System.out.print("UNIQUE DIGIT INTEGERS ARE:");//find unique numbers between m and n for(j=m;j<=n;j++) 
check=0; for(d=0;d<=9;d++) //this loop helps in checking digits from 0 to 9 { num=j; no_of_digits=0; while(num>0)//finding digits from number stored
 { 
int digit=num%10;
 if(digit==d)//check the equality of extracted digit and value of d
 {
 no_of_digits++;
 }//end if
 num=num/10;
 }//end while loop
 if(no_of_digits>1) 
{
 check=1;
 break;//from here control goes out of for d loop 
}//end if 
}//end of d loop 
if(check==0)//here check=0 means digits of the number is not repeating so it is unique
 { 
System.out.print(j+" ");
 count++; 
}//end if
 }//end for j loop 
System.out.println("\n\nFREQUENCY OF UNIQUE DIGIT INTEGERS ARE:"+count); }//end of main }//end class

Inheritance program 2

A class Employee contains employee details and another class Salary calculates the employee’s net
salary. The details of the two classes are given below:
Class name : Employee
Data members
empNo : stores the employee number.
empName : stores the employee name
empDesig : stores the employee’s designation.

Member functions:
Employee() : default constructor.
Employee(…) : parameterized constructor to assign values to data
members.
void display() : display the employee details.

Class name : Salary
Data members
basic : float variable to store the basic pay.

Member functions
Salary(…) : parameterized constructor to assign values to data
members.
void calculate() : calculates the employee’s net salary according to the
following rules:

DA = 10% of basic
 HRA = 15% of basic
 Salary = basic + DA +H RA
 PF= 8 % of Salary
 Net Salary = Salary –PF
 Display the employee details and the Net salary.

class Employee
{
int empno;String empname,empdesig;
Employee()
{
empno=0;
empname=null;
empdesig=null;
}
Employee(int a,String b,String c)
{
empno=a;
empname=b;
empdesig=c;
}
void display()
{
System.out.println("Employee name:"+empname);
System.out.println("Employee number:"+empno);
System.out.println("Employee designation:"+empdesig);
}
}

import java.util.*;
class Salary extends Employee
{
float basic;
Salary(float b,int n,String name,String d)
{
super(n,name,d);
basic=b;
}
void calculate()
{
double da=0.1*basic,hra=0.15*basic,gross=basic+da+hra,pf=0.08*gross,netpay=gross-pf;
System.out.println("\nEmployee Details");
System.out.println("----------------");
super.display();
System.out.println("\nPayment Details");
System.out.println("----------------");
System.out.println("Basic="+basic+"\nDA="+da+"\nHRA="+hra+"\nGross Pay="+gross+"\nNet Pay="+netpay);
}
public static void main(String arg[])
{
Scanner ob=new Scanner(System.in);
System.out.print("Enter employee name:");
String name=ob.nextLine ();
System.out.print("Enter employee number:");
int n=ob.nextInt();
System.out.print("Enter employee designation:");
String d=ob.next();
System.out.print("Enter basic pay:");
float b=ob.nextFloat ();
Salary call=new Salary(b,n,name,d);
call.calculate();
}
}

Tuesday, 22 October 2013

Interchange names in odd places in an array to even places

public class InterchangeOddPlacesNamesToEven
{
    String t;
    void input(String a[])
    {
        int i,l=a.length;
        for(i=0;i<l;i++)
        {
            System.out.print(a[i]+" ");
        }
        System.out.println("\nAfter Arranging");
        for(i=0;i<l;i+=2)
        {
            t=a[i];
            a[i]=a[i+1];
            a[i+1]=t;
        }
        for(i=0;i<l;i++)
        {
            System.out.print(a[i]+" ");
        }
    }
}

Magic Number using recursion

class Magic
{
int n;
Magic()
{
n=0;
}
void getnum(int nn)
{
n=nn;
}
int SumOfDigit(int nn)
{
int s=0,x;
while(nn!=0)
{
x=nn%10;
nn=nn/10;
s=s+x;
}
return s;
}
void isMagic()
{
int x=n,c,y;
do
{
c=0;
x=SumOfDigit(x);
y=x;
while(y!=0)
{
y=y/10;
c++;
}
}
while(c!=1);
if(x==1)
{
System.out.println("No. is magic");
}
else
System.out.println("No. is not magic");
}
}

Happy Number

A happy number is a number in which the eventual sum of the square of the digits of the number is equal to 1.
Example:



Hence, 28 is a happy number.

import java.io.*;
class Happy
{
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n;
Happy()
{
n=0;
}
void getnum(int nn)
{
n=nn;
}
int sum_sq_digits(int x)
{
if(x==0)
return 0;
else
{
int d=x%10;
return (d*d+ sum_sq_digits(x/10));
}
}
void ishappy()
{
int a=sum_sq_digits(n);
while(a>9)
{
a=sum_sq_digits(a);
}
if(a==1)
System.out.print(n+" is a Happy Number");
else
System.out.print(n+" is Not a Happy Number");
}
public static void main()throws IOException
{
Happy ob=new Happy();
System.out.print("Enter any number: ");
int b=Integer.parseInt(br.readLine());
ob.getnum(b);
ob.ishappy();
}
}


Reversing a String using recursion

import java.io.*;
class RevString
{
String str;
String revstr;
RevString()
{
str="";
revstr="";
}
void getstr()throws IOException
{
BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string");
str=x.readLine();
}
void recReverse(int i)
{
if(i==0)
return;
else
{
revstr=revstr+str.charAt(i-1);
recReverse(i-1);
}
}
void check()
{
System.out.println("Original string-"+str);
recReverse(str.length());
System.out.println("Reverse string-"+revstr);
if(str.equals(revstr))
{
System.out.println("Word is Palindrome");
}
else
{
System.out.println("Word is not Palindrome");
}
}
public static void main (String[] args)throws IOException
{
RevString call=new RevString();
call.getstr();
call.check();
    }
}

Sunday, 20 October 2013

Perfect number

A perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors. The first perfect number is 6, because 1, 2 and 3 are its proper positive divisors, and 1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 = 6.

public class IsPerfectNumber
 { 
public boolean isPerfectNumber(int number)
{
 int temp = 0;
 for(int i=1;i<=number/2;i++)
{
 if(number%i == 0)
{ temp += i; }
 }
 if(temp == number)
{ System.out.println("It is a perfect number"); 
return true; }
 else
 { 
System.out.println("It is not a perfect number");
 return false; 
}
 }
 public static void main(String a[])
IsPerfectNumber ipn = new IsPerfectNumber()
; System.out.println("Is perfect number: "+ipn.isPerfectNumber(28));
 } 
}

Inheritance program

A class Iscscores defines the scores of a candidate in six subjects and another class bestfour defines
the best four subjects.
The details of both the classes are given below:-

Class name : Iscscores
Data members
number[6][2] : int array to store marks of 6 subjects and subject code.
Member functions
Iscscores() : constructor to accept the marks
int point() : to return the point in each subject according to the
following:
Marks>=90 1 point
80-89 2 points
70-79 3 points
60-69 4 points
50-59 5 points
40-49 6 points
---------------------------------accordingly
Class name : bestfour
Member functions
void bestsubjects() : to display the total points and best four subject codes using
the concept of inheritance.
Specify the class details of both the classes using the concept of inheritance.


import java.io.*;
class Iscscores
{
   int number[][];
   int k;
   BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
   Iscscores()
   {
       number=new int [6][2];
       k=0;
   }
   void input()throws IOException
   {
       for(int i=0;i<6;i++)
       {
           System.out.print("Enter Subject Code: ");
           number[i][0]=Integer.parseInt(x.readLine());
           System.out.print("Enter marks of Subject: ");
           number[i][1]=Integer.parseInt(x.readLine());
        }
    }
   int point()
   {
       int n=number[k][1];
       if(n>=90)
       return 1;
       else if (n>=80)
       return 2;
       else if (n>=70)
       return 3;
       else if (n>=60)
       return 4;
       else if (n>=50)
       return 5;
       else if (n>=40)
       return 6;
       else if (n>=30)
       return 7;
       else if (n>=20)
       return 8;
       else
       return 9;
    }
}

class BestFour extends Iscscores
{
    void bestsubject()
    {
        int l=number[0][1],s=number[0][1];
        int pt=0,code,j=0,c=0;
        //total points and lowest marks
        for(int i=0;i<6;i++)
        {
            k=i;
            System.out.println("Subject Code="+number[i][0]+"\tMarks="+number[i][1]+"\tPoints="+point());
            pt=pt+point();
            if(s>number[i][1])
            s=number[i][1];
        }
        System.out.println("Total Points="+pt);
        System.out.println("Best 4 subjects");
        do
        {
            for(int i=0;i<6;i++)
            {
                if(l<number[i][1])
                {
                    l=number[i][1];
                    code=number[i][0];
                    j=i;
                }
            }
            System.out.println("Code="+number[j][0]);
            l=s-1;number[j][1]=s-1;
            ++c;
        }
        while(c!=4);
    }
}