Python,C,C++ and JAVA programs for CBSE, ISC, B.Tech and I.T Computer Science and MCA students

The Programming Project: April 2014

Sunday, April 20, 2014

Pascal trialngle



CODE

import java.io.*;
import java.util.*;
public class Pascal {
    public static void main(String[] args) {
        int rows;
        Stack<Integer> s1 = new Stack<Integer>();
        Stack<Integer> s2 = new Stack<Integer>();
        s1.push(1);
        s1.push(1);
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the number of rows:");
        rows = in.nextInt();
        System.out.println("Pascal Traingle:");
        for(int i = 1; i <= rows; i++) {
            if(i==1 || i==2) {
                if(i==1)
                    System.out.println("1");
                else {
                    System.out.println();
                    System.out.println("1  1");
                    }
                }
            else {
            System.out.println();
            int p = s1.pop();
            System.out.print(p+" ");
            s2.push(p);
            while(s1.empty() == false) {
                    int q = s1.pop();
                    int next = p+q;
                    System.out.print(next+" ");
                    s2.push(next);
                    p = q;
                    }
            System.out.println(" 1 ");
            s2.push(1);
            while(s2.empty() == false) {
                    s1.push(s2.pop());
                    }
                }
            } // end of i loop
        }
    }

Saturday, April 19, 2014

Longest increasing subsequence (LIS)


Longest increasing subsequence (LIS) problem is to find the length of longest subsequnce out of a given sequnce such that all the element of the subsequence is sorted in strictly increasing order of their value.

INPUT SPECIFICATION
An array (may be unsorted)
OUTPUT SPECIFICATION:
Length of LIS

Examples:

Input Array 10,22,9,33,21,50,41,60,80
Length of LIS is 6 & LIS is 10,22,33,50,60,80

Input Array 1,2,3,4,5,6,7,8,7,6,5,4,5,6,7,8,9,10,11
Length of LIS is 11 & LIS is 1,2,3,4,5,6,7,8,9,10,11



 import java.io.*;
import java.util.*;
public class ArraySubsequence {
    public static void main(String[] args) {
        int n;
        int[] arr;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the size of the array:");
        n = in.nextInt();
        arr = new int[n];
        System.out.println("Enter the elements of the array:");
        for(int i = 0; i < n; i++)
            arr[i] = in.nextInt();
        LIS ls = new LIS();
        ls.lisGenerate(arr);
        }
    }

class LIS {
    public void lisGenerate(int[] seq) {
        int[]L=new int[seq.length];
            L[0]=1;
            for(int i=1;i<L.length;i++) {
                  int maxn=0;
                   for(int j=0;j<i;j++){
                    if(seq[j]<seq[i]&&L[j]>maxn){
                          maxn=L[j];
                        }
                      }
                  L[i]=maxn+1;
            }
            int maxi=0;
            for(int i=0;i<L.length;i++) {
                  if(L[i]>maxi) {
                    maxi=L[i];
                     }
              }
        System.out.println(maxi);
        }
    }
   

Friday, April 18, 2014

Fibonacci Series in Python

#File: Fibonacci.py
#A simple program to generate Fibonacci series

def main():
    print "Fibonacci Series"
    n = input("Enter the value of n, number of terms:")
    x = n
    def fibo(n):
        if n == 0 or n == 1:
            return 1           
        else:
            return fibo(n-1)+fibo(n-2)
           
    for i in range(x+1):
        print fibo(i)   
main()

Thursday, April 17, 2014

Binomial Coefficient using recursion in Python and C language





Post by Maths.


C Code
#include<stdio.h>
long int Binomial(long int, long int);
int main()
    {
    long int n,k;
    printf("\n Enter the value of n and k, n is greater than k:");
    scanf("%ld %ld",&n,&k);
    while( k < 0 || n < 1 || k > n) {
        printf("\n Wrong input, enter again:");
        scanf("%ld %ld",&n,&k);
        }
    printf("\n Value of %ldC%ld: %ld \n", n,k,Binomial(n,k));
    return 0;
    }
