Flow Control

Sometimes it is useful to setup your program so that certain lines of code are executed based on certain conditions. C gives us the ability to control how the execution flows through our code, hence the term “flow control”. You will also learn about random numbers.

Example Program

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    int num;
    int loop;
    int count;
    
    // Seed random number generator
    srand(time(0));
    
    // Randomly number [0,999]
    num = rand() % 1000;
    
    /*
     * We want num to always
     * print with 3 digits,
     * so we will prepend a 0
     * if it is less than 100
     * and 00 if less than 10
     */
    if(num < 10)
    {
        printf("00%d\n",num);
    }
    else if (num < 100)
    {
        printf("0%d\n",num);
    }
    else
    {
        printf("%d\n", num);
    }
    
    loop = 1;
    while(loop)
    {
        num = rand();
        // Loop until num is even
        loop = num % 2;
        printf("%d\n",num);
    }
    
    // Pick a random number to count to
    num = 1 + (rand() % 10);
    for(count = 0; count < num; count++)
    {
        printf("%d\n",count);
    }
    
    return 0;
}

Your output almost certainly will not look exactly like what you see below, but it should resemble this.

008
2089878753
246795180
0
1
2
3
4 
5
6

Random Numbers

In order to use random numbers, we will be adding two headers, stdlib.h and time.h. Including stdlib.h will add C Standard Library, which gives us access to a LOT of features, but we only care about one of them right now. We are not doing much with time.h, we are just using the clock to tell the generator what value to start with.

// Seed random number generator
srand(time(0));

If we skip this step, we will end up getting exactly the same numbers every time, which defeats the purpose of random numbers. It’s not critical to understand the details of random seeds, but it’s critical to remember this line in your program if you want your numbers to appear random. That being said, if you want to learn more, knock yourself out.

If, Else If, and Else

An if statement takes a value and if the value is not zero it executes the block. If the value is zero, the block is skipped. If you want to add a block that is only executed when the condition is false, you add an else block. The else block can also include an if condition. An else statement with an if is called an else if, and it is only evaluated if the first if statement is false.

// Randomly number [0,999]
num = rand() % 1000;
    
/*
 * We want num to always
 * print with 3 digits,
 * so we will prepend a 0
 * if it is less than 100
 * and 00 if less than 10
 */
if(num < 10)
{
    printf("00%d\n",num);
}
else if (num < 100)
{
    printf("0%d\n",num);
}
else
{
    printf("%d\n", num);
}

Our example code uses an if, else if, and else to make sure our random integer always prints with 3 digits. Only one of the three blocks will be executed, and it will be executed once.

While Loops

If statements are useful, but they can only be executed once. If you would like to repeat a block of code based on a condition, then a while loop is what you are looking for. The condition is evaluated repeatedly, so it is important to write your code in a way that will cause your loop to end when appropriate.

loop = 1;
while(loop)
{
    num = rand();
    // Loop until num is even
    loop = num % 2;
    printf("%d\n",num);
}

In our example program, we are doing a trick with the modulo operator. We are dividing the random number by two and storing the remainder as the loop variable. Since we want the loop to stop when the number is even, storing a remainder of 0 as the condition will accomplish this for us. Not that there is another type of while loop, a do while loop, which is used when you know for certain that the loop needs to be run at least once. Our example code can be rewritten using a do while loop, as shown below:

do
{
    num = rand();
    loop = num % 2;
    printf("%d\n", num);
} 
while(loop);

You could very easily argue that the above code is more suitable for our example, given that we will be going through the loop at least once to find an even number. Like most things in C, this is down to your judgment.

For Loops

In some cases where we need a loop, we are only concerned with how many times the code is executed, rather than a condition that is evaluated based on the execution. For this, we have a for loop. A for loop takes an initialization statement, a condition, and an increment statement. It will execute the code and perform the increment on the initialized variable until the condition is met.

// Pick a random number to count to
num = 1 + (rand() % 10);
for(count = 0; count < num; count++)
{
    printf("%d\n",count);
}

In our example code, our only concern is that the loop is run num times. Most for loops can be rewritten as while loops, but this is usually more cumbersome because it requires you to initialize the variable before the loop and increment the variable inside the loop, both of which make it more prone to errors.

Switch Statements

If you can find a place in my code where I use switch statements, I will add them to this tutorial. Otherwise, I will refer you to this tutorial. Most use cases of switch statements can be logically reconstructed to use an if statement.

<< prev | next >>

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x