Introduction to C++
In this enrichment, you will be learning the C++ programming language. C++ is a popular, fast, object-oriented programming language created by Bjarne Stroustrup in 1983 as an extension to the C parogramming language. C++ can be extended by a large number of community- and business-provided software libraries, and is quite versatile. This enrichment will not teach you how to use any of these libraries, rather, it will give you the base skills you need to understand C++ code and C++'s standard library. Hopefully, this enrichment will teach you all of the tools you need to learn new programming languages and/or use more advanced libraries that work with C++.
In this page:
Your first program
Without further ado, here is your first C++ program!
#include <iostream> using namespace std; int main () { cout << "Hello, world!" << endl; return 0; }
OK, let's break it apart, line by line:
#include <iostream>
This line is asking the compiler to "include" the iostream
header file in your source file.
Header files contain definitions for a number of already-implemented functions and/or objects that you will find useful.
The contents of a header file are always related. For example, iostream
contains definitions for stream objects that allow you to print
text to the console and read user input.
What the #include
operation essentially does is paste the entire contents of the specified header file into your source file before compilation
(NEVER do this manually. ALWAYS #include
), which allows you to use all of the functionality provided by that header file in your source code. How handy!
This line is a bit different from most of the commands you will use in C++. You will notice that it begins with a pound sign -- that means it is a preprocessor instruction, or an instruction to the part of the compiler that runs before it actually starts analyzing your code. As such, it does not need a trailing semicolon (as described in the next line's explanation).
using namespace std;
This is an instruction telling the compiler that you will be using a lot of functions and/or objects from the std
namespace.
Everything in the C++ standard library is written into the std
namespace, so this saves you the trouble of having to explicitly state
the std
namespace every time you want to use something from the standard library.
Note that this line ends in a semicolon. Almost all statements in C++ end in semicolons -- the semicolon is kind of like the "end of sentence" character, telling the computer
that the current statement has finished. If you forget a semicolon where it is needed, the compiler will throw an error!
Always make sure that you are ending your statements with semicolons. (The #include
line does not need a semicolon, because it is an instruction to the )
int main() {
This defines a function called main
that takes no arguments.
You will learn more about functions later in the enrichment, but for now, think of this as the "signpost" to the computer that says
"Hey! My code starts here." The opening curly brace defines the start of the function body,
which are a series of statements that will be executed when main
is executed.
Since this is defining the structure of your program, this line does not need a semicolon at the end.
cout << "Hello, world!" << endl;
This line tells the computer to print the text "Hello, world!" (without the double quotes) to the screen, and then begin a new line (endl
).
More specifically, cout
is a stream object that sends any values input into the stream to the screen.
Conceptually, you can think of it as a river that flows in the direction of the screen. You can place a number of things in the river (text, numbers, etc.),
they will all eventually reach the screen.
You can chain the stream insertion operator (<<
) to put more things in the stream; for example you could also write:
cout << "Hello," << "world!" << endl;
which would produce the same exact output, except the text "Hello," and "world!" are passed separately to the stream instead of as one value. This will come in handy later when you start to use variables.
cout
and endl
are objects provided in the standard library, so theyt belongs to the std
namespace.
If we had forgotten our using namespace std;
instruction at the beginning, the compiler would not know to look in the std
namespace, so it
would error out, complaining that it couldn't find cout
or endl
. As mentioned before, you can get around this by explicitly stating that
these objects come from the std
namespace:
std::cout << "Hello, world!" << std::endl;
Moving on:
return 0;
This is the function's return statement, which essentially tells the computer to stop executing the main
function.
We will get into more detail about what the return statement actually does when we learn about functions. For right now, think of this line as the program
telling the computer "I'm done now, and I didn't have any errors while I was running." When this line executes, the computer's operating system will terminate
the process and clean up any memory it was using.
Technically, this is required in every C++ program. Some compilers will let you get away without having this line at the end of your main
function,
however, it is generally considered bad practice. Make sure that you are always including this line at the end of your program.
}
Finally, we have the closing brace for main
's function body. This tells the compiler that main
does not have any more code after this point.
It may be hard to see why this is necessary at this point, but when we discuss functions in more detail, the reason for this should become clearer.
And that's it! This program, when executed, will simply print the text "Hello, world!" to the screen and quit. Before we proceed to the guided exercise for this section, let's add one more thing:
#include <iostream> using namespace std; /* My very first C++ program! Written by me, Paul. I can write comments on multiple lines */ //Single-line comment int main () { cout << "Hello, world!" << endl; //prints "Hello, world!" return 0; }
What you see above are comments. When the compiler sees these, it will ignore everything in the comment and continue parsing your code after the end of the comment. Comments are a very useful tools for programmers to communicate what their code does, or take notes on particular parts of the code directly in the source. Comments are also commonly used to render sections of code inert without removing them from the source code. I highly recommend that you use comments to keep track of your own understanding of the source code, or to temporarily disable parts of your code.
Shown above are a multi-line comment (/* comment here */
) and two single-line comments (//comment here
). A multi-line comment can break onto multiple lines,
as long as it begins with a /*
and ends with a */
. A single-line comment will comment out everything from the comment mark (//
) until the end of the line;
the compiler will begin parsing code on the following line (unless that line starts with a comment itself).
Now, let's try changing some more things with this code.
Guided exercise
Create a new C++11 REPL in repl.it, and copy the Hello World program from above into your REPL (be sure not to copy the line numbers). Before you do anything, just run the program to see it in action. Then, modify the program to do the following:
- Print the text "Guten tag!" instead of "Hello, world!"
- Print the text "I am a jelly doughnut" five times, each on its own line.
- Print the number 42 to the screen. Remove the double quotes around the 42. Why does this still work?
- Remove the
using namespace std;
line from the code and modify the calls tocout
andendl
so that it compiles and runs. Do you notice any change in functionality? - Add a single-line comment and a multi-line comment to your code.
Variables
So, this is cool! However, all it does is print text to the screen; we have to modify the source and recompile it every time we want to change what it says. That's really inconvenient! Enter variables.
A variable is not too different from a variable that you might use in algebra. It is some value to which you give an arbitrary name. However, variable names in C++ (and any programming language, for that matter) do not need to be single letters; in C++ they can be of any length and contain numbers, letters, or underscores (_); however, the first character in a variable name must not be a number.
Let's add a variable to our Hello, World program:
#include <iostream> using namespace std; int main () { int foo = 42; cout << "Hello, world!" << endl; return 0; }
What we just added is called a variable declaration. It tells the compiler that we want to make a new variable named foo
to use at some point in the future.
Let's break this apart: first, we have the keyword int
, which specifies the data type of the variable, or what kind of data the variable will hold.
This tells the compiler that we want the data type of this this variable to be an integer, or any non-fractional negative or positive number.
(There are limits on the largest/smallest value an int
can store, but they are sufficiently large for our purposes). Now, we've given our variable the name foo
and
assigned it the value 42
. From this point forward, we can use the name foo
to retrieve the value we stored (42
). So, we might modify the program as such:
#include <iostream> using namespace std; int main () { int foo = 42; cout << "Hello, world!" << endl; cout << "My favorite number is " << foo << endl; return 0; }
Hello, world!
My favorite number is 42
Our variables don't just have to be integers; here is a list of some basic variable data types:
int
- As we have already seen, this is an integer, or any positive or negative value without a fractional part.
double
- This is a positive or negative number, but this can handle any real number (to a degree of precision). The term "double" refers to the amount of storage this data type uses.
bool
- This is a single true/false value. You can use the keywords
true
andfalse
to set its value. char
- This is a single character (like '
a
' or '$
'). You can specify characters in your code by using single quotes (e.g.char c = 'C';
). string
- This is an arbitrary sequence of characters (like
Hello, world!
). You can specify strings in your code by using double quotes (e.g.string str = "Hello, world!";
). Note that you must have#include
d eitheriostream
orstring
for this to be accessible.
So, we can do the following:
#include <iostream> using namespace std; int main () { string mystr = "HelloWorld"; double pi = 3.14159265358979323846; int foo = 42; bool bar = true; char c = '#'; cout << c << mystr << endl; //cout does not put spaces between values, so you have to do it manually cout << foo << ' ' << pi << endl; /* by default, cout will print a bool as '0' or '1' instead of 'false' or 'true', respectively; boolalpha changes that behavior */ cout << boolalpha << bar << endl; return 0; }
#HelloWorld
42 3.14159265358979323846
true
You do not need to set variables when you declare them, and you can set them at any point after you declare them. Note that you do not need to specify the data type after you've declared the variable:
#include <iostream> using namespace std; int main () { string mystr; double pi = 3.14159265358979323846; int foo = 42; bool bar = true; char c = '#'; mystr = "ProgrammingIsCool"; foo = -7; //this overrides 42. foo now contains -7. cout << c << mystr << endl; //cout does not put spaces between values, so you have to do it manually cout << foo << ' ' << pi << endl; /* by default, cout will print a bool as '0' or '1' instead of 'false' or 'true', respectively; boolalpha changes that behavior */ cout << boolalpha << bar << endl; return 0; }
#ProgrammingIsCool
-7 3.14159265358979323846
true
You can also do math on numeric data types. You can use the following operators:
+
- Addition. Example:
3 + myInt
-
- Subtraction. Example:
pi - 2.718
*
- Multiplication. Note that you need to use this operator when you want to multiply,
you cannot just put two variable names next to each other like you would in math.
Example:5 * e
/
- Division. Example:
bar / 2
Note that, if you give the division operator two integers, it will perform integer division. This means it will calculate the quotient without the fractional part, which sometimes is sometimes unexpected. If you want to divide two integers and get a double as a result, you will need to express the division as a division of doubles, like5./9.
(without the trailing dot on at least one of the numbers, this would result in a 0). ++
- Increment, or increase the value by 1. This is a unary operator (only has one argument), and only works on variables.
Example:++foo
orfoo++
There is a difference between the two above forms, however, for our purposes here they do effectively the same thing. The first form is almost always preferred. --
- Decrement, or decrease the value by 1. This is a unary operator, and only works on varaibles. Example:
--foo
orfoo--
.
There are also compound assignment operators, which use the current value of the variable as the first operand in the operation and the provided value as the second, and then store the result in the variable:
- +=
- Addition compound assignment. Example:
foo += 5
computesfoo + 5
and stores the result infoo
. - -=
- Subtraction compound assignment. Example:
bar -= 2.718
computesbar - 2.718
and stores the result inbar
. - *=
- Multiplication compound assignment. Example:
baz *= 42
computesbaz * 42
and stores the result inbaz
. - /=
- Division compound assignment. Example:
foo2 /= 4.5
computesfoo2 / 4.5
and stores the result infoo2
.
You can also use parentheses to define order of operations, just like you would in math. Here is a program using some of the math operators:
#include <iostream> using namespace std; int main () { double degF; double degC; degF = 59; --degF; degC = degF - 32; degC *= (5./9.); //5. and 9. to make sure we get the fraction 5/9, not 0 cout << degF << "F is " << degC << "C."; return 0; }
58F is 14.4444C.
It is important to note that you cannot mix and match data types. For example, you cannot do the following:
int foo = "Hello, world!"
The compiler would throw an error on this, because you are trying to assign string data to an integer; in other words you are violating the data type of foo
.
int f = 'f';
or int e = 2.718
). In this case, the compiler is still not letting you violate the type, rather, it is actually
converting the type on the right to the type on the left. In the former case, 'f'
gets converted to its ASCII value, 102, and in the latter case 2.718
gets truncated -- not rounded -- to 2. The compiler does not allow conversions from a string
to an int
because there is no such conversion that is sensible.
As a general rule of thumb, do not rely on type conversions to exist -- always make sure that you are assigning the appropriate data type to your variables.Guided exercise
In the same REPL as before, add at least variable of each type listed above and print each of them to the screen. Also, do the following:
- Compute the circumference of a circle with radius 2.718. Make sure the radius is stored in its own varaible. The formula for circumference is c = 2πr. You can copy the declaration for π from above.
- Increment an integer.
- Decrement a double.
- Increment a char. What did this do? (Why?)
Input
So, we've seen how to use variables, but we're still only setting the values in the source itself -- what if we want the user to input the variables' values instead? This is where input comes into play.
You might remember cout
from the introductory program that you wrote. It was basically a stream that flowed from your program to the console screen.
Well, there is another stream object that takes input from the keyboard and brings it to your program, called cin
. Let's see it in action:
#include <iostream> using namespace std; int main () { double degF; double degC; cout << "Please input the degrees Fahrenheit: "; cin >> degF; degC = degF - 32; degC *= (5./9.); //5. and 9. to make sure we get the fraction 5/9, not 0 cout << degF << "F is " << degC << "C."; return 0; }
So, we see cin >> degF
on line 9. This will make your program stop and wait (or, more technically, "block") until the user inputs a value.
It will then attempt to store that user input into the variable degF
. From that point forward, degF will contain the value that the user input on line 9 (until it is overwritten).
Note that with cin
we're using a >>
operator instead of a <<
operator -- this is because the direction of the stream is in the opposite direction.
Like cout
, we can chain the extraction operator (>>
) to grab multiple values from the user:
#include <iostream> using namespace std; int main () { double a, b; //declare a and b on the same line cout << "Please input two numbers, separated by a space: "; cin >> a >> b; cout << (a + b) << endl; return 0; }
This program would ask the user for two double
s, and then print their sum. The program can tell a
and b
apart as follows:
a
was input beforeb
.- The user put whitespace (space or enter) between the values
a
andb
.
But what if we didn't input a number? What if we typed Mwhahahaha! into the program where it was expecting a double
?
Well, if you tried this, you would see the program spaz out, repeatably and unstoppably printing the last prompt.
What happened here is the cin
stream object sees that the value Mwhahahaha! is not a double, so it continues looking through its own internal buffer for a double.
When it does this, it doesn't find a double, so it looks at the buffer again...infinite loop!
Do not worry about handling this case for now, all we want to do at the moment is just grab input from the user.
Guided exercise
Copy the Hello, World code from before, but make the following changes:
- Before printing the
Hello
line, ask the user for their name (Note: you will need to print something to the screen to indicate to the user that they need to type something in!) - Instead of printing
Hello, world!
, printHello, $user!
, where$user
is the name that the user just entered (e.g. if the user enters Paul, it would printHello, Paul!
). - After printing
Hello, $user!
, ask the user for two numbers. After the user has input the two numbers, add them and display the sum on the screen.
if-else
statements
So far, we've seen how to store data, print it to the screen, and how to retrieve data from the user. But, we still haven't been able to make decisions with the data that we get from the user.
This is what if-else
statements are for.
First, let's just look at an if
statement by itself:
#include <iostream> using namespace std; int main () { double a; cout << "Please input a number: "; cin >> a; if (a < 0) { a = -a; } cout << "The absolute value of the number you entered is " << a << '.'; return 0; }
Let's start with the statement a < 0
.
<
is a comparison operator that will evaluate to true
if the left hand side
is less than the right hand side, and false
otherwise (i.e. it evaluates a bool
value).
Now, we place this statement in parentheses, following the keyword if
. After this, we open another code block
(code between the {
and }
symbols). This does basically what reads: if a
is less than 0,
then execute the following block of code. If a
is not less than 0, then the block of code will be skipped.
We used a comparison operator (<
), which implies that there are more comparison operators available.
All of C++'s comparison operators can be used to compare either variables or literals (or both),
as long as both sides are of the same type or can be converted to equivalent types.
All will evaluate to a bool
value (true
or false
) based on the truth
of the statement they represent. Here is a list of the available comparison operators:
<
- "Less than" operator. Checks if the left-hand side (LHS) is strictly less than the right-hand side (RHS). Example:
x < y
>
- "Greater than" operator. Checks if LHS is strictly greater than RHS. Example:
x > y
==
- "Equal to" operator. Checks if LHS is equal to RHS. Note that this operator has two equals signs, not one (one equals sign is used for assignment).
Example:
a == b
!=
- "Not equal to" operator. Checks if LHS is unequal to RHS. Example:
a != b
. <=
- "Less than or equal to" operator. Checks if LHS is less than or equal to RHS. Example:
x <= y
>=
- "Greater than or equal to" operator. Checks if LHS is greater than or equal to RHS. Example;
x >= y
Now, what if we wanted to check multiple conditions in the same if
statement?
We can combine boolean expressions (like a < 0
) using the AND (&&
)
and OR (||
) operators. When you AND two boolean expressions together, the result of the full compound expression
will be true only if both of the two expressions on either side are true (otherwise it will be false).
If you OR two boolean expressions together, the result will be true if either of the statements on either side
are true (one or both). Let's see an example:
#include <iostream> using namespace std; int main () { double a, b, foo; cout << "Please input two numbers: "; cin >> a >> b; foo = a + b; //if a is less than 0 AND b is less than 0 if (a < 0 && b < 0) { foo = a - b; //overwriting foo } //if foo is less than or equal to 32 OR foo is greater than or equal to 52 if (foo <= 32 || foo >= 52) { cout << "Your number is outside of +/-10 of my number." << endl; } cout << "Your number is " << foo << endl; return 0; }
Note: the |
symbol can be typed with Shift + \ (it is the vertical bar on the backslash key on most keyboards).
Above, we see that if both a
and b
are negative, then foo
will contain a - b
;
otherwise foo
will contain a + b
. Then, if foo
is less than or equal to 32 or foo is greater than 52,
we will print the text Your number is outside of +/-10 of my number.
Additionally, there is another operator that is useful when dealing with if
statements --
the !
or unary NOT operator. This operator allows you to invert the truth value of the statement it precedes. For example:
!(a < b && x > y)
If a
is less than b
and x
is greater than y
, then this statement will evaluate to false
.
Otherwise, it will be true
.
Now, what if you wanted to do something in the event the if
statement evaluated to false
? This is where you use an else
:
#include <iostream> using namespace std; int main () { double a, b, foo; cout << "Please input two numbers: "; cin >> a >> b; if (a < 0 && b < 0) { foo = a - b; } else { foo = a + b; } if (foo <= 32 || foo >= 52) { cout << "Your number is outside of +/-10 of my number." << endl; } else { cout << "Your number is within +/-10 of my number." << endl; } cout << "Your number is " << foo << endl; return 0; }
Now, we see that lines 13 and 19 will execute if the if
statements on lines 10 and 16 (respectively) fail. Now, when the user enters a number that is inside of 42±10, they
will see the message Your number is within +/-10 of my number.
You can chain if
and else
statements to produce a number of mutually-exclusive options:
#include <iostream> using namespace std; int main () { double a, b, foo; cout << "Please input two numbers: "; cin >> a >> b; /* Only one of the three code blocks below will run. Note that if the first case is true (both a and b are negative), then it does satisfy the second case (at least one is negative); however, only the first code block will run because the second case is preceded by an else. */ if (a < 0 && b < 0) { foo = a - b; } else if (a < 0 || b < 0) { foo = -a + b; } else { foo = a + b; } if (foo <= 32 || foo >= 52) { cout << "Your number is outside of +/-10 of my number." << endl; } else { cout << "Your number is within +/-10 of my number." << endl; } cout << "Your number is " << foo << endl; return 0; }
if
and else
blocks do not need to have enclosing curly braces if they only contain one statement. All of the following are valid:
if (a < b) foo = bar + baz; else foo = baz - bar; if (a < b) foo = bar + baz; else if (a == b) foo = bar - baz; else foo = baz - bar;
However, you MUST only have one line to do this, if you have multiple lines in your if statement, you will need enclosing curly braces:
if (a < b) { foo = bar + baz; baz = baz - foo; } else foo = baz - bar; bar = bar + foo; //this line will *always* execute, regardless of which case above gets executed! Don't let the whitespace fool you!
Fun fact: A bug exactly like the one above was introduced to Safari some time ago that made it accept the certificate of every site served over HTTPS, even if it was invalid. This led a number of Safari users to believe their connection was secure when in reality it may not have been secure (the bug has since been fixed).
Guided exercise
Using your modified Hello, World program from the Input section, make the following changes:
- Ask the user to choose between English and the language you chose to study at school (if you are studying a language that does not use the Latin alphabet, use the Latin transliteration). Make all output following that prompt in the user's chosen language (you can ignore accents and diacritics. Yes, I know it's incorrect, but just for simplicity's sake).
- Before asking the user to input the two numbers, ask them if they want to add, subtract, multiply, or divide. Do the operation specified by the user on the two numbers.
Print the result and one of the following:
- If the result is strictly less than 32 print "Solid"
- If the result is greater than or equal to 32 and strictly less than 212 print "Liquid"
- If the result is greater than or equal to 212 print "Gas"
Loops
Now that we have done if-else
statements, we have just one more type of control structure to cover: or loops.
There are two kinds of loops: for
loops and while
/do-while
loops.
Generally speaking, loops are what we call iterative structures; they iterate over the same code multiple times
until some condition (just like a condition we might use for an if
statement) is broken. Each pass of a loop is called an iteration.
for
loops
A for
loop runs a block of code for a determined number of times. Let's look at an example:
#include <iostream> using namespace std; int main () { for (int x = 0; x < 10; ++x) { cout << x << endl; } return 0; }
0
1
2
3
4
5
6
7
8
9
First, let's look at the for
loop syntax:
for (initialization; condition; increment)
The idea here is that we initialize a control variable for the loop, and then on every iteration, run the increment and condition statements on that control variable.
Let's look at each individual component of a for
loop:
- Initialization (e.g.
int x = 0
) - This statement is executed just before the loop begins, and is used to initialize the loop's control variable (when necessary, see below). You can use an existing variable as a control variable, but you can also declare one inline (as shown above). If you choose to declare the control variable inline, it will only exist inside the loop (see scoping).
- Condition (e.g.
x < 10
) - This condition is evaluated before each iteration. If it ever evaluates to
false
, the loop will exit without executing the next iteration. It is important to note that if the condition fails the first time it is checked (before the first iteration), the loop will exit immediately, and the loop body Note how our example code did not print the number10
-- this is because whenx
was set to10
, the condition failed, and the loop exited. - Increment (e.g.
++x
) - This statement is executed after each iteration, but before the condition for the next iteration is evaluated.
This is used to update the control variable between iterations. Note that although this is called the "increment" field of a
for
loop, you don't have to increment -- you can perform any valid math operation that updates the control variable.
Note that these statements aren't required -- you can omit them if you don't need them (for example, if you have already initialized the loop's control variable in preceding code). However, the two semicolons are still required, so you can do something like this:
#include <iostream> using namespace std; int main () { int userNum, curNum; cout << "Please input a number: "; cin >> userNum; curNum = userNum + 1; cout << "The next five numbers are: "; //Note how the initialization statement is omitted below for (; curNum <= userNum + 5; ++curNum) cout << curNum << ' '; //Like an if statement, we can omit the curly braces if it's just a one-liner cout << endl; return 0; }
Please input a number: 65
The next five numbers are: 66 67 68 69 70
You can also create an infinite loop by omitting all of the for
loop parameters:
#include <iostream> using namespace std; /* A rudimentary implementation of the unix `yes` command https://linux.die.net/man/1/yes */ int main () { for (;;) { cout << 'y' << endl; } return 0; }
You should try to avoid infinite loops whenever possible, however. Even if you're using a break
statement to stop the
loop execution, it is generally considered bad style. You should always have some exit condition given to the loop.
As mentioned above, you can do anything to the control variable during the increment step; it is only called "increment" because that is what is usually done during that step.
Here's a for
loop that does something different with its control variable:
#include <iostream> using namespace std; int main () { for (int x = 25; x >= 0; x -= 5) cout << x << endl; return 0; }
25
20
15
10
5
0
while
/do-while
loops
The idea behind the for
loop is that the loop is supposed to execute a set number of times.
That number might be determined at runtime by variables, or it might be hard-coded. However, it is not meant to
be used in cases where you want to continue looping until some condition is met. This is where while
and
do-while
loops are used. Let's look at a while
loop first:
#include <iostream> using namespace std; int main () { string input; while (input != "yes") { cout << "Would you like to quit? "; cin >> input; } return 0; }
This program is fairly straightforward. It loops, asking the user if they want to quit until they enter yes.
So, all the while
loop does is check the condition it is given before each iteration (much like a for
loop),
and if the condition ever evaluates to false
, then the loop stops.
The big thing to note about while
loops is that, like a for
loop, if the condition is false before the first iteration, the loop body will never execute;
for example, the following loop would never execute:
#include <iostream> using namespace std; int main () { string input = "yes"; while (input != "yes") { cout << "Would you like to quit? "; cin >> input; } return 0; }
Because input
is already set to "yes"
, the condition for the while
loop would evaluate to false
before the first execution,
so the loop would immediately exit.
Now, let's look at a do-while
loop. They are quite similar to while
loops:
#include <iostream> using namespace std; int main () { string input; do { cout << "Would you like to quit? "; cin >> input; } while (input != "yes"); return 0; }
The above code is functionally equivalent to the original program we wrote for while
loops -- it loops until the user enters yes and then quits.
Note that the condition ends in a semicolon -- it is required.
The difference between a while
loop and a do-while
loop is that a do-while
loop checks its condition
after each loop iteration (which is why the condition is placed at the end of the loop). This minor difference means that, unlike a while
loop, a do-while
loop will always execute at least once. Our example from earlier would no longer skip executing the loop body:
#include <iostream> using namespace std; int main () { string input = "yes"; do { //this always executes at least once! cout << "Would you like to quit? "; cin >> input; //because input is overwritten, we see the same exact behavior //as the previous example } while (input != "yes"); return 0; }
The choice between a while
and do-while
loop is up to the discretion of (you!) the programmer, however while
loops are typically preferred where
the implementation would not otherwise differ at all between the two choices. If you need to ensure that the loop runs at least once, use a do-while
loop.
Loop control statements
Now that you are familiar with the different types of loops that C++ has to offer, let's look at two language keywords that C++ has for dealing with loops:
break
and continue
. Both keywords only have meaning inside of a loop body (except for break
in a
switch-case
statement); the compiler will throw an error if it finds them
anywhere else.
break
tells the loop to stop executing at the current position in the loop and resume execution after the end of the loop.
This happens regardless of whether the loop condition is false
or not.
#include <iostream> using namespace std; int main () { for (int i = 0; i < 10; ++i) { cout << i << ' '; //Loop will stop if i == 5 if (i == 5) break; } cout << endl << "Done" << endl; return 0; }
0 1 2 3 4 5
Done
continue
tells the loop to skip executing the rest of the current iteration and move on to the next iteration.
This does not skip the condition check, so if the condition fails, the loop will exit anyways.
#include <iostream> using namespace std; int main () { for (int i = 0; i < 10; ++i) { //Loop will skip printing if i == 5 if (i == 5) continue; cout << i << ' '; } cout << endl << "Done" << endl; return 0; }
0 1 2 3 4 6 7 8 9
Done
There are ongoing debates about whether the use of these keywords (predominantly break
) is considered "good style".
Generally speaking, however, using something like break
is fine as long as it "reads well", in other words, if using
break
makes your code easier for someone else to understand, then it is fine. However, a break
should
never be used in place of a loop condition. A good use of a break
statement would be
with error detection -- if you find an error in the middle of your loop and need the loop to stop, you can use a break
.
Guided exercise
Write the following two programs. Be sure to use a loop:
- Ask the user for a number 5 times and output the sum of the 5 numbers.
- Ask the user for a number until the user enters a negative number, then output the sum of the numbers (including the negative number).
You're all done for today's walkthrough! Head over to the repl.it classroom and get started on today's exercise.