Warning
This page is located in archive. Go to the latest version of this course pages. Go the latest version of this page.

Lab02 - Control flow

  • Look at controlling the flow of code
  • Introduction to if statements
  • Introduction to loops

Makefile

To make our compilation easier, we can use a makefile. These mean that we don't have to remember the command, but can just type “make” in a terminal when it is in the correct directory.

“make” will run the all command, which in our case runs a bash command. “make” on its own will run the all command but if we want anything more specific, we can run for example “make clean” which will remove temporary files form the file system.

Make sure your makefile is named “Makefile” with a capital M, and its very important to use tabs within the file rather than space-based indentation.

all:
	gcc main.c -o output -lm
	
clean:
	rm output -f

If statements

We can control the flow of our code by making certain parts of our code only execute if some condition is met. The general layout for this is as follows:

if(myVariable < 5)
{

}
else if(myVariable < 10)
{

}
else if(myVariable < 15)
{

}
else
{

}

Loops statements

Three types of loops exist, for making your code execute certain things repetetively. They are the while loop, for loop, and do while.

While loops: The while loop will check the variable condition (in the example below if the variable is greater than 20. If the variable is, the block of code will run, else the block of code will be skipped. If the block of code was run, at the end the program will come back to this line and check again.

while(myVariable > 20)
{

}

For loops: The for loop allows you to declare a variable, and check if it matches some condition. If so, then the block will repeat. Below we set a variable to zero, and as long as it is below 20, we keep repeating. The for loop increments the variable each time.

for(int i = 0; i < 20; i++)
{
    printf("Number of loops: %i\n", i);
}

Do while loops: These are very similar to while loops, however as the syntex suggests, the comparison is done at the end. This guarantees at least one loop.

do
{

}
while(myVariable < 5);

Exercises

  1. Task 1: Create a program which will prompt the user for a number. The program will add this to a total, display it, and then keep prompting the user again in a loop. If the user enters zero, the program will close. Use a while loop.
  2. Task 2: Alter Task 1 such that the program will also close if the total gets above 25. Change the code to a do while loop.
  3. Task 3: Write a program which prompts the user for a date in the format YYYY-MM-DD. The program will make use of a switch statement in order to print the date in a written form (eg. 16th November 2022)
courses/be5b99cpl/labs/lab02.txt · Last modified: 2022/10/05 13:17 by brouggeo