Introduction to Programming/Control Structures

Up to this point, the programs that we have looked at are very simple and serial in nature. Obviously computers can do more, but how?

Say, for example, that you write a small program that calculates how many seconds are in a given year. This is clearly a pretty trivial program, but it does have one interesting wrinkle—the number of days in a year isn't a constant. So how do we write a program that uses different values depending on the year? There are many different ways that this can be accomplished, but one of the most straightforward is to have a piece of code that is only executed if some condition is true—if, say, the year in question is a leap year then set the number of days to 366 instead of 365.

The If Statement

edit

Up to this point, everything that we've covered involved simple, linear execution of every line of code. In the seconds in a year example from above, we could have a line that declared a variable daysInYear and initialized it to 365.

   int daysInYear = 365;

That is the end of what we know how to do so far.

What we need now, is some way to say that, in the event that the year is a leap year, assign the value 366 to the variable daysInYear. One way to do this is with an if statement.

In most programming languages, an if statement contains three parts. The first part is a keyword that tells the computer that it's an if statement (some languages may have an equivalent structure that uses a different key word). The second part is a boolean expression. The third part is a statement or group of statements.

The way that the computer executes an if statement is that, first it evaluates the boolean expression. If the expression evaluates to false, it skips the third part, the statement(s), completely as if they weren't even there. On the other hand, if the expression evaluates to true, then the statement(s) are executed.

In a Java/C/C++ environment, where there was a boolean variable isLeapYear, you would write code that would look something like this:

    int daysInYear = 365;
    if (isLeapYear)
    {
        daysInYear = 366;
    }

It may not be the most interesting code ever written, but it is simple, direct and produces the correct result.

Variations Of If Statements

edit

An alternate way to set the number of days in a year might be:

    int daysInYear;
    
    if (isLeapYear)
    {
        daysInYear = 366;
    }
    if (! isLeapYear)
    {
        daysInYear = 365;
    }

This form seems kind of awkward and it requires the condition to be evaluated twice. Many programming languages allow an extension of the if statement, an else clause. It would look something like this:

    int daysInYear;
    
    if (isLeapYear)
    {
        daysInYear = 366;
    }
    else
    {
        daysInYear = 365;
    }

An if statement may be followed by exactly zero or one else statements. If the if statement evaluates as true, then its group of statements (in this case "daysInYear = 366;") are run. If the if statement evaluates as false the else clause's statements are executed (in this case "daysInYear = 365;").

Sample Problem: Checking an Error Condition

edit

One of the more common uses for the if statement is checking error conditions.

Let us suppose that we are working on a piece of code that performs a divide in a calculator program. We have three variables dividend, divisor and quotient. We want to divide dividend by divisor putting the result into quotient, unless divisor is equal to 0 in which case we want to report an error message. Assume that there is a statement ReportErrorMessage that does exactly that and write some code that performs the divide operation.

answer

Loops

edit

A loop is a program structure that executes the same piece of code zero or more times. A loop consists of a group of statements (called a block in many languages) to be executed and a boolean expression, called a condition. Every time the computer executes the statements in the loop (called an iteration), the condition is evaluated. The computer continues to iterate as long as the condition evaluates to true.

In some programming languages a while loop looks something like this:

int counter = 1;
int sum = 0;

while (counter < 10)
{
    sum += counter;
    print sum;

    counter += 1;
}

This is the style of while loop used in Java, C and C++. The code of the block is delineated in this example by a matched pair of curly braces. The condition is inside the parenthesis that follows immediately after the keyword while. The sample while loop given above will execute nine times with the value of the variable counter starting at one. With each iteration through the loop, the value of counter is incremented by one. When the value of counter reaches ten, the condition will evaluate to false and the loop will not be executed. With each iteration, the program will print out the sum of the first N integers with N equal to counter.

Exercise: Fibonacci numbers

edit

Using the above loop as a template, create a block of code that will print out the first 10 Fibonacci numbers.

answer

Pre-conditions versus post-conditions

edit

The while loop shown above is an example of a loop structure where the condition is checked before the code is executed. This is known as a pre-condition. The block is not executed at all if the pre-condition is false when reaching the loop.

In Java, C and C++, there is a structure that is called a do-while loop that is nearly identical to a while loop, except that it uses a post-condition. Because the condition is checked at the end of the loop, post-condition loops are guaranteed to execute at least once.

int counter = 1;
int sum = 0;

do
{
    sum += counter;
    print sum;

    counter += 1;
}
while (counter < 10)