C++ Control Statement: The Complete Guide For Beginners 2022

C++ Control Statement

A C++ control statement changes the flow of a program so that more code can be executed. Conditionals (if-else, switch) and loops are examples of these statements (for, while, do-while). To run one piece of code over another, they each rely on a logical condition that evaluates to a Boolean value.

A simple C++ statement is each of a program’s individual instructions, such as the variable declarations and expressions discussed previously. They always terminate in a semicolon (;), and they run in the same sequence as they occur in the program.

Programs, on the other hand, are not bound to a set of statements in a sequential order. A program may repeat code portions or make decisions and bifurcate during its execution. C++ includes flow control statements for this purpose, which specify what our program must do, when it must do it, and under what conditions.

AA generic (sub)statement is required in many of the flow control statements discussed in this section. This statement can be either a simple C++ statement or a compound statement, such as a single instruction followed by a semicolon (;).

A compound statement is a collection of statements (each ending in a semicolon), all of which are put together in a block and contained in curly braces::

The whole block is treated as a single statement (composed itself of multiple substatements). When a generic statement appears in a flow control statement’s syntax, it can be either a simple or a compound statement.

Boolean Logic

On their own, Boolean values don’t appear to be particularly useful, but when paired with control statements, they become one of the most powerful tools available in any programming language.

Boolean variables (bool) can be either true or false, as indicated in the data types notes. Binary operators are also available, which return a Boolean value based on certain conditions.

Some comparison operators, such as == and!, are used. =, >, etc., and return true if the entire statement is true. Others, such as && and ||, work with Boolean values to return another Boolean.

OperatorSymbolUsageExample
Equals==Returns true if the statements on either side of the operator are the same value, otherwise it returns false. Can be used with int, double/float, char, boolean, and string.x == ‘A’
Not Equal!=Returns true if the statements on either side of the operator are not the same, otherwise it returns false.x != 2
Greater Than>Returns true if the first term is greater than the second, otherwise it returns false. Note: If both terms are equal it returns false.x > 0
Less Than<Returns true if the first term is less than the second, otherwise it returns false.x < 10
Greater Than or Equal>=Returns true if the first term is greater than or equal to the second, otherwise it returns false.x >= 0
Less Than or Equal<=Returns true if the first term is less than or equal to the second, otherwise it returns false.x <= -2
And&&Returns true if both terms on either side of the operator are true, otherwise it returns false. It is commonly used to concatenate statements together.x && True
(x == 2) && (y >= 0)
Or||Returns true if any of the terms on either side of the operator are true, otherwise it returns false.x || y
Not!Negates the value of the statement that follows it.!(x > 2)
The expression being evaluated is called condition in this case. The statement is executed if this condition is true. If it’s false, the statement won’t be executed (it’ll just be ignored), and the program will continue directly after the selection statement.
The code segment below, for example, prints the message (x is 100) only if the value stored in the x variable is 100:

If and else statements are examples of selection statements.

If-Else statements allow the program to run different sections of code based on conditionals. The following is the format of all If statements:

If and only if a condition is met, the if keyword is used to execute a statement or block. Its syntax is as follows:

The expression being evaluated is called condition in this case. The statement is executed if this condition is true. If it’s false, the statement won’t be executed (it’ll just be ignored), and the program will continue directly after the selection statement.
The code segment below, for example, prints the message (x is 100) only if the value stored in the x variable is 100:

This sentence is disregarded if x is not exactly 100, and nothing is printed.

If you want more than one statement to be performed when the condition is met, wrap them in braces (), producing a block:

Indentation and line breaks have no effect in the code, hence the above code is equivalent to:

By utilizing the otherwise keyword to offer an alternative statement, selection statements with if can also define what happens if the condition is not met. Its syntax is as follows:

Where statement1 is executed if condition is true, and statement2 is executed if condition is false.

Consider the following scenario:

If x has a value of 100, this prints x is 100; if it does not, and only if it does not, it prints x is not 100.
With the goal of verifying a range of values, several if + else structures can be concatenated. Consider the following scenario:

By concatenating two if-else structures, this prints whether x is positive, negative, or zero. Again, by grouping the statements into blocks enclosed in braces, it would have been possible to execute more than one statement per case:(C++ Control Statement: The Complete Guide For Beginners 2022)

Iteration statements (loops)

Loops repeat a sentence until a condition is met or a specified number of times. The keywords while, do, and for are used to introduce them.

While Loop

The while-loop is the most basic type of loop. Its syntax is as follows:

Output:

In main, the first statement sets n to a value of 10. In the countdown, this is the first number. The while-loop then begins: if this value meets the condition n>0 (that n is greater than zero), the block after the condition is executed, and the process is continued as long as the condition (n>0) is true.

