If else statement in C Program

w‮w‬w.lautturi.com
If else statement in C Program

An "if-else" statement in a C program allows you to execute a block of code if a certain condition is met, and a different block of code if the condition is not met.

Here's the general syntax of an "if-else" statement in C:

if (condition)
{
    // code to execute if condition is true
}
else
{
    // code to execute if condition is false
}

The "condition" is a boolean expression that is evaluated to either "true" or "false". If the condition is true, the code in the first block (enclosed in curly braces) is executed. If the condition is false, the code in the second block is executed.

Here's an example of an "if-else" statement in C that checks if a number is positive or negative:

int num = 10;

if (num > 0)
{
    printf("The number is positive.\n");
}
else
{
    printf("The number is negative.\n");
}

In this example, the condition "num > 0" is evaluated to be true, so the code in the first block is executed and the message "The number is positive." is printed.

You can also use an "else if" clause to include additional conditions in your "if-else" statement. For example:

int num = 0;

if (num > 0)
{
    printf("The number is positive.\n");
}
else if (num == 0)
{
    printf("The number is zero.\n");
}
else
{
    printf("The number is negative.\n");
}

In this example, the condition "num == 0" is evaluated to be true, so the code in the second block is executed and the message "The number is zero." is printed.

Note: The "if-else" statement is an important control flow construct in C programming. It allows you to create conditional branches in your code and execute different blocks of code depending on the conditions you specify.

Created Time:2017-10-29 22:08:48  Author:lautturi