Monday, April 28, 2025

C Program - Nested If in C Programming Example

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("Enter a Number: \n");
    scanf("%d", &num);

    if (num <= 0)
    {
        if (num == 0)
        {
            printf("You Entered 0. \n");
        }
        else
        {
            printf("Number is Negative. \n");
        }
    }
    else
    {
        printf("Positive Number. \n");
    }

    return 0;
}

Example:

Enter a Number:
10
Positive Number.

Process returned 0 (0x0)   execution time : 1.786 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("Enter a Number: \n");
    scanf("%d", &num);

This code declares an integer variable num to store the user input and prints a message asking the user to enter a number. The scanf() function reads an integer value entered by the user from the console and assigns it to the num variable. 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)
    {
        if (num == 0)
        {
            printf("You Entered 0. \n");
        }
        else
        {
            printf("Number is Negative. \n");
        }
    }
    else
    {
        printf("Positive Number. \n");
    }

This code checks the value of num using nested if statements. If the value of num is less than or equal to zero, the first if block is executed. If num is equal to zero, a message stating that the user entered zero is printed to the console. If num is less than zero, a message indicating that the number is negative is printed to the console. If the value of num is greater than zero, the else block is executed and a message stating that the number is positive 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 .  ...