Computer Science, asked by siddharthasingh15, 8 months ago

Java program to check whether the number is +ve or -ve without > & < sign?​

Answers

Answered by Vyomsingh
2

Question:-

Java program to check whether the number is +ve or -ve without > & < sign?

_____________________________

Logic used➛

By using Math.abs()

let number be -x(negative)

therefore if we add +x to this.

answer became 0.

Otherwise if number is +x(positive)

we add +x to this.

answer became 2x

_____________________________

Code➛

class Positive

{

public static void main (int n)

{

int m=Math.abs(n);//abs function will give absolute value

if(n+m==0)

{

System.out.println("Number is Negative");

}

else

{

System.out.println("Number is positive");

}

}

}

_____________________________

1st test:-

Input:-

-4

Output:-

Number is negative.

___________________________

2nd Test:-

Input:-

5

Output:-

Number is positive

Answered by anindyaadhikari13
2

\star\:\:\:\sf\large\underline\blue{Question:-}

  • Write a java program to check whether a number is positive or negative without > or < sign.

\star\:\:\:\sf\large\underline\blue{Approach:-}

import java.util.*;

class Program

{

public static void main(String s[])

{

Scanner sc = new Scanner(System.in);

System.out.print("Enter the number: ");

int n=sc.nextInt();

if(n==0)

System.out.println("Number is 0.");

else

{

n/=Math.abs(n);

if(n==1)

System.out.println("Number is positive. ");

else

System.out.println("Number is negative. ");

}

}

}

\star\:\:\:\sf\large\underline\blue{Logic:-}

Consider a number, say 2

Therefore, n=2

When n is divided by absolute value of n, result is 1

2/|2|=1 only.

So, we found that if the result is 1 then it is positive else it is negative.

Similarly,

Consider n=-5

Therefore

-5 / |-5|

=-5/5

=-1

So, it is a negative number.

For zero, we will simply check it by using == operator.

\star\:\:\:\sf\large\underline\blue{Output:-}

First run

Enter a number: 5

Number is positive.

Second run

Enter a number: -5

Number is negative.

Similar questions