w3resource

C++ Exercises: Check whether a number is positive, negative or zero

C++ Basic: Exercise-32 with Solution

Write a program in C++ to check whether a number is positive, negative or zero.

Visual Presentation:

C++ Exercises: Check whether a number is positive, negative or zero

Sample Solution:

C++ Code :

#include <iostream> // Including input-output stream header file

using namespace std; // Using the standard namespace

int main() // Start of the main function
{
    signed long num1 = 0; // Declaring and initializing a signed long variable num1 to zero

    cout << "\n\n Check whether a number is positive, negative or zero :\n"; // Outputting a message indicating the purpose of the program
    cout << "-----------------------------------------------------------\n"; // Outputting a separator line

    cout << " Input a number : "; // Prompting the user to input a number
    cin >> num1; // Taking input for the variable num1 from the user

    if (num1 > 0) // Checking if the entered number is greater than zero
    {
        cout << " The entered number is positive.\n\n"; // Outputting a message if the number is positive
    }
    else if (num1 < 0) // Checking if the entered number is less than zero
    {
        cout << " The entered number is negative.\n\n"; // Outputting a message if the number is negative
    }
    else // Handling the case where the entered number is zero
    {
        std::cout << " The number is zero.\n\n"; // Outputting a message if the number is zero
    }

    return 0; // Returning 0 to indicate successful program execution
} // End of the main function

Sample Output:

 Check whether a number is positive, negative or zero :                
-----------------------------------------------------------            
 Input a number : 8                                                    
 The entered number is positive.    

Flowchart:

Flowchart: Check whether a number is positive, negative or zero

C++ Code Editor:

Previous: Write a program in C++ to input a single digit number and print a rectangular form of 4 columns and 6 rows.
Next: Write a program in C++ to divide two numbers and print on the screen.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/cpp-exercises/basic/cpp-basic-exercise-32.php