Saturday, May 26, 2012

Loops in C

    We've discussed conditional commands, which may or may not be performed, but loops allow commands to be repeated many times.  Interactive applications wait for user input, process the input, output the results, and repeat in a loop until the user quits.  Three types of loops found in C are the while loop, the do-while loop, and the for loop.

While loop:
    The syntax for this loop is the simplest and allows the other loops to be built from it.  The syntax is "while (logic test) {commands;}", where logic test and commands are replaced by real code.  If the logic test is true, the commands are executed and the logic test is again tested.  This continues until the logic test is false.

    The following example should print a statement three times, wait for user input, then exit:
#include <stdio.h>

//wait_key prototype
int wait_key();

int main() {
    int cycles_performed = 0;
    int cycles_to_do = 3;

    while (cycles_performed < cycles_to_do) {
        printf("cycle %d\n", cycles_performed);
        cycles_performed = cycles_performed + 1;
        //go back to logic test
    }

    return wait_key();
}

//wait_key definition
int wait_key() {
    getchar();
    return 0;
}
output in prompt:
cycle 0
cycle 1
cycle 2

    To demonstrate how this works, let's run through the code.  The variable cycles_performed starts at 0 and we enter the while loop.  0 < 3, so we print and add 1 to cycles_performed. 1 < 3 also, so we print again and add 1 to cycles_performed.  Finally, 2 < 3 so we print and add 1 to arrive at the logic test 3 < 3.  Since 3 < 3 is false, the loop is done and the next statement is return wait_key();.

    Were you to switch the order of the printing and adding one commands, the output would start from cycle 1 and go to cycle 3.  The print command is still called three times, but the variable can be updated before the print in that case.  One loop that demonstrates the order of commands well is the do-while loop.

Do-while loop:
    Similar to the written style of the while loop, the do-while loop requires commands and a logic test.  The syntax is "do {commands;} while (logic test);" and has one key difference when compared to the while loop: the test is performed after the commands.

    If the logic test for a while loop is false, the commands will not be performed.  However, a do-while loop guarantees that the commands will be performed at least once.  The following example shows a possible side-effect of this command order:
#include <stdio.h>

//wait_key prototype
int wait_key();

int main() {
    int number = 4;

    while (number == 5) { //test first
        printf("while loop cycle\n");
        number = number + 1;
    }

    do { //test after a cycle
        number = number + 1;
        printf("do-while loop cycle\n");
    } while (number == 5);

    return wait_key();
}

//wait_key definition
int wait_key() {
    getchar();
    return 0;
}
output in prompt:
do-while loop cycle
do-while loop cycle

    The commands in the while loop are never called because 4 != 5.  For the do-while loop though, one cycle is performed and number is increased to 5.  Since 5 == 5, another cycle is performed and the loop ends because number is now 6 and 6 != 5.

    The do-while loop is the only loop which tests after a first cycle through the commands.  The equivalent for a while loop would be "commands; while(logic test) {commands;}", so the do-while loop can save some typing if you want to ensure the commands run once.

for loop:
    The final loop to discuss is the for loop.  The syntax requires more than a logic test: "for (initial command; logic test; cycle command) {commands;}".  The initial command is run once before the loop starts and the cycle command is run at the end of each loop, before the logic test.

    In previous examples, variable = variable + 1 was used to make the logic test false after a number of cycles.  This command is often used in the for loop as the cycle command, and setting the variable's value before the loop can be done in the initial command.

    For example, for (number = 0; number < 3; number = number + 1) {printf("hello\n";} will set the integer number to zero once, print "hello" and a newline, add one to number, then try the logic test.  If the logic test is true, it will print "hello" again, add 1 to number, and try the logic test again.

    The following example shows a for loop with some additional features:
#include <stdio.h>

//wait_key prototype
int wait_key();

int main() {
    int number;

    /*without break or continue, this loop
    would print 20 times*/
    for (number = 0; number < 20; number += 1) {
        if (number == 5) continue;
        printf("cycle #%d\n", number);
        if (number == 10) break;
    }

    return wait_key();
}

//wait_key definition
int wait_key() {
    getchar();
    return 0;
}
output in prompt:
cycle #0
cycle #1
cycle #2
cycle #3
cycle #4
cycle #6
cycle #7
cycle #8
cycle #9
cycle #10


    This example attempts to show the commands continue and break.  The break command was used in switch statements to exit the switch statement.  For loops, break does the same thing; in this case, when number is 10, the loop is broken and the return wait_key(); command is called.  While loops and do-while loops can also use the break statement to exit.

    The continue command in a for loop means commands from that point are no longer called, the cycle command number += 1 is called, and the logic test is run.  Notice that cycle #5 is not printed: this is because continue is called before the print statement.  However, cycle #10 is present because break is called after the print command when number is 10.

    The command number += 1; is a shortened version of number = number + 1.  This applies to subtraction(-=), multiplication(*=), division(/=), modulo(%=), and bitwise operators.  If number == 7, then number *= 5 changes the value of number to 35 since this is the equivalent of number = number * 5 (or 7 * 5).

    For loops can be converted into while loops with the form "initial command; while(logic test) {commands; cycle command;}".  However, if you call continue in this while loop, the cycle command is not called because it is a while loop.

    For more information about loops in C, check the pages http://www.codingunit.com/c-tutorial-for-loop-while-loop-break-and-continue and http://www.cprogramming.com/tutorial/c/lesson3.html.

    The next post will be about structures and custom data types.  Thank you for reading :)

No comments:

Post a Comment