The following script (beginning in main) can be used to interpret the entire process of the previous program:

  • A value is assigned to n.
  • (n>0) The while condition is checked. There are two options at this point:
  • The statement is executed if the condition is true (to step 3)
  • If the condition is false, disregard the statement and go on (to step 5)
  • Statement to be executed:
  • cout n n n n n n n n n n n n n n n
  • —n;
  • (prints n’s value and reduces n by one)
  • The block is now complete. Return to step 2 automatically.
  • After the block, continue the program as follows:
  • Liftoff is printed! and then turn off the television.

When using while-loops, keep in mind that the loop must come to a conclusion at some point, therefore the statement must change the values checked in the condition in some way to compel it to become false at some point.

Otherwise, the loop will keep continuing indefinitely. The loop in this example includes —n, which reduces the value of the variable being evaluated in the condition (n) by one, making the condition (n>0) false after a specific number of loop iterations.(C++ Control Statement: The Complete Guide For Beginners 2022)

To be more exact, after 10 iterations, n equals 0, indicating that the condition is no longer true and the while-loop is terminated. Because the complexity of this loop is trivial for a computer, the entire countdown is completed instantaneously, with no practical delay between elements of the count (for a countdown example with delays, see sleep for).

Do-While Loop

The do-while loop, which has the following syntax:

It behaves similarly to a while-loop, with the exception that condition is evaluated after rather than before the execution of the statement, ensuring that the statement is executed at least once, even if condition is never met. The following example application, for example, repeats any text the user enters until the user says goodbye:

// echo machine
#include
#include
using namespace std;

int main ()
{
string str;
do {
cout << "Enter text: "; getline (cin,str); cout << "You entered: " << str << '\n'; } while (str != "goodmorning"); }

Output:

When a statement must be executed at least once, such as when the condition to check at the loop’s end is determined within the loop statement itself, the do-while loop is usually preferred over the while loop.

The user input within the block determines whether the loop ends in the previous example. As a result, even if the user wants to exit the loop as quickly as possible by typing goodbye, the block in the loop must be executed at least once to request for input, and the condition can be determined only after it has been executed.

For Loop

The for loop is made to iterate several times. Its syntax is as follows:

This loop, like the while-loop, repeats the statement while the condition is true. However, the for loop also includes particular locations for an initialization and an increment expression, which are run before the loop starts for the first time and after each iteration, respectively. As a result, using counter variables as a condition is particularly handy.

The following is how it works:

  • initialization is carried out. In most cases, this declares a counter variable and sets it to a value. This is only performed once, at the start of the loop.
  • The condition has been verified. If it’s true, the loop will continue; if it’s false, the loop will finish and the statement will be skipped, sending you straight to step 5.
  • The statement is carried out. It can be a single statement or a block enclosed in curly braces, as is customary.
  • increment is carried out, and the cycle returns to step 2.
  • The loop comes to a close, and the following sentence in the sequence takes its place.

Here’s an example of a countdown using a for loop:

// countdown using a for loop
#include
using namespace std;

int main ()
{
for (int n=10; n>0; n–) {
cout << n << ", "; } cout << "itsourcecode!\n"; }

Output:

A for-three loop’s fields are optional. They can be left blank, however semicolon signals between them are necessary in all situations. For example, a loop without initialization or increase (equivalent to a while-loop) is for (;n10;++n); whereas a loop with increase but no initialization is for (;n10;++n) (maybe because the variable was already initialized before the loop). A loop that has no condition is the same as a loop that has true as a condition (i.e., an infinite loop).

Because each of the fields is run at a different point in the loop’s life cycle, it’s possible to utilize more than one expression as an initialization, condition, or statement. Unfortunately, because these are simple expressions rather than statements, a block cannot be used to replace them.

They can, however, employ the comma operator (,) as an expression separator, which allows them to separate many expressions where only one is normally anticipated. For example, a for loop may use it to handle two counter variables, initializing and increasing them both:

If neither n nor I are changed during the loop, the loop will run 50 times:

n begins with a number of 0 and I with a value of 100. The condition is n! =i= (i.e., that n is not equal to i). The loop’s condition will become false after the 50th iteration, when both n and I are equal to 50, because n is increased by one and I is decreased by one on each iteration.

Range-based for loop

The for-loop has a different syntax that is only used with ranges:

This type of for loop loops through all of the elements in range, where declaration declares a variable that can accept the value of any element in the range.

Ranges are collections of items, such as arrays, containers, and any other type that supports the begin and end functions; the majority of these kinds have yet to be covered in this tutorial, but we are already familiar with at least one form of range: strings, which are character sequences.

Using strings as an example of a range-based for loop:

// range-based for loop
#include
#include
using namespace std;

int main ()
{
string str {“Hello!”};
for (char c : str)
{
cout << "[" << c << "]"; } cout << '\n'; }

Output:

The declaration of a char variable comes before the colon (:) in the for loop (the elements in a string are of type char). The value of each element in the range is then represented by this variable, c, in the statement block.

This loop is self-contained and does not necessitate the declaration of any counter variables.

In most range-based loops, type deduction is used to determine the type of the items with auto. The range-based loop described above can also be written as:

