C++ from the beginning - control flow

softchris

Chris Noring

Posted on November 11, 2021

C++ from the beginning - control flow

TLDR; this is a part of the series C++ for beginners, this part ia about control flows, the execution path taken through your program using constructs like if, else, for and while.

Resources

 What is control flow and why should I care

A control flow is the order in which the instructions are executed. Consider the below code:

int main() 
{
  int value = 3;
  cout << value;
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

In this example, we have a main(). The code will be executed from top to bottom, first the declaration of value, followed by the call to cout, to print the value and lastly to return statement.

However, sometimes you want to change that flow, so it's not top to bottom. The reason for wanting that is that you might have a condition in your code that says execute these statements instead of that, or you might want to repeat a set of statements.

Let's look at how you can control the flow with if next up.

If, a new execution path

By using if, you can declare in the code that if a certain condition holds true, then the code should do something different. Typically, your if constructs looks like so:

if(condition) 
{
  // do something
}
Enter fullscreen mode Exit fullscreen mode

The if construct wrapt a bool condition within parenthesis and uses curly braces to define what should happen if the condition evaluates to true. Here's an example:

cout << "Welcome to your account\n";
int account_balance = 0;
if(account_balance > 0) 
{
  cout << "You can withdraw money"; 
}
Enter fullscreen mode Exit fullscreen mode

Where we to run this code, it would only print "Welcome to your account" as account_balance > 0 is false. To change that, we can modify account_balance and set it to 10 for example:

cout << "Welcome to your account\n";
int account_balance = 10;
if(account_balance > 0) 
{
  cout << "You can withdraw money\n"; 
}
Enter fullscreen mode Exit fullscreen mode

Now your code would print:

Welcome to your account
You can withdraw money
Enter fullscreen mode Exit fullscreen mode

What you saw here account_balance > 0, is a boolean expression, you could just replace it with the values true or false.

 Else, then what to do

So far, we looked at using if, there's also else. else expresses that if the boolean expression for if is false, then else will be run. Therefore, else can't exist without if.

To use else, you place it right after the if, it doesn't need a boolean expression. Let's modify the code from before to incorporate else:

cout << "Welcome to your account\n";
int account_balance = 10;
if(account_balance > 0) 
{
  cout << "You can withdraw money\n"; 
}
else 
{
  cout << "No money, you can' withdraw\n";
}
Enter fullscreen mode Exit fullscreen mode

With our addition of else, we know have another execution path, it will run if or else. Given the code above, it will run the if, let's change that:

cout << "Welcome to your account\n";
int account_balance = 0;
if(account_balance > 0) 
{
  cout << "You can withdraw money\n"; 
}
else 
{
  cout << "No money, you can't withdraw\n";
}
Enter fullscreen mode Exit fullscreen mode

If you run this, your program will say:

Welcome to your account
No money, you can't withdraw
Enter fullscreen mode Exit fullscreen mode

You might have another case, if you think about it, what if you balance is negative, that can happen. Looks look at that next with else if.

 Else-If, if if fails

Ok, so you have another condition that you want to test if if fails and it's a specific one, like checking for a negative balance? Great, that's when you should use else if. Like if, else if takes a condition within parenthesis. Also, just like else, it can't exist without if. Here's how we can modify our code to incorporate else if:

cout << "Welcome to your account\n";
int account_balance = -10;
if(account_balance > 0) 
{
  cout << "You can withdraw money\n"; 
}
else if(account_balance < 0)
{
  cout << "You are overdrawn, please top up the balance to at least 0\n";
}
else 
{
  cout << "No money, you can't withdraw\n";
}
Enter fullscreen mode Exit fullscreen mode

Where you to run this code, you would now get this output:

Welcome to your account
You are overdrawn, please top up the balance to at least 0
Enter fullscreen mode Exit fullscreen mode

As you can see, the else if is being hit. This program now has three different paths through it, if, else if and else.

 Loop constructs, repeat instructions

if, else if and else is way to make your code create different execution paths. Sometimes however, your code needs a different behavior, it needs to repeat a behavior until a condition is fulfilled. Take an example where you want to keep the user in the program as long as they enter valid commands and only quit when the typed command equals the phrase "quit". Or imagine that you have an array of values, and you need to summarize them. In both these cases, you need a loop construct, albeit different types of loop constructs.

Let's look at the first one while.

While, repeat until false

With while, you express that you want to repeat a set of instructions until false. Let's take the below code for example:

int value = 3;
while(value < 5) 
{
  value++;
}
cout << "Value is" << value; // prints 5
Enter fullscreen mode Exit fullscreen mode

The above will repeat this loop two times, as the first time, value will be 3 and incremented to 4. Next iteration, 4 will be incremented to 5. The last time, it will fail the check as the value is 5.

Here's another example, that you can use to create command-based console programs:

string user_input = "";

while(true)
{
  cout << "Type a command: ";
  getline(cin, user_input);
  if(user_input == "quit") 
  {
    break;
  }
  cout << "You typed: " << user_input;
  if(user_input == "hello") 
  {
    cout << "Greetings";
  } else {
    cout << "Unknown command: " + user_input; 
  }
  // add command definitions here
}
cout << "Bye";
Enter fullscreen mode Exit fullscreen mode

A possible program execution of the above could be:

> Type a command: hello
> Greetings
> Type a command: help
> Unknown command: help
> Type a command: quit
> Bye
Enter fullscreen mode Exit fullscreen mode

Note the use of break in this code:

if(user_input == "quit") 
{
  break;
}
Enter fullscreen mode Exit fullscreen mode

Calling break while stop the loop from looping.

for, when you know more about what you loop

There's another looping construct that it's good to know about, for. for, just like while allows you to repeat instructions until a condition is met. Where it differs is that with a for loop, you have additional concepts, an index variable that keeps track of starting point, a comparison point and increment point. Here's an example:

// will print values 0-9
for(int i=0; i< 10; i++) 
{
  cout << i;
}
Enter fullscreen mode Exit fullscreen mode

There are three parts here:

  • int i = 0, this is where you initialize a variable
  • i < 10, for every iteration, the loop construct will test this comparison, if it results in false then looping will stop
  • i++, this is where i++ gets incremented for every iteration.

A more real example can be iterating a set of records, let's say actions on a bank account:

vector<int> transactions;
transactions.push_back(100);
transactions.push_back(-50);
transactions.push_back(-25);
transactions.push_back(50);
int sum = 0;
for (vector<int>::size_type i = 0; i < transactions.size(); i++)
{
  sum += transactions[i];
}

cout << "Your account balance is: " << sum;
Enter fullscreen mode Exit fullscreen mode

transactions are being iterated over, and for each item in its collection, the value is added to sum.

Summary

You've learned about if, else if and else. These constructs are used to create different execution paths in your program. Your code will select one of these paths. Additionally, you were told about while and for loops that's used to repeat instructions. for is different from while as you have the idea of a variable that keeps tracks of what looping iteration you are on.

💖 💪 🙅 🚩
softchris
Chris Noring

Posted on November 11, 2021

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

Sign up to receive the latest update from our blog.

Related

C++ Урок #2
cpp C++ Урок #2

March 6, 2024

Insertion sort in C++
cpp Insertion sort in C++

February 29, 2024

C++ Pointers
programming C++ Pointers

November 19, 2023

C++ Operatorlar.
cpp C++ Operatorlar.

March 1, 2023