long int Binomial(long int n, long int k)
    {
    return (k <= 1 ? (k == 0 ? 1 : n) : (n*Binomial(n-1,k-1))/k);
    } 


Python Code
 
#File: binomial.py
#A simple program to calculate nCk using recursion
def main():
    print "Binomial Coefficient"
    n = input("Enter the value of n:")
    k = input("Enter the value of k:")
    x,y= n,k
    def binomial(n,k):
        if k < 2:
            if k == 1:
                return n
            else:
                return 1
        else:
            return (n*binomial(n-1,k-1))/k
   
    print "Value of nCk is",binomial(x,y)
   
main()


OUTPUT:

administrator@ubuntu:~/python$ python
Python 2.7.4 (default, Sep 26 2013, 03:20:26)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import binomial
Binomial Coefficient
Enter the value of n:1200
Enter the value of k:600
Value of nCk is 396509646226102014036716014862605729531608195706791651137874888645453416610941265150218719101931467943643355545203450497992759241509133380338379948816055787676920090991204851973167965845932778899299658455186568000803781988756668261491937388063732393433822461878746138860879613812823280622769290795808335597761702284943981759657834318699226167559487050708295600
>>>

/* To calculate the Binomial Coeffcient using recursion */
/* We have use the formula nCk = (n/k)*{(n-1)C(k-1)} */

Wednesday, April 16, 2014

Kaprekar's Number in JAVA: ISC Computer Science Practicals 2010


Post by Maths.


Given the two positive integers p and q, where p < q. Write a program to determine how
many kaprekar numbers are there in the range between 'p' and 'q'(both inclusive) and
output them.
About 'kaprekar' number:

SAMPLE DATA:

INPUT:
p=1
Q=1000

OUTPUT:

THE KAPREKAR NUMBERS ARE:
1, 9, 45, 55, 99, 297, 703, 999
FREQUENCY OF KAPREKAR NUMBERS IS:8

/* ISC COMPUTER SCIENCE PRACTICALS SOLVED, 2010 */

Tuesday, April 15, 2014

ISC COMPUTER SCIENCE PRACTICALS, 2013


/*
Write a program to declare a square matrix A[][] of order (M X M) where 'M'
is the number of rows and the number of columns such that M must be greater
than 2 and less than 20. Allow the user to input integers into this matrix.
Display appropriate error message for an invalid input.
Perform the following tasks:
(a) Display the input matrix.
(b) Create a mirror image of the inputted matrix.
(c) Display the mirror image matrix.
Test your program for the following data and some random data:
Example 1
INPUT : M = 3
4 16 12
8 2 14
6 1 3
OUTPUT :
ORIGINAL MATRIX
4 16 12
8 2 14
6 1 3
MIRROR IMAGE MATRIX
12 16 4
14 2 8
3 1 6
Example 2
INPUT : M = 22
OUTPUT : SIZE OUT OF RANGE
*/
/* ISC COMPUTER SCIENCE PRACTICALS, 2013 */

ISC Computer Science Practicals, 2012


/* A prime palindrome integer is a positive integer (without leading zeros) which is prime as well as a palindrome.
Given two positive integers m and n, where m < n, write a program to determine how many prime-palindrome integers
are there in the range between m and n (both inclusive) and output them.
The input contains two positive integers m and n where m < 3000 and n < 3000.
Display the number of prime palindrome integers in the specified range along with their values in the format specified below:

Test your program with the sample data and some random data:

Example 1:
INPUT: m=100
N=1000

OUTPUT: The prime palindrome integers are:
101,131,151,181,191,313,351,373,383,727,757,787,797,919,929
Frequency of prime palindrome integers: 15

Example 2:
M=100
N=5000

OUTPUT: Out of range */

/* ISC COMPUTER SCIENCE PRACTICALS,2012 Solved */

CODE


Tags: ISC, Computer Science, Practicals, 2012, Prime, String.valueOf(), Palindrome, Integer to String, Prime Palindrome

Monday, April 14, 2014

ISC Computer Science Practicals Solved, 2011


