Skip to content
This repository has been archived by the owner on Jun 25, 2021. It is now read-only.

tutorial control

Tianshu Huang edited this page Oct 3, 2018 · 2 revisions

Control Flow and Loops

At some point, you'll probably get tired of only being able to use printf. Now to make your program actually do things!

If, Else If, Else

If, Else If, and Else statements are used according to the following pattern:

if(x == 5) {
    do_something();
}
else if(x > 10) {
    do_something_else();
}
else {
    do_whatever();
}

Each else and else if statement should be associated with a previous if statement. If any code separates an else or else if from its associated if statement, the code will most likely not compile. For example,

\\ Does not compile
int x = 0;
if(x > 5) {
    foo();
}
x += 1;       // ??????
else {
    bar();
}

While

While loops will execute the code inside the block repeatedly while the condition is true.

This code prints out "0,1,2,3,4,":

int x = 0;
while(x < 5) {
    printf("%d,", x);
    x = x + 1;
}

Since your robot will probably want to run forever (and not just run through the main loop and stop), your code will probably be wrapped with a while loop that always returns:

while(1) {
    do_robot_things();
}
// or
while(true) {
    do_robot_things();
}

For

The for loop has three main parts.

int i;
//  Initial Value
//    |    Break Condition
//    |      |   'Increment'
//    v      v     v
for(i = 0; i < 5; i = i + 1) {
    printf("%d,", i);
}

At the start of the for loop, the initial condition (i = 0 in this example) is set; then, the loop is run until the break condition (i < 5 here) is no longer true. Each loop, the increment (i = i + 1) is executed.

Clone this wiki locally