The type of the items in str is automatically derived as the type of c.

Jump statements

Jump statements allow you to change the flow of a program by jumping to certain places.

Break statement

Even if the requirement for the loop’s termination is not met, break creates one. It can be used to break an infinite loop or cause it to terminate sooner than it would otherwise. Let’s say we want to stop the countdown before it reaches its natural conclusion:

// break loop example
#include
using namespace std;

int main ()
{
for (int n=10; n>0; n–)
{
cout << n << ", "; if (n==3) { cout << "countdown aborted!"; break; } } }

Output:

Continue Statement

The continue statement instructs the computer to skip the rest of the loop in the current iteration, as if the statement block’s end had been reached, and jump to the beginning of the next iteration. Let’s take number 5 in our countdown as an example:(C++ Control Statement: The Complete Guide For Beginners 2022)

// continue loop example
#include
using namespace std;

int main ()
{
for (int n=10; n>0; n–) {
if (n==5) continue;
cout << n << ", "; } cout << "itsourcecode!\n"; }

Output:

Goto statement

Goto allows you to jump to a specific point in the program. This unconditional jump is unaffected by nesting levels and does not result in stack unwinding. As a result, it’s a feature to utilize with caution, preferably within the same block of statements, especially if local variables are present.

A label identifies the destination point, which is subsequently passed as an argument to the goto command. A valid identification is followed by a colon in a label (:).

goto is considered a low-level feature, with no specific use cases in modern higher-level programming paradigms such as C++. But, as an example, here’s a goto-based version of our countdown loop:

// goto loop example
#include
using namespace std;

int main ()
{
int n=10;
mylabel:
cout << n << ", "; n--; if (n>0) goto mylabel;
cout << "itsourcecode!\n"; }

Output:

Another selection statement: switch.

The switch statement’s syntax is a little strange. Its goal is to find a value among a set of potential constant expressions. It’s like concatenating if-else statements, but it’s only for constant expressions. The most common syntax is:

switch (expression)
{
case constant1:
group-of-statements-1;
break;
case constant2:
group-of-statements-2;
break;
.
.
.
default:
default-group-of-statements
}

Switch examines expression and checks if it is equivalent to constant1; if it is, group-of-statements-1 is executed until the break statement is found. The software jumps to the end of the switch statement when it sees this break statement (the closing brace).(C++ Control Statement: The Complete Guide For Beginners 2022)

If expression does not equal constant1, it is compared to constant 2. If it equals this, group-of-statements-2 is executed until a break is discovered, at which point it skips to the end of the switch.

Finally, if the value of expression does not match any of the previously provided constants (which could be any number), the program performs the statements after the default: label, if it exists (since it is optional).

Both of the following code segments, which demonstrate the if-else equivalent of a switch expression, have the identical behavior:

The Switch example:

switch (x) {
case 1:
cout << "x is 1"; break; case 2: cout << "x is 2"; break; default: cout << "value of x unknown"; }

The if-else equivalent

if (x == 1) {
cout << "x is 1"; } else if (x == 2) { cout << "x is 2"; } else { cout << "value of x unknown"; }

Because it employs labels instead of blocks, the switch statement has a strange syntax that dates back to the early days of C compilers. Break statements are required after each group of statements for a particular label in the most common application (see above).

All statements after the case (including those under any other labels) are likewise executed until the end of the switch block or a jump statement (such as break) is reached if break is not specified.(C++ Control Statement: The Complete Guide For Beginners 2022)

If there was no break statement after the first group for case one in the preceding example, the program would not immediately move to the end of the switch block after printing x is 1, instead continuing to execute the statements in case two (thus printing also x is 2).

It would then do so until a break statement or the end of the switch block was found. This eliminates the need for brackets around the statements for each case, and it can also be beneficial to run the same set of statements for different possible values.

Consider the following example:

switch (x) {
case 1:
case 2:
case 3:
cout << "x is 1, 2 or 3"; break; default: cout << "x is not 1, 2 nor 3"; }

Switch can only compare its evaluated expression to labels that are constant expressions, as you can see. Because variables aren’t acceptable C++ constant expressions, they can’t be used as labels or ranges.

It is preferable to use concatenations of if and else if statements to check for ranges or values that are not constant.

Summary

A C++ Control Statement: The Complete Guide For Beginners 2022 changes the flow of a program so that more code can be executed. A simple C++ statement is each of a program’s individual instructions, such as the variable declarations and expressions discussed previously.

C++ includes flow control statements for this purpose, which specify what our program must do, when it must do it, and under what conditions.

A generic (sub)statement is required in many of the flow control statements discussed in this section.
This statement can be either a simple C++ statement or a compound statement, such as a single instruction followed by a semicolon (;).

Related Articles

Inquiries

If you have any questions or suggestions about C++ Control Statement: The Complete Guide For Beginners 2022, please feel free to leave a comment below.

Leave a Comment