/*
Encryption is a technique of coding messages to maintain their secrecy.
A String array of size 'n' where 'n' is greater than 1 and less than 10,
stores single sentences (each sentence ends with a full stop) in each row of the array.
Write a program to accept the size of the array.
Display an appropriate message if the size is not satisfying the given condition.
Define a string array of the inputted size and fill it with sentences row-wise.
Change the sentence of the odd rows with an encryption of two characters ahead of the original character. Also change the sentence of the even rows by storing the sentence in reverse order.
Display the encrypted sentences as per the sample data given below.
Test your program on the sample data and some random data.
Input: n=4
IT IS CLOUDY. IT MAY RAIN. THE WEATHER IS FINE. IT IS COOL.
Output: KV KU ENQWFA. RAIN MAY IT. VJG YGCVJGT KU HKPG. COOL IS IT.
Input: n=13
Output: INVALID ENTRY
*/
/* ISC Computer Science Practicals, 2011 */ 

Saturday, April 12, 2014

ISC Computer Science Practicals Solved, 2013


/*
A palindrome is a word that may be read the same way in either direction.
Accept a sentence in UPPER CASE which is terminated by either ".", "?", or "!".
Each word of the sentence is separated by a single blank space.
Perform the following taks:
(a) display the count of palindromic words in the sentence.
(b) Display the palindromic words in the sentence.
Example of palindromic words:
MADAM, ARORA, NOON
Test your program with the sample data and some random data:
Example 1
INPUT : MOM AND DAD ARE COMING AT NOON
OUTPUT : MOM DAD NOON
NUMBER OF PALINDROMIC WORDS : 3
Example 2
INPUT : HOW ARE YOU?
OUTPUT : NO PALINDROMIC WORDS
*/
/* ISC COMPUTER SCIENCE PRACTICAL,2013 */ 

ISC Computer Science Practical Paper-2013

COMPUTER SCIENCE
Paper – 2
(PRACTICAL)
(Reading Time: 15 minutes)
 (Planning Session AND Examination Session: Three Hours)
————————————————————————————————————
The total time to be spent on the Planning and the Examination Session is Three hours.
After completing the Planning Session, the candidate may begin with the Examination Session.
A maximum of 90 minutes is permitted to begin the Examination Session.
(Maximum Marks: 80)
————————————————————————————————————
As it is a practical examination the candidate is expected to do the following:
  1. Write an algorithm for the selected problem. Algorithm should be expressed clearly using ay standard scheme such as pseudo code or in steps which are simple enough to be obviously computable.  [10]
  2. Write a program in JAVA language. The program should follow the algorithm and should be logically and syntactically correct. [20]
  3. Document the program using mnemonic names / comments, identifying and clearly describing the choice of data types and meaning of variables. [20]
  4. Code / Type the program on the computer and get a printout (hard copy). Typically this should be a program that compiles and runs correctly. [10]
  5. Test run the program on the computer using the given sample data and get a printout of the output in the format specified in the problem. [20]
  6. Viva-Voce on the Selected Problem.   [20]
Solve any one of the following Problems:
 Question 1.
An ISBN (International Standard Book Number) is a ten digit code which uniquely identifies a book.
The first nine digits represent the group, publisher and title of the book and the last digit is used to check whether ISBN is correct or not.
Each of the first nine digits of the code can take a value between 0 to 9. Sometimes it is necessary to make the last digit equal to ten. This is done by writing the last digit of the code as X.
To verify an ISBN, calculate 10 times the first digit, plus 9 times the second digit, plus 8 times the third digit and so on until we add 1 time the last digit. If the final number leaves no remainder while divided by 11, the code is a valid ISBN
For example:
0201103311=10*0+9*2+8*0+7*1+6*1+5*0+4*3+3*3+2*1+1*1=55
This is a valid ISBN
007462542X=10*0+9*0+8*7+7*4+6*6+5*2+4*5+3*4+2*2+1*10=176
This is a valid ISBN
Similarly 0112112425 is not a valid ISBN.
 Test Data:
