Wednesday, 10 January 2018

Coding - Sequence & Selection

Examples of sequences would be if statements, else statements and switch cases. The if statement checks if the condition is "true" or as truthy. So if there is a variable called 'a' and it is equal to 1 then if you check if it is greater than 0 then it will be true. If the condition is not met then it skips what is inside the brackets and continues to a fallback statement identified by the syntax "else" if it is defined. Here is an example in C#.


In this snippet of code it checks if the inputted string contains a '@' or '.' symbol and if they are found then the variables "containsAt" and "containsDot" are set to true. If both of them are true then the code in the brackets under it are executed. If either one of them are false then the code in the brackets under the else syntax is executed.



Another example of sequences is a switch or case statement and the switch statement is a neater way of doing multiple if statements which use the same variable. With the switch statement you only specify what variable you want to check once.


Then with the syntax "case" if the value you specify is equal to the variable that you are checking then the code below it is executed. A few other things to note is that the syntax "break" skips to the end of the switch statement. The syntax "default" is equivalent to the else statement and if non of the other cases are met then it executes the coder under it.

















An example of iteration would be a for loop which will do x a y amount of times. This is useful to loop through an array and get an object in that position. Another example of iteration is a while loop which as the name suggests executes a set of code while a condition is met.


In this example the local variable 'i' is assigned the value of 0 since a string is an array of characters. After the semi colon is a condition including the variable 'i' and if that condition is met then the following statement after that is executed. In this for loop it will loop though each character in the string and check if it is a '@' or '.'. 





No comments:

Post a Comment

Coding - Variables & Statements

Variables Variables have naming conventions such has camel, pascal, and Hungarian. These are the ways that people will name their variab...