Without using Math Functions and String's replace functions, write a program in Java that returns the absolute of a number input. The program continuously runs until user enters "exit()".
_
Good Luck !!
Thanks in advance.
Share
Without using Math Functions and String's replace functions, write a program in Java that returns the absolute of a number input. The program continuously runs until user enters "exit()".
_
Good Luck !!
Thanks in advance.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Verified answer
[tex]\textsf{\large{\underline{Solution}:}}[/tex]
The given problem is solved using language - Java.
import java.util.Scanner;
public class ABS{
public static void main(String s[]){
String str="";
Scanner sc=new Scanner(System.in);
while(!str.equals("exit()")){
System.out.print("Enter a number: ");
int n=sc.nextInt();
if (n<0)
n=-n;
System.out.println("Absolute value of the number is: "+n);
System.out.print("Type exit() to exit or any other value to continue: ");
str=sc.next().toLowerCase();
}
System.out.println("Program Terminated.");
}
}
[tex]\textsf{\large{\underline{Explanation}:}}[/tex]
In this problem, we have to calculate the absolute value of integer number without using abs() function. This means we cannot use the basic function for calculation.
Absolute value is defined as:
[tex]\rm\implies |x| = \begin{cases}\rm x\ if\ x\geq0\\ \rm -x\ if\ x<0\end{cases}[/tex]
Therefore, we can negate the number if its less than 0 to calculate its absolute value.
[tex]\textsf{\large{\underline{Sample I/O}:}}[/tex]
Enter a number: -5
Absolute value of the number is: 5
Type exit() to exit or any other value to continue: x
Enter a number: 9
Absolute value of the number is: 9
Type exit() to exit or any other value to continue: exit()
Program Terminated.