Monday, April 28, 2025

C Program - Check Whether a Number is Positive or Negative using If Statement

This C code takes an integer input from the user and determines whether it is positive, negative, or zero. 

#include <stdio.h>

int  main()
{
    int num;

    printf("Number to Check: \n");

    scanf("%d", &num);

    if (num > 0)
        printf("%d is a Positive Number \n", num);

    else if (num < 0)
        printf("%d is a Negative number \n", num);

    else
        printf("Number is 0. \n");

    return 0;
}

Result for 10 as input: 

Number to Check:
10
10 is a Positive Number

Process returned 0 (0x0)   execution time : 2.098 s
Press any key to continue.

Here's a detailed explanation of the code: 

#include <stdio.h>

This line includes the standard input/output library, which provides functions for printing to the console. 

int main()
{
    int num;

    printf("Number to Check: \n");

This code declares an integer variable num to store the user input and prints a message asking the user to enter a number. 

    scanf("%d", &num);

This code reads an integer value entered by the user from the console and assigns it to the num variable using the scanf() function. The & symbol is used to pass the address of the num variable so that its value can be modified by the scanf() function. 

    if (num > 0)
        printf("%d is a Positive Number \n", num);

    else if (num < 0)
        printf("%d is a Negative number \n", num);

    else
        printf("Number is 0. \n");

This code checks the value of num using an if-else statement. If the value of num is greater than zero, it is considered a positive number and a message indicating so is printed to the console using the printf() function. If the value of num is less than zero, it is considered a negative number and a message indicating so is printed to the console. If num is equal to zero, a message stating that the number is zero is printed to the console. 

    return 0;
}

This line ends the main function and returns 0 to indicate that the program has completed successfully.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...