Input code: 0201530821
Output: Sum=99
Leaves no remainder – valid ISBN
Input code: 356680324
Output: Sum=invalid input
Input code: 0231428031
Output: Sum=122
Leaves remainder – invalid ISBN
Question 2:
Write a program to declare a square matrix A[][] of order (MXN) where ‘M’ is the number of rows and the number of columns. ‘M’ should be greater than 2 and less than 20. Allow user to enter integers into this matrix. Display appropriate error message for an invalid input. Perform the following tasks.
1.    Display the input matrix
2.    Create a mirror image of the inputted matrix.
3.    Display the mirror image matrix
Test Data:
Input: M=3
4  16  12
8   2  14
6   1   3
Output:
Original matrix
4  16  12
8   2  14
6   1   3
Mirror image matrix:
12  16  4
14  2    8
3   1    6
Input: M=22
Output: Size out of range
Question 3:
A palindrome is a word that may be read the same in either direction.
Accept a sentence in upper case which is terminated by either ‘.’  ,  ’,’  ,  ‘? ’ ,  ‘!’. Each word in the sentence is separated by a blank space.
Perform the following tasks:
Test Data:
Input: MOM AND DAD ARE COMING AT NOON.
Output: MOM DAD NOON
Number of palindromic words: 3
Input: HOW ARE YOU?
Output: No palindromic words

ISC Computer Science Practicals, 2012 Solved


/*
Write a program to accept a sentence as input. The words in the string are to be separated by a blank.
Each word must be in upper case. The sentence is terminated by either '.','!' or '?'.
Perform the following tasks:
1. Obtain the length of the sentence (measured in words)
2. Arrange the sentence in alphabetical order of the words.
Test your program with the sample data and some random data:
Example 1:
INPUT: NECESSITY IS THE MOTHER OF INVENTION.
OUTPUT:
Length: 6
Rearranged Sentence:
INVENTION IS MOTHER NECESSITY OF THE
Example 2:
INPUT: BE GOOD TO OTHERS.
OUTPUT:
Length: 4
Rearranged Sentence: BE GOOD OTHERS TO
*/
// ISC Computer Science Practicals, 2012 


ISC Computer Science Practical Solved, 2011


/*Design a program which accepts your date of birth in dd mm yyyy format. Check whether the date entered is valid or not.
If it is valid, display "VALID DATE", also compute and display the day number of the year for the date of birth.
If it is invalid, display "INVALID DATE" and then terminate the program.
Testing of the program
Input: Enter your date of birth in dd mm yyyy format 05 01 2010
Output: VALID DATE 5
Input: Enter your date of birth in dd mm yyyy format 03 04 2010
Output: VALID DATE 93
Input: Enter your date of birth in dd mm yyyy format 34 06 2010
Output: INVALID DATE */
// ISC Computer Science 2011, Practicals

ISC Computer Science Practical Solved, 2010


/*
Input a paragraph containing 'n' number of sentences where (1<=n<=4). The words are to be separated with single blank space and are in upper case. A sentence may be terminated either with a full stop (.) or question mark (?). Perform the followings:

(i) Enter the number of sentences, if it exceeds the limit show a message.
(ii) Find the number of words in the paragraph
(iii) Display the words in ascending order with frequency.

Example 1:

INPUT:
Enter number of sentences:
1
Enter sentences:
TO BE OR NOT TO BE.

OUTPUT:
Total number of words: 6
WORD FREQUENCY
OR 1
NOT 1
TO 2
BE 2


Example 2:

INPUT: Enter number of sentences:
3
Enter sentences:
THIS IS A STRING PROGRAM. IS THIS EASY? YES, IT IS.

OUTPUT:
Total number of words: 11
WORD FREQUENCY
A                       1
STRING            1
PROGRAM        1
EASY                1
YES                  1
IT                      1
THIS                 2
IS                      3
*/

Friday, April 11, 2014

ISC Computer Science Practical 2013


