C++ Program to Check Number is Positive or Negative or Zero

In this post, we will write a C++ program to check whether the given number is positive or negative or zero. We will develop this program in three ways, using if-else, using switch case, and using the function. First, let us develop a C++ program using the if-else statement.

#include<iostream>
using namespace std;
int main()
{
  // declare variable
  double number;

  // take input
  cout << "Enter a Number : ";
  cin >> number;

  // check
  if (number > 0)
    cout << "Positive" << endl;
  else if(number < 0)
    cout << "Negative" << endl;
  else
    cout << "Zero" << endl;
    
  return 0;
}

Output at different test-cases:-

Enter a Number : 20
Positive

Enter a Number : -9
Negative

Enter a Number : 0
Zero

C++ Program to Check Whether a Number is Positive or Negative or Zero Using Function

Now, let us develop the same program using the function. A function is a block of code that performs a specific task. Every program must have at least one function with the name main. The execution of the program always starts from the main function and ends with the main function. The main function can call other functions to do some special task.

#include<iostream>
using namespace std;

// function declaration
void check(double);

// main function
int main()
{
  // declare variable
  double number;

  // take input
  cout << "Enter a Number : ";
  cin >> number;

  // check number
  check(number);
  
  return 0;
}

// function to check number 
void check(double number) 
{
  if (number > 0)
    cout << "Positive" << endl;
  else if(number < 0)
    cout << "Negative" << endl;
  else
    cout << "Zero" << endl;
}

C++ Program to Check Whether a Number is Positive or Negative or Zero Using Switch

#include<iostream>
using namespace std;
int main()
{
  // declare variable
  double number;

  // take input
  cout << "Enter a Number : ";
  cin >> number;

  // check
  switch(number > 0)
  {
      // positive number
      case 1 :
         cout << "Positive" << endl;
         break;
      // number is zero or negative
      case 0 :
        switch(number < 0)
        {
            // number is negative
            case 1 :
               cout << "Negative" << endl;
               break;
            // number is zero
            case 0 :
               cout << "Zero" << endl;
               break;
        }
        break;
  }
  
  return 0;
}

Output:-

Enter a Number : 10
Positive

Enter a Number : 0
Zero

Enter a Number : -251
Negative

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Learn More C++ Programming Examples,

Leave a Reply