Saturday 15 July 2017

Java Code to find the reciprocal of a number

Problem:

Design and implement an algorithm to compute the reciprocal of a number.

Solution:
package com.myprograms;

import java.util.Scanner;

public class Reciprocal {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter the number: ");
String n = s.nextLine();
System.out.println("the reciprocal of " + n + " is " + findTheReciprocal(n));
s.close();
}

public static String findTheReciprocal(String n){
String result = "";
if(n.contains("/")){
String[] strings = n.split("/");
result = strings[1] + "/" + strings[0];
}
else{
result = "1" + "/" + n;
}
return result;
}
}


Output:

enter the number:
3/4
the reciprocal of 3/4 is 4/3


enter the number: 
8
the reciprocal of 8 is 1/8


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...