An ISBN ( International Stanadar Book Number) is a ten digit code which uniquely identifies a book. The first nine digits represent the Group, Publisher and Title of the book and the last digit is used to check whehter ISBN is correct or not. Each of the first nine digits of the code can take a value between 0 and 9. Sometimes it is necessary to make the last digit equal to ten; this is done by writing the last digit of the code as X. To verify an ISBN, calculate 10 times the first digit, plus 9 times the second digit, plus 8 times the third and so on until we add 1 time the last digit. If the final number leaves no remainder when divided by 11, the code is a valid ISBN. 


For example:
Example 1
INPUT CODE : 0201530821
OUTPUT : SUM = 99
LEAVES NO REMAINDER - VALID ISBN CODE
Example 2
INPUT CODE : 035680324
OUTPUT : INVALID INPUT
Example 1
INPUT CODE : 0231428031
OUTPUT : SUM = 122
LEAVES REMAINDER - INVALID ISBN CODE
ISC 2013 ~ Computer Science Practicals  

Sorting using Stacks

This program implements the Collection Framework classes Stack a subclass of class Vector to sort a intial array using two stacks and their standard operations viz., push(), pop(), peek() and empty().

Thursday, April 10, 2014

Rational Numbers representation Using classes and structures


Basic operations on Rational Numbers using C, C++ and Java.
The same program is written in the above languages, helping you to grasp the basic principles of classes and objects in C++ and Java. Students moving from C++ to Java will be able to relate the similarities at the same time the major differences between them.

Code in C
#include<stdio.h>
#define TRUE 1
#define FALSE 0
typedef struct
{
int numerator;
int denominator;
} RATIONAL;
void multiply(RATIONAL *frst,RATIONAL *scnd);
void add(RATIONAL *frst,RATIONAL *scnd);
void subtract(RATIONAL *frst,RATIONAL *scnd);
int equality(RATIONAL *frst,RATIONAL *scnd);
void divide(RATIONAL *frst,RATIONAL *scnd);
void reduce(RATIONAL *rat);

int main()
{
RATIONAL x,y;
int choice;
printf("\n Enter the numerator and denominator of the first rational:");
scanf("%d %d",&x.numerator,&x.denominator);
printf("\n Enter the numerator and denominator of the second rational:");
scanf("%d %d",&y.numerator,&y.denominator);
//printf("\n Reduced form of the input rationals are:");
reduce(&x);
//printf("\n %d / %d ",x.numerator,x.denominator);
reduce(&y);
//printf("\n %d / %d ",y.numerator,y.denominator);
printf("\n Press 1 for addition:");
printf("\n Press 2 for subtraction:");
printf("\n Press 3 for multiplication:");
printf("\n Press 4 for divison:");
printf("\n Press 5 to check for equatilty");
printf("\n Enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
add(&x,&y);
break;
case 2:
subtract(&x,&y);
break;
case 3:
multiply(&x,&y);
break;
case 4:
divide(&x,&y);
break;
case 5:
equality(&x,&y)==TRUE ? printf("\n They are equal:\n") : printf("\n They are unequal:\n");
break;
default:
break;
}
return 0;
}
void divide(RATIONAL *frst,RATIONAL *scnd)
{
RATIONAL sum;
sum.numerator = (frst->numerator)*(scnd->denominator);
sum.denominator = (frst->denominator)*(scnd->numerator);
reduce(&sum);
printf("\n After dividing the new rational is: %d / %d \n",sum.numerator,sum.denominator);
}
void multiply(RATIONAL *frst,RATIONAL *scnd)
{
RATIONAL sum;
sum.numerator = (frst->numerator)*(scnd->numerator);
sum.denominator = (frst->denominator)*(scnd->denominator);
reduce(&sum);
printf("\n Product of the rationals is: %d / %d \n",sum.numerator,sum.denominator);
}
int equality(RATIONAL *frst,RATIONAL *scnd)
{
return ( (frst->numerator == scnd->numerator && frst->denominator == scnd->denominator) ? TRUE : FALSE );
}
void subtract(RATIONAL *frst,RATIONAL *scnd)
{
int lcm=1,i;
for(i=1;;i++)
{
if (frst->denominator % i == 0 && scnd->denominator % i== 0)
break;
}
lcm = ((frst->denominator)*(scnd->denominator))/i;
RATIONAL sum;
sum.numerator = (frst->numerator)*(lcm/frst->denominator)-(scnd->numerator)*(lcm/scnd->denominator);
sum.denominator = lcm;
reduce(&sum);
printf("\n Sum of the rationals is: %d / %d \n",sum.numerator,sum.denominator);
}
void add(RATIONAL *frst,RATIONAL *scnd)
{
int lcm=1,i;
for(i=1;;i++)
{
if (frst->denominator % i == 0 && scnd->denominator % i== 0)
break;
}
lcm = ((frst->denominator)*(scnd->denominator))/i;
RATIONAL sum;
sum.numerator = (frst->numerator)*(lcm/frst->denominator)+ (scnd->numerator)*(lcm/scnd->denominator);
sum.denominator = lcm;
reduce(&sum);
printf("\n Sum of the rationals is: %d / %d \n",sum.numerator,sum.denominator);
}
void reduce(RATIONAL *rat)
{
int a,b,rem;
if(rat->numerator > rat->denominator) {
a = rat->numerator;
b = rat->denominator;
}
else {
a = rat->denominator;
b = rat->numerator;
}
while(b!=0) {
rem = a%b;
a = b;
b = rem;
}
rat->numerator /= a;
rat->denominator /= a;
}



