Program to Check Whether a Number is Positive or Negative - (C# Basic Programs)
In this tutorial, we will discuss a basic program to check whether a number is positive or negative using C# programming language.
Syntax
The syntax of the program to check whether a number is positive or negative in C# is as follows:
if (number > 0)
{
Console.WriteLine("The number is positive");
}
else if (number < 0)
{
Console.WriteLine("The number is negative");
}
else
{
Console.WriteLine("The number is zero");
}
Example
using System;
namespace PositiveOrNegative
{
class Program
{
static void Main(string[] args)
{
int number;
Console.WriteLine("Enter a number: ");
number = Convert.ToInt32(Console.ReadLine());
if (number > 0)
{
Console.WriteLine("The number is positive");
}
else if (number < 0)
{
Console.WriteLine("The number is negative");
}
else
{
Console.WriteLine("The number is zero");
}
Console.Read();
}
}
}
Output
Enter a number:
-5
The number is negative
Explanation
This program prompts the user to enter a number and then uses conditional statements to check whether the number is positive, negative or zero. If the number is greater than zero, the program outputs "The number is positive," if the number is less than zero, the program outputs "The number is negative," and if the number is equal to zero, the program outputs "The number is zero."
Use
Checking whether a number is positive or negative is an essential basic programming task that can be used in a variety of programs. This program can be modified to perform more complex arithmetic calculations or to implement other logic based on the sign of the input number.
Summary
In this tutorial, we discussed a basic program to check whether a number is positive, negative or zero using C# programming language. We have seen the syntax, example, explanation and use of checking whether a number is positive or negative. This program serves as a foundation for more complex C# programs and can be useful in a range of real-world applications.