SPA4321 Introduction to C++ 2015-16 Flow Control: Loops and Branches In this document you’ll learn about how to change the flow of your programs: how to make decisions during running about which instructions to run and how to repeat instructions. The specific topics covered are: if… then .. else statements switch statements for loops while loops do … while loops The first two of these concern making decisions – branching – and the last three concern repeating sections of code – looping. Branching: Taking decisions Branching allows you to execute based on the result of a test. In C++ this can be carried out in two basic ways: the if statement and the switch statement. In actual fact the later of these is actually just a specialised form of the first. The minimal if statement is: Here you just have the word if followed by round brackets. Inside the brackets must be an expression that evaluates to a bool value – either true or false. Typically this will be done with a comparative operator like less-than ( < ) or greater-than ( > ), equal-to (==) or not-equal-to (!=). Note here - = is not the equal-to operator. It is the assignment operator. To check if two things are the same you need to use: ==. But since all built-in types will implicitly convert to a bool: 0 = false, anything else = true, you can also do statements like: In this case, the integer is non-zero and so the test is true and the message will be printed. 1 SPA4321 Introduction to C++ 2015-16 Generally it is good practise to explicitly do the comparison, even when you are testing simply for a non-zero value. It makes the code clearer to read and you are less likely to make a mistake. Also, note in the second example the if-statement was followed by a scope, a pair of curly brackets enclosing some instructions, but in the first example it wasn’t. If you don’t put the curly brackets there, the compiler will assume that the very next instruction it finds – and only that one single instruction - is what you want it to execute if the test expression is true. It will then carry on executing from the second instruction after the if-statement. Though leaving out the curly brackets saves you a bit of typing and allows you to write code that is slightly more compact, generally you should consider always putting the curly brackets in there explicitly – this avoids some very simple mistakes. Note, also the location of semi-colons. There is no semi-colon after an if-statement – this can also lead to a very common mistake: If you put this snippet into a program and run it – you might think it would never print the message “Test is true”, since the test is always false. But the presence of the semi-colon is interpreted by the compiler as an empty but perfectly valid statement – and it assumes this is what should be executed in the case that the test is true. Then, having dealt with the if-statement it moves to the next line of code and runs it – assuming it has nothing to do with the if-statement – even though the indentation in the editor might suggest to a human eye something different. You can see in this snippet, where the border of the editor window in Eclipse has been included that there is a yellow bug symbol, indicating Eclipse has spotted something that isn’t strictly wrong according to the language rules but which looks a bit suspicious all the same. Always pay attention to these warnings, they are almost always indicators of a real mistake. You can also provide alternative code to be executed if the test is false using the else keyword: 2 SPA4321 Introduction to C++ 2015-16 Here, you have the word – else – between two scopes. If the test is true, then the instructions in the first scope will be executed, otherwise the code in the second scope will be executed. You can even chain together a series of if-statements as follows: If the first if-statement is true then is will print the first message and jump to the end and print a newline. If the first if-statement is false, however, it will try the second if-statement. If this is true it will print the second message and jump to the end. If this is false it will move to the next ifstatement and keep going until either an if-statement is true, or there are no if-statements left – at which point it will execute the code in the “else” block. Another way of building a similar decision structure is using a switch-statement: This will carry out the same actions as the previous example. This starts with the keyword switch followed by brackets which must contain the variable to be tested – this must be an integral type (ie int, char or bool). Then inside a scope are one or more case-statements. Each of these tests the value given against the value in the variable. If a match is found, then execution starts from that spot and runs until the end of the switch statement – doing no more tests but executing all the code. So it ignores the case-statements but not the instructions in-between. This is a little different from the example using if-statements – where only the code in the matching block will be executed. The behaviour can be made the same through the use of a break statement. This causes the execution to 3 SPA4321 Introduction to C++ 2015-16 skip to the end of the scope. The equivalent of the final else from the previous example, is then the “default:” section. This is optional and will always match the parameter, if no preceding case statements match. Loops : repeating things Loops are ways to repeat the same instructions over and over again. There are three forms of loop in C++: The for loop This is primary used for repeating something a known number of times. It begins with the word – for – which is then followed by a bracket containing three parts separated by semi-colons. The first part is the initialisation instruction. This is executed once at the beginning of the loop – in this example we set a variable, i, equal to 0. The second part consists of a test – the loop will stop unless this condition is true – in this case we check to see if the variable i<n. The third part is an action carried out at the end of every loop – typically this is used to increment the variable. Then the final part is the scope enclosed in the curly brackets – these are the instructions that will be executed inside the loop. In principle, just as with the if-statement, you can leave out the curly brackets and the compiler will assume the very next statement (and only this one) is the body of the loop. As with the ifstatement – this is not recommended, it saves some typing but so often leads to mistakes that it is a good idea to always use the curly brackets. Also, notice that just like an if-statement, there is no semi-colon after a for-statement. The loop in the example above will run through 10 iterations (since n=10). This diagram shows the flow of the loop: 4 SPA4321 Introduction to C++ 2015-16 The while loop This loop is mostly used when perhaps you don’t know quite how many loops you want to run. It has the form: It begins with the keyword – while – followed by brackets that contain a condition that must evaluate to true for the code in the curly brackets to be executed. It will keep executing the code in the curly brackets until the condition is false. The example here will run forever – since finished = false and thus !finished = true. Here, again – no semi-colon should be used after the while- 5 SPA4321 Introduction to C++ 2015-16 statement. The flow looks like this: The do-while loop This is almost the same as the while-loop – the difference being that the test is made at the end of the loop – thus it will always execute the code in the loop at least once. Notice, however, that here you need to have a semi-colon after the while loop. 6 SPA4321 Introduction to C++ 2015-16 Exercises These exercises are non-assessed – they do not contribute towards your module mark. They are intended to give you some basic practise using loops and branches. Exercise 1: Loops In a new project called “Loop” carry out the following tasks: using a “for” loop, print the integer numbers from 1 to 10 to the console using a “while” loop, print the integer numbers from 1 to 10 to the console using a “do while” loop, print the integer numbers from 1 to 10 to the console using a “for” loop, print the integer numbers in decreasing order from 10 to 1 to the console using a “while” loop, print the integer numbers in decreasing order from 10 to 1 to the console using a “do while” loop, print the integers number in decreasing order from 10 to 1 to the console Exercise 2: Even In a new project called “Even” carry out the following tasks: write a program to print out the numbers between 1 and 20 in the following way: o using a “for” loop, print out the numbers from 1 to 20 – one per line – to the console o using an “if” statement, print out the number and the message “Even” if the number is even, or the number and the message “Odd” if the message is odd. Use the modulo operator to test if the number is even or not Exercise 3: Choices In a new project called “Choices” carry out the following tasks: Write a program that requests a single character as input from the console and store the result in a char variable Using an if-then-else structure print the following messages depending on the input stored from the console: Input a b c d Any other input Message “a is for apple” “b is for banana” “c is for cranberry” “d is for date” “I don’t know any other fruit” Exercise 4: Case In a new project called “Case” repeat the task from Exercise 3 but use a switch-case structure instead of if-then-else 7
© Copyright 2025 Paperzz