C All-in-One Desk Reference For Dummies Cheat Sheet
How to Make Static Variables in C Programming
Basics of Global Variables in C Programming

How to Construct a Basic IF-ELSE Statement in C

More often than not, your C-language programs react to an if comparison in two ways. First, they execute statements when a condition is true, but what happens when the situation is false? For example, consider the following code:

#include <stdio.h>
int main()
{
    float temp;
    printf("What is the temperature outside?");
    scanf("%f",&temp);
    if(temp < 65)
        printf("My but it's a bit chilly out!\n");
    if(temp >= 65)
        printf("My how pleasant!");
    return(0);
}

Save this code, compile it, and then run it. The first time, enter a value less than 65. The second time, enter a value 65 or greater. The code works because the first if statement catches all values less than 65. The second if statement catches all values 65 or greater. But, you have a better way to weave this solution in the C language: else.

Many decisions in your C programs are of the either-or type. The program takes one course of action if the condition is true, and if the condition is false, the program takes another course of action. The preceding code attempts to do this in a clumsy way with two if statements. But C has a better solution: Use the else keyword, as shown here:

#include <stdio.h>
int main()
{
    float temp;
    printf("What is the temperature outside?");
    scanf("%f",&temp);
    if(temp < 65)
    {
        printf("My but it's a bit chilly out!\n");
    }
    else
    {
        printf("My how pleasant!");
    }
    return(0);
}

This code includes all the braces for readability, and the second if statement from the first code example was replaced with else. What happens is that when the if condition is true, statements belonging to if are executed. But when the condition is false, the statements belonging to else are executed instead.

if and else work together; you cannot use else without an if statement immediately before it.

The output is no different from the preceding program, but the source code has become more readable and logical; figuring out the opposite condition isn't necessary when you can just use else.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Basics of Code::Blocks IDE for C Programming
How to Make a Simple Comparisons in C Programming
How to Use the Bitwise & Operator in C Programming
C Language Conversion Characters
C Language Variable Types
Advertisement

Inside Dummies.com