Code in C++

#include<iostream>
using namespace std;
#define TRUE 1
#define FALSE 0
class Rational {
private:
int numerator;
int denominator;
public:
Rational() { numerator = 1; denominator = 1;}
void setValues()
{
cout<<"\n Enter the numerator:";
cin>>numerator;
cout<<"\n Enter the denominator:";
cin>>denominator;
}
void dispValue()
{
cout<<"\n"<<numerator<<"/"<<denominator<<"\n";
}
void reduce();
void add(Rational r);
void subtract(Rational r);
void multiply(Rational r);
void divide(Rational r);
int equality(Rational r);
};
int Rational::equality(Rational r)
{
return ( (numerator == r.numerator && denominator == r.denominator) ? TRUE : FALSE );
}
void Rational::divide(Rational r)
{
Rational sum;
sum.numerator = (numerator)*(r.denominator);
sum.denominator = (denominator)*(r.numerator);
sum.reduce();
cout<<"\n On divison the rationals:";
sum.dispValue();
}
void Rational::multiply(Rational r)
{
Rational sum;
sum.numerator = (numerator)*(r.numerator);
sum.denominator = (denominator)*(r.denominator);
sum.reduce();
cout<<"\n Product of the rationals is:";
sum.dispValue();
}
void Rational::subtract(Rational r)
{
int lcm=1,i;
for(i=1;;i++)
{
if (denominator % i == 0 && r.denominator % i== 0)
break;
}
lcm = ((denominator)*(r.denominator))/i;
Rational sum;
sum.numerator = numerator*(lcm/denominator)-(r.numerator)*(lcm/r.denominator);
sum.denominator = lcm;
sum.reduce();
cout<<"\n Difference of the rationals is:";
sum.dispValue();
}
void Rational::add(Rational r)
{
int lcm=1,i;
for(i=1;;i++)
{
if (denominator % i == 0 && r.denominator % i== 0)
break;
}
lcm = ((denominator)*(r.denominator))/i;
Rational sum;
sum.numerator = numerator*(lcm/denominator)+(r.numerator)*(lcm/r.denominator);
sum.denominator = lcm;
sum.reduce();
cout<<"\n Sum of the rationals is:";
sum.dispValue();
}
void Rational::reduce()
{
int a,b,rem;
if(numerator > denominator) {
a = numerator;
b = denominator;
}
else {
a = denominator;
b = numerator;
}
while(b!=0) {
rem = a%b;
a = b;
b = rem;
}
numerator /= a;
denominator /= a;
}
int main()
{
int choice;
Rational x,y;
x.setValues();
y.setValues();
x.reduce();
y.reduce();
cout<<"\n Press 1 for addition:";
cout<<"\n Press 2 for subtraction:";
cout<<"\n Press 3 for multiplication:";
cout<<"\n Press 4 for divison:";
cout<<"\n Press 5 to check for equatilty";
cout<<"\n Enter your choice:";
cin>>choice;
switch(choice)
{
case 1:
x.add(y);
break;
case 2:
x.subtract(y);
break;
case 3:
x.multiply(y);
break;
case 4:
x.divide(y);
break;
case 5:
x.equality(y)==TRUE ? cout<<"\n They are equal:\n" : cout<<"\n They are unequal:\n";
break;
default:
break;
}
return 0;
}


