C Program to find if the number is Positive or Negative

In this C Programming example, we will implement the program to check whether the number entered by the user is positive, negative using conditional statements and relational operators, and print the output on the console.

1. Introduction

This program takes the number entered by the user and evaluates if the number is positive or negative respectively.

Example 1- Enter a number: 5
            The number entered is positive.
Example 2- Enter a number: -9
            The number entered is negative.

Helpful topics to understand this program better are


2. Find positive or negative Number using if-else-if

Given a number, we will check whether the number entered is positive or negative. Let us implement this concept in the c program and check if the number entered by the user is positive or negative.

  • Initially, the user enters a number and we call the method checkIfNumberIsPositiveOrNegative().
  • checkIfNumberIsPositiveOrNegative() evaluate whether the number is positive, negative, or zero.
  • Finally, we print the output on the console.
#include <stdio.h>

int num;

void checkIfNumberIsPositiveOrNegative() {
  if (num >= 0) {
    printf("number is positive.");
  } else if (num < 0) {
    printf("number is negative.");
  }
}

int main() {
  printf("Enter a number: ");
  scanf("%d", &num);
  checkIfNumberIsPositiveOrNegative();
  return 0;
}
Output
Enter a number: 5
number is positive.

3. Find positive or negative Number using ternary operator

Let us now rewrite the code written above using the ternary operator to find whether the number is positive or negative.

Note: We will just update the method checkIfNumberIsPositiveOrNegative()as the main method will remain the same.

void checkIfNumberIsPositiveOrNegative() {
  num >= 0 ? printf("number is positive.") : printf("number is negative.");
}
Output
Enter a number: 5
You entered a positive number.

4. Conclusion

In this C Programming example, we have discussed how to check if the number entered by the user is positive or negative using conditional statements and relational operators.


Helpful Links

Please follow C Programming tutorials or the menu in the sidebar for the complete tutorial series.

Also for the example C programs please refer to C Programming Examples.

All examples are hosted on Github.


Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index