Control Structures

realrichi3

Richie Moluno

Posted on April 19, 2022

Control Structures

Control Structures enable developers to control the order of events in a program. They can be considered as the building blocks of computer programs. Control structures are commands that enable a program to “take decisions”, follow one execution path or another, repeat code, or continue linearly.

There are three basic types of control structures namely;

  • Sequential flow
  • Selection or Conditionals
  • Repetition (Loops or iteration)


Sequential flow

For sequential flow, the program is executed in an ordered form, basically in the form in which the code blocks are written in the program.

Source: GeekforGeetks.org

The first command in the sequence is executed first, the next command will only be executed after executing the previous one.

Example

name = "Richie"
print(name)

age = 99
print(age)

print("Richie is 99 years old")

Enter fullscreen mode Exit fullscreen mode

The code block above is an example of a python code. This would be the order of execution.

  1. Assign the string "Richie" to the variable "name"
  2. Print name
  3. Assign an integer value of 99 to the variable "age"
  4. Print age
  5. Print "Richie is 99 years old"

Output


>>> Richie
>>> 99
>>> Richie is 99 years old

Enter fullscreen mode Exit fullscreen mode

You can see that the print statements were executed according to the order in which they were written, it first printed the name then the age, followed by "Richie is 99 years old"



Selection or Conditional flow

The idea behind conditional flow is that they allow you to control the code execution based on different conditions in the program. There are different types of conditional statements in programming.

  • if Statements
  • while Statements

if statements

Here you're essentially telling the computer to check if a certain value is true or false. If the condition is true, the computer needs to perform a certain action. If the condition is false, then the computer would perform a different action or continue in the original sequence of code.

If statements

The general syntax for if statements are

if (condition/Boolean expression):
       statement A
Enter fullscreen mode Exit fullscreen mode

Example
Here's an example in python code

Image description

In this example, the "2 > 1" was the condition placed, and print("Hello world") is the statement. Since 2 is greater than 1 the Boolean expression returns True. Now, that the condition has been met, python will proceed to execute the code within the if statement.

What do you think will happen if the condition wasn't met?
In this case, python will ignore the statement within the if code block, and, continue to follow the original path of execution.

Image description

Here, i changed the condition, so we have 2 > 4 as the condition. 2 isn't greater than 4, this condition returns false. Now, python will ignore the statement within the if code block and continue in the original flow.

Output

>>> My name is Richie
Enter fullscreen mode Exit fullscreen mode

Instead of printing "Hello world", our output would be "My name is Richie"

For the example above, we had only two path of execution, there are cases where we may need more alternatives.


If (Condition):
     [Module A]
Else:
     [Module B]
[End if structure]

Enter fullscreen mode Exit fullscreen mode

Here, if the if condition isn't met, the code within the else block will be executed

Double Alternative control flow

To add multiple alternatives, you can use the else if of elif structure.


If (condition A), then:
     [Module A]
Else if (condition B), then:
     [Module B]
        ..
        ..
Else if (condition N), then:
     [Module N]
[End If structure]

Enter fullscreen mode Exit fullscreen mode

Example
This flow adds conditions to the else code block. Here's an example below.

Image description

Output

>>> 2 is less than 4
Enter fullscreen mode Exit fullscreen mode

The output was so because, of all the conditions stated, only 2 < 4 returned true, so python will proceed to execute the code within this block.



Repetition (Loops) structure

For loops, the program repeats a sequence of steps as often as long as the conditions placed are valid. It is similar to selection and conditional flow, since they both have a condition. And this condition has to be met before executing the code within the block.
The difference is that, the code within the block will be executed continuously as long as the condition is True.

Here, it requires a statement that initializes the condition controlling the loop, and there must also be a statement inside the module that will change this condition leading to the end of the loop.

There are generally two types of looping techniques namely;

  1. While loops
  2. For loops

While loops

In while loops, a condition is first evaluated. If this condition returns True, only then will the program proceed to execute the statements within the block.
Below, is the general syntax for while loops


while condition:
      statements

Enter fullscreen mode Exit fullscreen mode

A While loop will run as long as the condition returns true. To avoid this there has to be a statement within the block that'll change the condition. This will lead to the end of the loop.

source: geeksforgeeks.org

Here's an example where i implemented while loops in python

Image description

Condition --> counter < 5
Module --> print hello world
print the value of the counter variable
increase counter by 1

By increasing the counter by 1, it'll get to a point where the counter value will no longer satisfy the condition attached to the loop.

The program will execute in the following manner

1. Program starts.
2. counter is initialized with value 1.
3. Condition is checked. 1 < 5 yields true.
  3.a) "Hello World" gets printed 1st time.
  3.b) Updation is done. Now counter = 2.
4. Condition is checked. 2 < 5 yields true.
  4.a) "Hello World" gets printed 2nd time.
  4.b) Updation is done. Now counter = 3.
5. Condition is checked. 3 < 5 yields true.
  5.a) "Hello World" gets printed 3rd time
  5.b) Updation is done. Now counter = 4.
6. Condition is checked. 4 < 5 yields true.
  6.a) "Hello World" gets printed 4th time
  6.b) Updation is done. Now counter = 5.
7. Condition is checked. 5 < 5 yields false.
8 . Flow goes outside the loop.
Enter fullscreen mode Exit fullscreen mode

Output


Hello world
1
Hello world
2
Hello world
3
Hello world
4
Enter fullscreen mode Exit fullscreen mode

For loops

In for loops, a set of instructions are repeated for every value in a sequence. The sequence may be a list, a dictionary, a tuple or even a string.

Image description

The general syntax of a for loop is


for loopingVariable in sequence:
      code block

Enter fullscreen mode Exit fullscreen mode

Here the loop assigns the value of the first element in the sequence to the loopingVariable, then it executes the code. Then it assigns the second variable in the sequence to the loopingVariable, then it executes the code in the code block.
It will do this for every element in the sequence.

Example
Image description

In this example, letter is the loopingVariable
"Hello" is the string

What is happening here?

  1. First, the first element in the string "Hello" is 'H'. This first element is assigned to the variable letter. Then the print statement prints the letter and its' position index.
  2. The looping variable is then assigned to the second letter in the sequence, which is e. Then the print statement prints the letter e and its' position.
  3. The looping variable is then assigned to the second letter in the sequence, which is e. Then the print statement prints the letter l and its' position.

This will be repeated for all elements within the sequence till there are no more elements to assign to the looping variable.

Output


H is in position 0
e is in position 1
l is in position 2
l is in position 2
o is in position 4

Enter fullscreen mode Exit fullscreen mode

Conclusion

Control structures change the flow of programs and enable us to construct complex sets of instructions out of simpler building blocks.

As long as you understand the nature of the flow, the different control structures can be combined in any way. Conditionals can contain loops, Loops can also contain conditional. You can go a step further by adding loops within loops within conditionals. It all depends on what you want to achieve.

💖 💪 🙅 🚩
realrichi3
Richie Moluno

Posted on April 19, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Elasticsearch, descobrindo!
programming Elasticsearch, descobrindo!

May 9, 2022

Control Structures
programming Control Structures

April 19, 2022