Control Statements in C++ Language with Examples

A C++ control statement changes the flow of a program so that more code can be executed. Conditionals (if-else, switch statement) and loops are examples of these group 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 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.

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:

{ statement1; statement2; statement3; }

The whole block is treated as a single statement (composed itself of multiple times sub-statements). 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 0 Boolean value based on certain condition is false.

Some comparison operators, such as == and!, are used 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. It 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)

If and else statements are examples of selection statements.

If-else statements allow the program to run different sections of code based on a conditional statement. The following is the format of all if statements:

 if ( condition ) {
        //body
    }

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

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:

if (x == 100)
  cout << "x 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:

if (x == 100)
{
   cout << "x is ";
   cout << x;
}

The indentation and line break statement does not affect the code hence the above code is equivalent to:

if (x == 100) { cout << "x is "; cout << x; }

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.

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:

while (expression) statement
// custom countdown using while
#include <iostream>
using namespace std;

int main ()
{
  int n = 10;

  while (n>0) {
    cout << n << ", ";
    --n;
  }

  cout << "itsourcecode!\n";
}

Output:

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, itsourcecode!

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.

Do-While Loop

The do-while loop has the following syntax:

do statement while (condition);

It behaves similarly to a while-loop, except that the condition is evaluated after rather than before the execution of the statement, ensuring that the statement is executed at least once, even if the 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:

Enter text: hello
You entered: hello
Enter text: who's there?
You entered: who's there?
Enter text: goodmorning
You entered: goodmorning

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.

For Loop

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

for (initialization; condition; increase) statement;

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

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:

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, itsourcecode!

They can, however, employ the comma operator (,) as an expression separator, which allows them to separate many expressions where only one is normally anticipated.

Range-based for loop

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

for ( declaration : range ) statement;

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.

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:

[H][e][l][l][o][!]

Summary

A Control Statements in C++ changes the flow of a program so that more code can be executed.

A simple C++ statement is each program’s individual instructions, such as the variable declarations and expressions discussed previously.

Related Articles

Leave a Comment