Tuesday 2 October 2018

Checking whether a number is positive or negative in C++

Positive and negative numbers


Positive numbers are those numbers which have a plus sign(+) in front it. These numbers are greater(or bigger) than zero. A number written without any sign is also considered as a positive number. E.g: +7, 89, +22.145, 8.54 and so on.

Negative numbers are those numbers which have a minus sign(-) in front it. These numbers are smaller than zero. E.g: -1, -9.9, -3.145, -7.33333 and so on.
Zero(0) is neither a positive nor a negative number.

POSITIVE NUMBERS > 0 > NEGATIVE NUMBERS

Write a program in C++ to input a number from the user and check whether it is positive, negative or zero.


In this program, we input a number from the user. We compare it with zero(0). If the number is greater than 0, then we display it as a positive number. If it is smaller than 0, then we display it as a negative number. We check this conditions using if...else if...else statement and obtain our results. 


Program


#include<iostream.h>
#include<conio.h>
void main()
{
float a;
clrscr();
cout<<"Enter a number=";
cin>>a;
cout<<endl;
if(a>0)
           cout<<a<<" is a positive number"
else if(a<0)
           cout<<a<<" is a negative number";
else
           cout<<"You have entered zero";
getch();
}


Output


Program to check positive and negative numbers
CHECKING POSITIVE AND NEGATIVE NUMBERS







Explanation


In the above program, the user entered -7.33(i.e. a=-7.33). The value of a was compared with 0 and was found to be smaller than 0. The second condition in the if...else if...else statement was true. So, -7.33 is a negative number was displayed on the console screen.




No comments:

Post a Comment