Google Add

Search

Check Whether a Number is Positive, Negative or Zero in C, C++

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

This is very basic and easy programming question. If you are solving this problem then i recommend first try by itself and then check the solution.

Some more basic programming questions.

Print ASCII value of input character.

Compare two strings using strcmp().

Calculate the sum of digits of a number.

How to check whether a number is positive, negative or zero 


The logic of this program is pretty simple and straightforward.

1. Take a input number from user.

2. If number is greater than zero, it is positive. If it is less than zero then it is negative. If it is equal to zero then it's zero.

Check Whether a Number is Positive, Negative or Zero in C


#include <stdio.h>

int main(void) {
 
 int num;
 
 printf ("Enter a number \n");
 scanf ("%d", &num);
 
 if (num > 0) {
  
  printf ("You have entered positive number");
 
 } else if (num < 0) {
  
  printf ("You have entered negative number");
  
 } else {
  
  printf ("You have entered zero");
 }
 
 return 0;
}


Check Whether a Number is Positive, Negative or Zero in C++


#include <iostream>
using namespace std;

int main() {
 int num;
 
 cout << "Enter a number \n";
 cin >> num;
 
 if (num > 0) {
  
  cout << "You have entered positive number";
 
 } else if (num < 0) {
  
  cout << "You have entered negative number";
  
 } else {
  
  cout << "You have entered zero";
 }
 
 return 0;
}

Output :

Enter a number : 5

You have entered positive number

Enter a number : -2

You have entered negative number

Enter a number : 0

You have entered zero

No comments:

Post a Comment