08 - Loops

The Three Types of Loops

In C, there are three types of loops:

While Loop - This loop will run if the "while (condition)" is true. At the end of the loop it will check if the condition is true to see if it should run again or break out.

Do-While Loop - This is the same as a While Loop, except the "while (condition)" comes at the end of the loop so the loop will run once even if the condition is false. This can be very helpful. Example: You only want the loop to double back if the user entered something they shouldn't have, otherwise the program continues normally.

For Loop - This loop has incrementation built in. It still has a (condition) and will run until that (condition) is false. However, different from a While Loop, it also has a built in starting value (initialization) and incrementation. Example: The loop will run only while "number" is less than 5, however also built into the loop are the fact that the "number" will start at 0 and go up by 1 each time the loop runs. This saves you from writing these inside/outside the loop and can quickly and efficiently be used for such things as: repeat something x number of times, print the number from 1 to x, etc.

Below, we will look at each loop a little more closely and define the syntax that should be used with each. After looking at each loop, there will be a brief note about how to use a loop to repeat something a desired number of times.

Additional Commands in Loops

Just as in Python, there are a few very useful commands in a loop. The main two are:

break - This ends the loop immediately. This is often used with a conditional statement such as "if (condition) {break};" to stop a loop mid cycle, rather than running through the rest of the loop before checking the (condition) to see if it should run again. Keep in mind that once a loop is started, it will run through completely until it checks whether it should run again. Even if the condition for the loops becomes false right after the loop starts, it still finishes the entire code of the loop before checking if it should run again. A loop does not "continuously check" the condition.

continue - This command immediately restarts the loop. Again this is often used with a conditional statement such as "if (condition) {continue};" to skip the rest of the code in the loop and immediately start the loops over.

While Loop

A while loop is the same as in Python. This loop will only run if the (condition) is true. It will continue to run until the (condition) is false. Remember that once the while condition is checked, the entire set of brackets will run, and the condition won't be checked again until the entire set of brackets is done running. If the condition is changed in the middle of the bracketed section, it will only stop if there is a "break" command. The syntax of an example of this loop is below.

Example:

while (condition) {

command statement;

}

Below is an example of code that would print the numbers 0 to 4 on separate lines.

Example:

int counter = 0;

while (counter<5) {

printf("%d\n",counter);

counter = counter + 1;

}

Activity 1

Write a program that counts down from 10 to 0, then say BLAST OFF! once at the end.

Solution: Link

Activity 2

Write a program that:

1. Ask the user for a positive integer.

2. Calculate the sum of the numbers from 1 to the number the user entered.

3. Print the sum in a complete sentence.

Solution: Link

Do While Loop

This is the same as a While Loop, except the condition for the loop is checked at the end. This way you are certain the code in the loop will run through at least once, then it will check if it should/needs to run again.

Example:

do {

command statement;

} while (condition);

Below is a sample of how this code might be used. It will run through once, then ask if it should run again. If the user enters yes, it will run again.

Important Note - Remember that you cannot use the "==" operator to compare strings or arrays. Instead you need to include the "string.h" header and use the "strcmp" function to compare the two strings. This literally compares the values of every slot of the two strings. If all of the values are the same, it returns 0. If they are different it returns an integer other than 0.

Activity 3

Write a program that:

1. Uses a DO WHILE loop to ...

2. Tell your own joke (this happens before the user is asked anything)

3. Ask the user if they would like to hear the joke again.

4. Have the user enter a 1 if they would like to hear it again, or a 0 if they are done with your nonsense.

Solution: Link

For Loop

A for loop works just like a while loop as it has a (condition) at the start that determines whether it will run or not. Additionally though, it can initialize and increment automatically. This can be really useful when using an index counter or if you want to repeat code x number of times.

Overall format:

for (initialization; test; increment) {

command statement;

}

Explanation of the three inputs/parameters of the For Loop:

initialization - This can be used to initialize a variable to any desired starting value and will only happen once, before the loop has run the first time. You can create/declare a new variable here.

test - This is the (condition) that determines whether the code in the loop will run, just like in a While Loop.

increment - This can automatically increment a number, for example it could do something like "add one to the index counter after each time the loop runs".

Example of this code can be found below. This code will print the numbers from 1 to 5 then stops.

for ( int counter=0; counter<=5; counter++ ) {

printf("%d\n",counter);

}

Note about Incrementing:

You can automatically increment in the C programming language using the commands below:

counter++ or counter+=1 is equivalent to counter = counter + 1 (which is equivalent to counter += 1 in Python)

counter-- or counter-=1 is equivalent to counter = counter - 1 (which is equivalent to counter -= 1 in Python)

Activity 4

Write a program with four FOR loops that do the following:

1. Count from 1 to 10 inclusive.

2. Count from 2 to 7 inclusive.

3. Count down from 21 to 5 inclusive.

4. Count from 3 to 36 inclusive by 3.

Solution: Link

Activity 5

Write a program that:

1. Asks the user for an integer to start counting at.

2. Asks the user for an integer to count until (inclusive).

3. Asks the user for an integer to use as an increment/step.

4. Write a FOR loop that starts counting at the starting value, goes in steps of the given value and ends and the given value.

Solution: Link

Using Loops as a "Repeat X Number of Times" Command

In many of the examples above, we used a counter in our loops to do such things as print the numbers from 1 to 10. Notice that instead of this, we could have used the same code to print the word "great" those ten times by simply switching the two codes below:

This code prints the numbers 1 to 10.

This code prints "great" ten times.

int counter = 1;

while (counter<11) {

printf("%d\n",counter);

counter = counter + 1;

}

int counter = 1;

while (counter<11) {

printf("great\n");

counter = counter + 1;

}

Notice that the counter is still declared/created, and is still initialized to be equal to one. The counter is still incremented up by one each time the loop runs and the counter is still being tested to see if the loop should run again (is counter less than 11?). The only difference is that the counter is not being printed in the code on the right. It can still be used to count the number of times the loop runs. Below are examples of each loop being run 10 times. You can just replace the 10 below with any number you want, or a variable that the user inputs, and these types of loops can repeat code a desired number of times.

While Loop

int counter = 1;

while (counter<11) {

printf("great\n");

counter = counter + 1;

}

Do-While Loop

int counter = 1;

do {

printf("great\n");

counter += 1;

} while (counter<11);

For Loop

for (int counter=1; counter<11; counter++) {

printf("great\n");

}

Notice that I used a difference way to increment in each loop (increase the counter by 1 each time). Be comfortable seeing any of these three types (counter = counter +1, counter+=1, counter++). They are all equivalent and all simply add one to the current value of "counter".

Activity 6

Write a program that:

1. Asks the user for a string to print (easy - single word, advanced - multiple words in a line).

2. Asks the user for an integer number of times to print this string.

3. Write a loop that prints this string the desired number of times.

Solution: Link

Common Mistakes

    1. Using commas in the FOR loop instead of semicolons. As we often use commas to separate inputs in a function, and simply to denote separate values in programming, it can be a common mistake to use commas in the declaration of a FOR loop. This causes an a red error message. Example of the mistake: for (int counter=0, counter<10, counter++) ...

    2. More coming soon ...