In this program, we will learn how to check if the number is positive or negative using C++ Programming language.
This program asks the user to enter a number, then we will use an if-else statement to check whether the number is positive or negative.
So, without further ado, let’s begin this tutorial.
C++ Program to Check If the Number is Positive or Negative
// C++ Program to Check If the Number is Positive or Negative #include <iostream> using namespace std; int main(){ int num; // Asking for input cout << "Enter an integer: "; cin >> num; // Checking whether the number is positive or negative if (num > 0){ cout << num << " is a positive number." << endl; } else if (num == 0){ cout << num << " is equal to zero." << endl; } else { cout << num << " is a negative number." << endl; } return 0; }
Output 1
Enter an integer: 12
12 is a positive number.
Output 2
Enter an integer: -6
-6 is a negative number.
Output 3
Enter an integer: 0
0 is equal to zero.
How Does This Program Work ?
int num;
In this program, we have declared an integer data type variable named num.
// Asking for input cout << "Enter an integer: "; cin >> num;
Now, the user is asked to enter an integer. This number gets stored in the num named variable.
// Checking whether the number is positive or negative if (num > 0){ cout << num << " is a positive number." << endl; } else if (num == 0){ cout << num << " is equal to zero." << endl; } else { cout << num << " is a negative number." << endl; }
Now, we check whether the entered number is greater or smaller than zero.
- If num > 0, then the entered number is a positive integer.
- If num = 0, then the entered number is equal to zero.
- Otherwise if num < 0, then the entered number is negative.
Conclusion
I hope after going through this post, you understand how to check if the number is positive or negative using C++ Programming language.
If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to assist you.
Also Read: