C++ Program - Check whether a Number is Positive or Negative


Advertisements

A number is said to be positive if it is greater than zero and it is said to be negative if it is less than zero. A number can be checked for zero, positive and negative using if, if-else, nested if-else and short-hand if-else statements.

Example: Using If statement

In the below example, only if conditional statements are used.

#include <iostream>
using namespace std;

static void CheckNumber(double);

static void CheckNumber(double x) {
  string message;
  if (x > 0)
    {message = "Positive number";}
  if (x == 0)
    {message = "Zero";}
  if (x < 0)
    {message = "Negative number";}
  cout<<message<<"\n";
}

int main() {
  CheckNumber(5.5);
  CheckNumber(-10.8);
  return 0;
}

Output

Positive number
Negative number

Example: Using If-else statement

It can also be checked using If-else conditional statements.

#include <iostream>
using namespace std;

static void CheckNumber(double);

static void CheckNumber(double x) {
  string message;
  if (x > 0)
    {message = "Positive number";}
  else if (x == 0)
    {message = "Zero";}
  else
    {message = "Negative number";}
  cout<<message<<"\n";
}

int main() {
  CheckNumber(5.5);
  CheckNumber(-10.8);
  return 0;
}

Output

Positive number
Negative number

Example: Using Nested If-else statement

The above problem can also be solved using nested if-else conditional statements.

#include <iostream>
using namespace std;

static void CheckNumber(double);

static void CheckNumber(double x) {
  string message;
  if (x >= 0)
    {
      if (x > 0)
        {message = "Positive number";}
      else
        {message = "Zero";}
    }
  else
    {message = "Negative number";}
  cout<<message<<"\n";
}

int main() {
  CheckNumber(5.5);
  CheckNumber(-10.8);
  return 0;
}

Output

Positive number
Negative number

Example: Using Ternary Operator

Ternary operator can also be used here.

#include <iostream>
using namespace std;

static void CheckNumber(double);

static void CheckNumber(double x) {
  string message;
  message = (x > 0)? "Positive number" : (x == 0)? "Zero" : "Negative number";
  cout<<message<<"\n";
}

int main() {
  CheckNumber(5.5);
  CheckNumber(-10.8);
  return 0;
}

Output

Positive number
Negative number



Recommended Pages


Advertisements