Conditionals and Loops

A quick introduction to conditionals and loops in C++, and how we can use them to control how our program executes
This lesson is part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

a52.jpg
Ryan McCombe
Ryan McCombe
Posted

This lesson is a quick introductory tour of loops within C++. It is not intended for those who are entirely new to programming. Rather, the people who may find it useful include:

  • those who have completed our introductory course, but want a quick review
  • those who are already familiar with programming in another language, but new to C++
  • those who have used C++ in the past, but would benefit from a refresher

It summarises several lessons from our introductory course. Anyone looking for more thorough explanations or additional context should consider Chapter 2 of that course.

Previous Course

Intro to Programming with C++

Starting from the fundamentals, become a C++ software engineer, step by step.

Screenshot from Cyberpunk 2077
Screenshot from The Witcher 3: Wild Hunt

Conditionals

The implementation of conditionals and loops in C++ is going to be very comfortable for those coming from other languages. The syntax is likely to be very similar

We have the normal if, else if, and else statements:

int Health{100};

if (Health > 50) {

} else if (Health > 25) {

} else {

}

We have access to ternary statements:

Health > 50 ? DoSomething() : DoSomethingElse();

Finally, we have the typical switch statements. C++ switch statements include “fallthrough” behavior, which we can control using break:

int Number{3};
switch (Number) {
  case 1:
    std::cout << "One";
    break;
  case 2:
    std::cout << "Two";
    break;
  case 3:
    std::cout << "Three";
    break;
  default:
    std::cout << "Something else";
}
Three

Short Circuit Evaluation

C++ short circuits evaluation of compound boolean expressions. This means once the result of a boolean is known, any further conditionals within that expression are skipped.

As an example of this, the following program does not log anything. The std::cout operations are not executed, because they will not change the result of the boolean expression:

#include <iostream>

int main(){
  // The result will be true
  true || std::cout << "Hi";

  // The result will be false
  false && std::cout << "Hi";
}

This can situationally be used as a terse alternative to an if statement:

#include <iostream>
bool ShouldLog{true};

int main(){
  ShouldLog && std::cout << "Hi";
};
Hi

Or as an alternative to a series of if-else statements:

#include <iostream>

bool Log1(){
  return false;
};

bool Log2(){
  std::cout << "Hi from Log2";
  return true;
};

bool Log3(){
  std::cout << "Hi from Log3";
  return true;
};

int main(){
  Log1() || Log2() || Log3();
}
Hi from Log2

Loops

We have the usual 3 looping options that may be recognized from other programming languages: for, while, and do while.

For Loop

A for loop contains three expressions, separated by semicolons:

  • An expression to execute at the start of the loop, used to initialize some state if required
  • An expression that returns a boolean, indicating whether the loop should continue
  • An expression that will run at the end of each iteration of the loop

A typical form of a for loop is below, which will log out the numbers from 1 to 10:

#include <iostream>

int main(){
  for (int i{1}; i <= 10; ++i) {
    std::cout << i;
  }
}
12345678910

Each expression is optional. Below, we provide only the middle expression, which controls whether the loop should continue. We still need to include two semicolons in the appropriate place, to clarify which expressions we’re providing:

#include <iostream>

int main(){
  int i{1};
  for (; i <= 10;) { std::cout << i++; }
}
12345678910

While Loop

A while loop accepts a single expression, which determines whether the loop should continue:

#include <iostream>

int main(){
  int i{1};
  while (i <= 10) {
    std::cout << i++;
  }
}
12345678910

Do While Loop

A do-while loop has a similar syntax to a while loop, except the conditional is moved to after the block:

#include <iostream>

int main(){
  int i{1};
  do {
    std::cout << i++;
  } while (i <= 10);
}
12345678910

The key difference with a do while loop is that it will always run at least once, even if the boolean that controls the loop is initially false.

#include <iostream>

int main(){
  do {
    std::cout << "I'm running anyway!";
  } while (false);
}
I'm running anyway!

For-Each Loops and Container Iteration

Those coming from other languages are likely to be familiar with a dedicated way to iterate over the objects in containers like arrays and sets.

C++ includes these techniques too, which we’ll cover in dedicated sections later in this course.

Skipping Loops using continue

The continue keyword skips over the current loop iteration. Below, we use it to omit 3 from our logging:

#include <iostream>

int main(){
  for (int i{1}; i <= 10; ++i) {
    if (i == 3) continue;
    std::cout << i;
  }
}
1245678910

Ending Loops using break

The break keyword ends our loop entirely. Below, we use it to stop looping once an integer becomes larger than 10:

#include <iostream>

int main(){
  int i{1};
  while (true) {
    std::cout << i++;
    if (i > 10) break;
  }
}
1245678910

Was this lesson useful?

Edit History

  • — First Published

Ryan McCombe
Ryan McCombe
Posted
This lesson is part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Whirlwind Tour of C++ Basics
7a.jpg
This lesson is part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access!

This course includes:

  • 106 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Next Lesson

Classes, Structs, and Enums

A crash tour on how we can create custom types in C++ using classes, structs and enums
7d.jpg
Contact|Privacy Policy|Terms of Use
Copyright © 2023 - All Rights Reserved