|
You are in Section 2 of 9, Article 2.1 of 2.6
Introduction To Control Structures
Controlling program flow is a fundamental principle of programming and computer science. There may be many different ways to find the solution to a particular problem, but the programmer will strive to find the most efficient solution.
C++ has four types of control structures:
- sequential
- selection (decision-making)
- repetition (looping)
- subprograms (functions)
These structures simply control the execution or program flow of a program.
Sequential
Sequential means that program flow moves from one statement to the next, that statement moves to the next, and so on. It is the simplest form of structures. Normally, a program will consist of a combination of sequential flow with other flow structures.
Pseudocode example:
Selection (decision-making)
Selection structures make decisions and execute commands accordingly. Selection structures involve "if statements" which are basically statements similar to "if this, then do that" and "if not this, then do that".
With "if statements", we can also include "nested if statements", which are "if statements" inside other "if statements".
Another form of a selection structure is called a "switch statement", which is very efficient under certain circumstances. "Switch statements" focus on the value of a particular variable and execute different "cases" accordingly.
Pseudocode example:
Repetition (looping)
Repetitive structures are used when something needs to be repeated a certain number of times using a "loop". A loop is simply a statement that completes iterations or cycles until a certain value is reached. Once the test expression has been met, execution moves to the next executable statement.
For instance, if the user of a program was asked to enter ten values to find the average of the numbers, a loop could be written that would continue letting the user enter numbers until ten numbers had been entered.
Pseudocode example:
Subprograms (functions)
A function is a subprogram that performs a specific task and may perhaps return a value to the statement that called or invoked it. Functions allow for modular programming because once a programmer develops a function to handle a particular situation, the programmer can later use that function to accomplish goals in other programs.
A function can call another function, which may call another function, and so on.
Functional programming is generally the fundamental method of organizing a program and breaking a program down into logical steps.
Pseudocode example:
After a very brief introduction to the different types of control structures, it's time to move on and find out how you can use each type.
We'll skip over sequential structures since we implicitly code in a sequential manner and move on to selection statements. Read on for more about "if statements"...
Next: Selection Statements
You are in Section 2 of 9, Article 2.1 of 2.6
[Back to Top]
|