In modern programming languages, we use both signed and unsigned numbers. For signed numbers, they can be positive, negative, or zero. To represent negative numbers, the system uses the 2's complement method to store numbers. In this article, we will discuss how to determine whether a given number is positive or negative in C.
Basic sign checking can be done by using if else conditions. The syntax of if-else condition is as follows -
if <condition> { perform action when condition is true } else { perform action when condition is false }
The algorithm for determining positive or negative numbers is as follows −
#include <iostream> using namespace std; string solve( int n ) { if( n < 0 ) { return "Negative"; } else { return "Positive"; } } int main() { cout << "The 10 is positive or negative? : " << solve( 10 ) << endl; cout << "The -24 is positive or negative? : " << solve( -24 ) << endl; cout << "The 18 is positive or negative? : " << solve( 18 ) << endl; cout << "The -80 is positive or negative? : " << solve( -80 ) << endl; }
The 10 is positive or negative? : Positive The -24 is positive or negative? : Negative The 18 is positive or negative? : Positive The -80 is positive or negative? : Negative
We can remove if-else conditions by using the ternary operator. The ternary operator uses two symbols ‘? 'and':'. The algorithm is similar. The syntax of the ternary operator is as follows −
<condition> ? <true case> : <false case>
#include <iostream> using namespace std; string solve( int n ) { string res; res = ( n < 0 ) ? "Negative" : "Positive"; return res; } int main() { cout << "The 56 is positive or negative? : " << solve( 56 ) << endl; cout << "The -98 is positive or negative? : " << solve( -98 ) << endl; cout << "The 45 is positive or negative? : " << solve( 45 ) << endl; cout << "The -158 is positive or negative? : " << solve( -158 ) << endl; }
The 56 is positive or negative? : Positive The -98 is positive or negative? : Negative The 45 is positive or negative? : Positive The -158 is positive or negative? : Negative
Checking whether a given integer is positive or negative in C is a basic condition checking problem, we check whether the given number is less than zero, if so, then the number is negative, otherwise it is positive. This can be extended to negative, zero and positive checks by using else-if conditions. A similar approach can be used by using the ternary operator. In this article, we discuss them with some examples.
The above is the detailed content of C++ program to check if a number is positive or negative. For more information, please follow other related articles on the PHP Chinese website!