Code in JAVA

import java.util.*;
public class Rational
{
public static void main(String[] args)
{
int choice;
Scanner in = new Scanner(System.in);
OperationRational x = new OperationRational();
OperationRational y = new OperationRational();
x.setValues();
y.setValues();
x.reduce();
y.reduce();
System.out.println("You have entered the following rationals:");
x.dispValue();
y.dispValue();
System.out.println("Press 1 for addition:");
System.out.println("Press 2 for subtraction:");
System.out.println("Press 3 for multiplication:");
System.out.println("Press 4 for divison:");
System.out.println("Press 5 to check for equatilty");
System.out.println("Enter your choice:");
choice = in.nextInt();
switch(choice)
{
case 1:
x.add(y);
break;
case 2:
x.subtract(y);
break;
case 3:
x.multiply(y);
break;
case 4:
x.divide(y);
break;
case 5:
if (x.equality(y) == true)
System.out.println("They are equal:");
else
System.out.println("They are unequal:");
break;
default:
break;
}
}
}
class OperationRational
{
OperationRational()
{
numerator = 1;
denominator = 1;
}
public void setValues()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the numerator:");
numerator = in.nextInt();
System.out.println("Enter the denominator:");
denominator = in.nextInt();
}
public void dispValue()
{
System.out.println(numerator+"/"+denominator);
}
public void reduce()
{
int a,b,rem;
if(numerator > denominator) {
a = numerator;
b = denominator;
}
else {
a = denominator;
b = numerator;
}
while(b!=0) {
rem = a%b;
a = b;
b = rem;
}
numerator /= a;
denominator /= a;
}
public void add(OperationRational r)
{
int lcm=1,i;
for(i=1;;i++)
{
if (denominator % i == 0 && r.denominator % i== 0)
break;
}
lcm = ((denominator)*(r.denominator))/i;
OperationRational sum = new OperationRational();
sum.numerator = numerator*(lcm/denominator)+(r.numerator)*(lcm/r.denominator);
sum.denominator = lcm;
sum.reduce();
System.out.println("Sum of the rationals is:");
sum.dispValue();
}
public void subtract(OperationRational r)
{
int lcm=1,i;
for(i=1;;i++)
{
if (denominator % i == 0 && r.denominator % i== 0)
break;
}
lcm = ((denominator)*(r.denominator))/i;
OperationRational sum = new OperationRational();
sum.numerator = numerator*(lcm/denominator)-(r.numerator)*(lcm/r.denominator);
sum.denominator = lcm;
sum.reduce();
System.out.println("Difference of the rationals is:");
sum.dispValue();
}
public void multiply(OperationRational r)
{
OperationRational sum = new OperationRational();;
sum.numerator = (numerator)*(r.numerator);
sum.denominator = (denominator)*(r.denominator);
sum.reduce();
System.out.println("Product of the rationals is:");
sum.dispValue();
}
public void divide(OperationRational r)
{
OperationRational sum = new OperationRational();;
sum.numerator = (numerator)*(r.denominator);
sum.denominator = (denominator)*(r.numerator);
sum.reduce();
System.out.println("On divison the rationals:");
sum.dispValue();
}
public boolean equality(OperationRational r)
{
return ( (numerator == r.numerator && denominator == r.denominator) ? true : false );
}
private int numerator;
private int denominator;
}

Get the pdf file, click here