Conditionals and Loops
Learn the fundamentals of controlling program flow in C++ using if statements, for loops, while loops, continue, and break
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 are 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.
Intro to C++ Programming
Become a software engineer with C++. Starting from the basics, we guide you step by step along the way
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 also 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 in which they are used:
#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 Loops
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 << ' ';
}
}
1 2 3 4 5 6 7 8 9 10
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++ << ' ';
}
}
1 2 3 4 5 6 7 8 9 10
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++ << ' ';
}
}
1 2 3 4 5 6 7 8 9 10
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);
}
1 2 3 4 5 6 7 8 9 10
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!
Skipping Loop Iterations 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 << ' ';
}
}
1 2 4 5 6 7 8 9 10
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;
}
}
1 2 3 4 5 6 7 8 9 10
Summary
In this lesson, we explored the fundamentals of conditionals and loops in C++. These constructs allow you to control the flow of your program based on specific conditions and repeat blocks of code as needed. Key takeaways:
- C++ provides if, else if, else, and switch statements for conditional execution
- Ternary operators offer a concise way to make simple conditional assignments
- Short-circuit evaluation optimizes compound boolean expressions
- for, while, and do-while loops enable repeated execution of code blocks
- The continue keyword skips the current loop iteration, while break terminates the loop entirely
Classes, Structs and Enums
A crash tour on how we can create custom types in C++ using classes, structs and enums