If Statements

C If Statements

In C, the if-else construct is used to test conditions such as relations and optionally execute one or more statements depending on whether the condition is true. The else clause is optional, so if we merely want to do something if a condition is true and do nothing if the condition is false, then the code would look something like the following:

    if ( condition )
        statement;      // Do this only if condition is true
            

If we want to do one thing if the condition is true and a different thing if it is false, then we add the else clause:

    if ( condition )
        statement1;     // Do this only if condition is true
    else
        statement2;     // Do this only if condition is false
            

In C, including multiple statements under an if or any other construct uses the same syntax. A C block statement is any group of statements enclosed in curly braces ({}). Block statements can be used anywhere in a C program, such as in if statements, loops, or even alone.

Since C is a free-format language, it makes no difference to the compiler whether the curly braces are on the same line or different lines. However, indentation is important for readability. Adding four columns to each indent level is common, since this is half a standard TAB indent. Typically, the braces are aligned in the same column and the statements between the braces are indented one more level. Some programmers prefer to place the first brace on the same line as the if in order to fit more code onto the screen.

    if ( (age < 18) || (age >= 65) )
    {
        puts("You get free peanuts!");
        --peanut_inventory;
    }
    
    if ( (age < 18) || (age >= 65) ) {
        puts("You get free peanuts!");
        --peanut_inventory;
    }
            
    if ( (age < 18) || (age >= 65) )
    {
        puts("You get free peanuts!");
        --peanut_inventory;
    }
    else
        puts("No free peanuts for you!");
            

Free programs such as indent can automatically reformat C source files, changing the indent levels and several other aspects of code format.

Fortran If Statements

The Fortran if-then-else-endif construct is used to test Boolean expressions and conditionally execute one or more statements.

The minimal version of Fortran conditional execution consists of a condition and a single statement. The statement must be on the same line as the if ( condition ), unless a continuation character & is used. If the statement is below the if, it should be indented one more level than the if for readability.

if ( condition ) statement

if ( condition ) &
    statement
            
if ( (age < 18) .or. (age >= 65) ) &
    print *, 'You get free peanuts.'
            

If more than one statement are to be conditionally executed, then Fortran requires the longer form, with the word then on the same line as the if, the statements on subsequent lines, and finally endif on a line below the last statement. The statements between the if and endif are indented one more level than the if and endif.

    if ( (age < 18) .or. (age >= 65) ) then
        print *, 'You get free peanuts!'
        peanut_inventory = peanut_inventory - 1
    endif
            
    if ( (age < 18) .or. (age >= 65) ) then
        print *, 'You get free peanuts!'
        peanut_inventory = peanut_inventory - 1
    else
        print *, 'No free peanuts for you!'
    endif
            
Additional Use Cases

In some cases, we might be tempted to use an if statement to set a Boolean variable for later use:

    bool    free_peanuts;
    
    if ( (age < 18) || (age >= 65) )
        free_peanuts = true;
    else
        free_peanuts = false;
            
    if ( (age < 18) .or. (age >= 65) ) then
        free_peanuts = .true.
    else
        free_peanuts = .false.
    endif
            

However, note that we are simply setting free_peanuts to the same value as the condition in the if statement. In cases like this, we can replace the entire if-else statement with a simple assignment:

bool    free_peanuts;

free_peanuts = (age < 18) || (age >= 65);
            
logical free_peanuts;

free_peanuts = (age < 18) .or. (age >= 65)
            

We can take it a step further, and check for a series of conditions:

    if ( age < 3 )
        puts("No peanuts for you! You might choke on them.");
    else if ( age < 10 )
        puts("Ask your mom if you can have some peanuts.");
    else if ( (age < 18) || (age >= 65) )
    {
        puts("You get free peanuts!");
        --peanut_inventory;
    }
    else
        puts("No free peanuts for you!");
            
    if ( age < 3 ) then
        print *, 'No peanuts for you! You might choke on them.'
    else if ( age < 10 ) then
        print *, 'Ask your mom if you can have some peanuts.'
    else if ( (age < 18) .or. (age >= 65) ) then
        print *, 'You get free peanuts!'
        peanut_inventory = peanut_inventory - 1
    else
        print *, 'No free peanuts for you!'
    endif
            
Nesting If Statements

The code inside an if or else clause can contain anything, including other if statements. Suppose the economy is tight, and we decide to cancel free peanuts for seniors, but keep them for kids. We might then restructure the code as follows:

    if ( age < 18 )
        if ( age < 3 )
            puts("No peanuts for you! You might choke on them.");
        else if ( age < 10 )
            puts("Ask your mom if you can have some peanuts.");
        else
        {
            puts("You get free peanuts!");
            --peanut_inventory;
        }
    else
        puts("No free peanuts for you!");
            
    if ( age < 18 ) then
        if ( age < 3 ) then
            print *, 'No peanuts for you! You might choke on them.'
        else if ( age < 10 ) then
            print *, 'Ask your mom if you can have some peanuts.'
        else
            print *, 'You get free peanuts!'
            peanut_inventory = peanut_inventory - 1
        endif
    else
        print *, 'No free peanuts for you!'
    endif
            
Practice Break

With the class, develop a program that asks the user for the radius of a sphere and then computes the surface area and volume. The program should print an error message to stderr and exit with status EX_DATAERR if a valid number is not entered, i.e. scanf() does not return 1, or the number entered is less than or equal to zero. Be sure to use meaningful variable names, input prompts, and error messages.

Practice

Note

Be sure to thoroughly review the instructions in Section 2, “Practice Problem Instructions” before doing the practice problems below.
  1. What is a block statement in C? Where can it be used?

  2. How should if statements be indented?

  3. What is wrong with the following code?

        bool    free_peanuts;
        
        if ( (age < 18) || (age >= 65) )
            free_peanuts = true;
        else
            free_peanuts = false;
            
  4. Write a C or Fortran program that inputs the coefficients of a quadratic equation and computes the roots, if real roots exist. The program should return EX_OK if real roots exist and EX_DATAERR if they do not. These constants are defined in sysexits.h.

    Please enter the coefficients a, b, and c: 1 2 3
    There are no real roots for 1.000000x^2 + 2.000000x + 3.000000 = 0.
    
    Please enter the coefficients a, b, and c: 1 4 2
    The roots of 1.000000x^2 + 4.000000x + 2.000000 = 0 are -0.585786, -3.41421.