0% found this document useful (0 votes)
9 views

PART 1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

PART 1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 111

Learning Objectives: Printing

Use the cout command to write text to the console

Add a newline character by using the endl command

Create single-line and multi-line comments by using //


and /* */ respectively
Printing to the Console

Printing to the Console


As you learn C++, you will write code in the text editor to the left. There is
already some code there that we will cover later. For now, use a cout
command to see the output of your program. Copy and paste the code
below into the text editor on the left. Make sure your code is in between the
//add code below this line and //add code above this line comments.
Then click the TRY IT button to see what is outputted by the code.

cout << "Hello world!";

The reason you were able to see the words appear is because of the cout
command followed by the << and finally what you want to print "Hello
world";. cout is short for characters out and is used to output your desired
text.

Change your desired output to look like this and TRY IT again.

"My name is Codio."


Printing

Printing without the Newline Character


The cout command does not add a newline character. The code below will
print the two words on the same line without a space. Copy the code below
into the text editor on the left and then click the TRY IT button below to see
the output.

cout << "Hello";


cout << "world!";

Adding the Newline Character


The text in red shows the endl command which adds the newline
character. (The newline character is what is inserted when you press
“Enter” or “Return”).

.guides/img/NewlineCharacter

Add a second line by using the cout << endl; command under "cout <<
"world!";. Then enter the ouput command to print My name is Codio.
Finally, click the TRY IT button to see the resulting output.

cout << "Hello";


cout << "world!";
cout << endl;
cout << "My name is Codio." << endl;
challenge

What happens if you:


Add a space after Hello and before the closing "
Add << endl; after cout << "Hello ";
Delete cout << endl; under cout << "world!";
Comments

Comments
You may have wondered why a couple of lines of code are a different color
(in the below example, light brown, but it depends on the Theme you have
picked):

.guides/img/Comment

In C++, to write notes in code without affecting its function, we can use //
to make a single-line comment. Click the TRY IT button below to see the
resulting output.

Comments can also be used to help you fix your code. You can “comment
out” lines of code that are not working or you suspect are causing
problems.

challenge

What happens if you:


Change cout << "Red" to cut << "Red"
Add // in front of cut << "Red"

Block Comments
To make a block comment you can either make multiple single-line
comments using // or wrap the set of lines in /* and */. TRY IT below!
/*
This is the start of a multi-line comment.
You can end the comment with a star(*) followed by a forward
slash(/).
*/

//You can also do a multi-line comment


//like this!

cout << "Notice how the comments above are lightly faded.";
cout << "Most IDEs automatically lighten the comments.";
cout << "This is a common feature known as syntax
highlighting.";

What is an IDE?
An integrated development environment, or IDE, is a computer program that
makes it easier to write other computer programs. They are used by
computer programmers to edit source code, and can be easier to use than
other text editors for new programmers. They can have compilers so
programmers don’t have to open other programs to compile the source code.
They also often have syntax highlighting. … It also may have predictive
coding that can finish lines with syntax such as brackets or semicolons and
can suggest variables to be used. It also may have debuggers that can step
through lines, take breaks and inspect variables.
Source: Simple Wikipedia
Learning Objectives: Variables

Understand the rules of naming a variable

Assign/overwrite a value to a variable

Understand four basic data types: integers (ints), floats,


boolean (bool), and strings
Variables

What Is a Variable?
In computer science, we often need to use data. Variables are used to store
a value for a particular type of data.

Each variable in C++ has:

1. a data type
2. a name
3. a value

We will discuss each of these parts over the rest of this reading assignment.

Three Actions for Variables


There are a few different actions taken involving variables:
1. Declaring - when you set or declare the data type and name of the
variable. These two properties of a variable do not change.
1. Assigning - when you set the value of the variable. The value of a
variable can change.
1. Accessing - when you retrieve the value of the variable by calling its
name.

You must declare and assign a variable before you can access it.

Take a look at the visualizer on the left to see an example of how this
works. Click on the Forward > button at the bottom of the page to
repeatedly move through each stage of the process. The visualizer may take
a few seconds to load. Click on the Refresh code button in the upper left
corner if you encounter an error message.
Data Types: Integers

Integers
Integers (often called ints) are whole numbers. They can be positive or
negative. Do not use a comma when typing large numbers.

Copy the code below into the text editor. Then click the TRY IT button.

int number;
number = 50;
cout << number << endl;

Next, let’s modify the code to look like what’s below and then click the TRY
IT button again.

int number = 50;


cout << number << endl;

important

You may have noticed that we can declare a variable name and assign
it a value all in one step by using int number = 50; instead of int
number; followed by number = 50;. Both ways will produce the same
result.

5 vs. “5”
5 is not the same thing as “5”. The first one is an integer, the second is a
string. You will see in a later lesson the different operations you can
perform on strings and numbers. Treating a string as a number can cause
errors.
challenge

What happens if you:


Change the variable to 5000?
Change the variable to 5,000?
Change the variable to 050?
Change the variable to "5000" (with double quotes)?
Data Types: Floating Point
Numbers

Floating Point Numbers


Floating point numbers (often called floats) are numbers with a decimal.
They can be positive or negative. Copy the code below and TRY IT.

double decimal = 0.5;


cout << decimal << endl;

Why Use Double Instead of Float?


In C++, there is a data type called float, but as it only uses 4 bytes, it is
insufficient for most math. Instead, we use double which uses 8 bytes or
double the space of a float.

challenge

What happens if you:


Change the variable to 50.?
Change the variable to .001?
Data Types: Boolean

Boolean
A boolean variable (declared as a bool) can only take on the value of true
or false. You will see how boolean values are used when we talk about
conditionals and while loops. Copy the code below and TRY IT.

bool thisIsFun = true;


cout << boolalpha << thisIsFun << endl;

challenge

What happens if you:


Change the variable to false?
Remove the boolalpha << command?
Change the variable to True?
Change the variable to False?
Change the variable to TRUE?

important

You may have noticed that printing a boolean of true resulted in a 1


and a boolean of false resulted in a 0 when you remove the boolalpha
<< command. In C++, the boolean value of true is associated with the
integer 1 while the boolean value of false is associated with the integer
0. Assigning the value of uppercase True or False to a boolean variable
will cause an error message to appear.
Data Types: Strings

Strings
A string is a collection of text, numbers, or symbols. Strings are always
surrounded by quotation marks. Copy the code below and TRY IT.

string words = "This is a string.";


cout << words << endl;

challenge

What happens if you:


Forget one of the " quotation marks?
Forget both " " quotation marks?
Use single (') quotation marks?
Use uppercase String instead of lowercase string?

Notice that when you print a string, the quotation marks are not printed.
Declaring Variables

Declaring a Variable
Declaring a variable has two parts - setting or declaring the data type and
the name of the variable. These two properties of a variable do not change.

To declare a variable, type the data type and name of the variable you want
to create, and a ; (semi-colon). Copy the code below and TRY IT.

string my_var;

You will notice we are not printing anything - that is because no value has
been assigned yet. Thus, the message Command was successfully executed.
appears when you click on the TRY IT button. The declaration step only sets
aside empty memory.

challenge

What happens if you:


Create two variables with the same type and name?
Create two variables with the same name but different
capitalization (i.e. my_var and My_var)?
Create two variables of different types with the same name?

Variable Naming Rules


Here are the rules for naming a variable.

Rule Correct Incorrect


Start with a
letter or variable, _variable 1variable
underscore
Remainder
of variable
name is
letters, var_i_able, var1able var-i-able, var!able
numbers, or
underscores
Cannot use a
my_class class
C++ keyword
Variables variable, Variable, and
are case VARIABLE are all
sensitive different variables

What Are C++ Key Words?


C++ keys words are words that are reserved for specific functions or tasks
within C++ programs. These words cannot be used to name variables and
will result in errors if they are not handled correctly. Click below to see a
list of C++ key words.

List of C++ key words

and and_eq asm auto bitand


bitor bool break case catch
char class compl const const_cast
continue default delete do double
dynamic_cast else enum explicit extern
false float for friend goto
if inline int long mutable
namespace new not not_eq operator
or or_eq private protected pubic
register reinterpret_cast return short signed
sizeof static static_cast struct switch
template this throw true try
typedef typeid typename union unsigned
using virtual void volatile wchar_t
while xor xor_eq
Initializing, Assigning, and
Assessing

Initializing & Assigning Values


We call the process of setting the initial value of a variable initialization.
Recall that you can do this separately after the declaration or combine it
into the same statement as the declaration.

.guides/img/VariableAssignmentInt

Since the value stored in a variable can change, we call changing the value
assigning or re-assigning. Use the assignment operator, =, to give a
variable a new value.

Accessing Variables
Copy the code below and TRY IT to see the results of the cout commands.
Click on the ++Code Visualizer++ link to see how the value of my_int
changes.

int my_int = 123;


cout << my_int << endl;
my_int = 321;
cout << my_int << endl;

When we use a variable’s name to get the value like in the cout statements
above, we say we are accessing the variable.

Code Visualizer
Lab: Printing

Tutorial Lab 1: Printing


1. In the text editor to your left, you will see the code below:

string my_var = "I am learning"; //step 1


cout << my_var; //step 2
my_var = " to program"; //step 3
cout << my_var; //step 4
my_var = " in C++."; //step 5
cout << my_var << endl; //step 6
my_var = "Hooray!"; //step 7
cout << my_var; //step 8

2. Click TRY IT to see what the code outputs.

3. Click on the ++underlined++ text below to highlight some of the


important points in the code:

Step 1 - Declare the variable my_var and initialize it to the value I am


learning
Step 2 - Print without a new line character by not including << endl;
Step 3 - Add a space when starting the string to avoid printing
learningto
Step 6 - A newline character is added using << endl;
Step 8 - Hooray! is on its own line since the << endl; command was
used in step 6

4. To remove the highlighting, click here: Remove Highlighting


Lab: Variables

Tutorial Lab 2: Variables


1. Use the text editor to the left.

2. Copy the code below.

int one = 1;
int two = 2;
int three = 3;
int four = 4;

two = one;
three = two;
four = three;

cout << four;

3. TRY IT to see the output. Click on the ++Code Visualizer++ link below to
go through the program step by step.

Code Visualizer
Lab: Challenge

Tutorial Lab 3: Fundamentals Challenge


In the code to the left, we see that there are a series of declared and
initialized variables. Use these variables along with the cout << and <<
endl; commands to print out a custom message to customers who open a
chat client.

Your output should look something like this:

Hello! Today is Wednesday, May 4.


The current wait time is 4 minutes.

The pattern is as follows. The * indicates variables:

*greeting* Today is *dayOfWeek*, *month* *day*.


The current wait time is *currentWaitMinutes* minutes.

To test the code, first click on the COMPILE button. This will compile your
code and turn it into a program. If your program compiled successfully, you
will see the message Command was successfully executed. Then you can
run your program by clicking on the TEST buttons. You will see the output
of a few different test cases:

Take a look at the test outputs above. Do they look like the expected outputs
below? If not, your code may need some revision.

Hello! Today is Monday, July 4.


The current wait time is 9 minutes.

Howdy! Today is Tuesday, December 15.


The current wait time is 2 minutes.

Greetings! Today is Friday, March 13.


The current wait time is 39 minutes.
Learning Objectives: Arithmetic
Operators

Recognize the symbols for arithmetic operators

Use the printf() command to print doubles and integers

Demonstrate how to increment and decrement a


variable

Perform string concatenation

Apply PEMDAS rules to arithmetic operations


Addition

The Addition (+) Operator


The addition operator works as you would expect with numbers. Copy and
paste the code below into the text editor on the left. Make sure your code is
in between the //add code below this line and //add code above this
line comments. Then click the TRY IT button to see what is outputted by
the code.

cout << 7 + 3 << endl;

You can also add two variables together. Modify the code to look like what’s
below and then click the TRY IT button again.

int a = 7;
int b = 3;
cout << a + b << endl;

challenge

What happens if you:


Make a of type double (e.g. double a = 7.0;)?
Change a to double a = 7.1;?
Make b a negative number (e.g. int b = -3;)?
Make b an explicitly positive number (e.g. int b = +3;)?
important

IMPORTANT
You may have noticed that when you add an int of 3 to a double of 7.1
you get 10.1. However, when you add an int of 3 to a double of 7.0, you
get 10 instead of 10.0. This occurs because by default cout does not
print zeros after a decimal point unless those zeros are enclosed by
other non-zero digits.

Examples:
* cout << 7 + 3.14; prints 10.14
* cout << 7.0 + 3.00; prints 10
* cout << 7.00 + 3.01400; prints 10.014

==Note== that when an int and a double are added together, the result
will be a double because the program will take on the data type that is
more flexible.
Printing Floating Point Numbers

cout
The cout command is considered to be non-specific because you can use the
same syntax for all of your printing needs (e.g. cout << 1;, cout <<
"Hello";, and cout << true;). However, for printing certain numbers, it is
not always clear if what’s printed is an int or a double sometimes.

int a = 1;
double b = 1.0;
cout << a << endl;
cout << b << endl;

Even though you are printing a double of 1.0, the system will disregard the
decimal and the trailing zero when cout is used. There is another print
command called printf() that also prints text to the console.

printf()
printf() originates from the C language and, unlike the cout command, it
is considered to be specific. This means that you must specify what type of
data you want to print before you can use the command successfully.

int a = 1;
double b = 1.0;
cout << a << endl;
cout << b << endl;
printf("%d \n", a);
printf("%f \n", b);
challenge

What happens if you:


Remove the \n from printf("%d \n", a);?
Replace %d with %f in printf("%d \n", a);?
Replace %f with %d in printf("%f \n", b);?

important

IMPORTANT
When printf() is used, a specifier is needed in order to tell the system
what type of data you want to print. The %d tells the system to print an
integer and %f tells the system to print a floating point number. If you
use an incorrect specifier, you will receive an error message. By
default, floating point numbers contain six zeros after the decimal
point if they are printed using printf().

The \n in printf() is equivalent to endl. They both print a newline


character. Removing the \n from printf("%d \n", a); will delete the
newline character and cause the variables a and b to be printed side-
by-side.

cout vs. printf()


Unless you want to be specific with how your data is printed, you should
always default to using cout. Only use printf() when formatting is
important.
Incrementing Variables

Incrementing Variables
Incrementing a variable means to increase the value of a variable by a set
amount. The most common incrementation you will see is when a variable
increments itself by the value of 1.

int a = 0;
a = a + 1;
cout << a << endl;

How to Read a = a + 1
The variable a appears twice on the same line of code. But each instance of
a refers to something different.

.guides/img/Increment

The ++ and += Operators


Since incrementing is such a common task for programmers, many
programming languages have developed a shorthand for a = a + 1. The
result is a++ which does the same thing as a = a + 1.

int a = 0;
int b = 0;
a = a + 1;
b++;
cout << a << endl;
cout << b << endl;
In the cases where you need to increment by a different number, you can
specify it by using the += operator. You can replace b++; with b+=1; in the
code above and still get the same result.

challenge

What happens if you:


Replace b++ in the code above with b+=2?
Replace b++ in the code above with b+=-1?
Replace b++ in the code above with b-=1?
String Concatenation

String Concatenation
String concatenation is the act of combining two strings together. This is
done with the + operator.

string a = "This is an ";


string b = "example string";
string c = a + b;
cout << c << endl;

challenge

What happens if you:


Concatenate two strings without an extra space (e.g. remove the
space after an in string a = "This is an";)?
Use the += operator instead of the + operator (e.g. a+=b instead of a
+ b)?
Add 3 to a string (e.g. string c = a + b + 3;)?
Add "3" to a string (e.g. string c = a + b + "3";)?
Subtraction

Subtraction
Copy the code below and TRY IT.

int a = 10;
int b = 3;
int c = a - b;
cout << c << endl;

challenge

What happens if you:


Assign b to -3?
Assign c to a - -b?
Assign b to 3.1?
Change b to bool b = true;?

important

IMPORTANT
Did you notice that you were able to subtract a bool from an int?
Recall that a bool of true is actually an integer of 1 and false is actually
0. Thus, the system is able to add and subtract bools and ints. In
addition, assigning b which is of type int to 3.1 will force the variable
to adopt the integer value of 3 instead. Remember that all ints
disregard decimal places.

The -- and -= Operators


Decrementing is the opposite of incrementing. Just like you can increment
with ++, you can decrement using --.
int a = 10;
a--;
cout << a << endl;

Like +=, there is a shorthand for decrementing a variable, -=. For example,
if you want to decrement the variable a by 2 instead of 1, replace a-- with
a-=2.

Subtraction and Strings


You might be able to concatenate strings with the + operator, but you
cannot use the - operator with them.

string a = "one two three";


string b = "one";
string c = a - b;
cout << c << endl;
Division

Division
Division in C++ is done with the / operator.

double a = 25.0;
double b = 4.0;
printf("%f \n", a / b);

challenge

What happens if you:


Assign b to 0.0?
Assign b to 0.5?
Change the code to…

double a = 25.0;
double b = 4.0;
a /= b;
printf("%f \n", a);

Hint(s)
/= works similarly to += and -=.

important

IMPORTANT
Division by zero is undefined in mathematics. In C++, dividing by an
integer of 0 results in an error message. However, dividing by a
double of 0.0 results in inf which is short for infinity.

Integer Division
Normally, you use double in C++ division since the result usually involves
decimals. If you use integers, the division operator returns an int. This
“integer division” does not round up, nor round down. It removes the
decimal value from the answer.

.guides/img/IntDivision

int a = 5;
int b = 2;
cout << a / b << endl;
Modulo

Modulo
Modulo is the mathematical operation that performs division but returns
the remainder. The modulo operator is %.

.guides/img/Modulo

int modulo = 5 % 2;
cout << modulo << endl;

challenge

What happens if you:


Assign modulo to 5 % -2?
Assign modulo to 5 % 0?
Assign modulo to 5 % 2.0?
Multiplication

Multiplication
C++ uses the * operator for multiplication.

int a = 5;
int b = 10;
cout << a * b << endl;

challenge

What happens if you:


Assign b to 0.1?
Assign b to -3?
Change the code to…

int a = 5;
int b = 10;
a*=b;
cout << a << endl;

Hint(s)
*= works similarly to +=, -=, and /=.
Order of Operations

Order of Operations
C++ uses the PEMDAS method for determining order of operations.

.guides/img/PEMDAS

By default, there are no operators for exponents and square roots.


Instead, functions such pow( , ) and sqrt() are used to calculate powers
and square roots respectively. In order to use these functions, they must be
imported by including #include <cmath> at top of the program header. For
exponents, the base number goes before the , in pow( , ) and the exponent
goes after the ,. For example, pow(4, 2) calculates and pow(4, 0.5)
calculates or . For square roots, the number goes inside the () in
sqrt(). An example is sqrt(4) which calculates .

cout << pow(2, 2) << endl;


cout << pow(25, (1 / 2)) << endl;
cout << pow(25, (1.0 / 2.0)) << endl;
cout << sqrt(25) << endl;

pow(25, (1 / 2)) vs. pow(25, (1.0 / 2.0))


pow(25, (1 / 2)) results in 1 because integer division is performed within
(1 / 2). 1 divided by 2 returns in an integer of 0 and computes to 1. On
the other hand, pow(25, (1.0 / 2.0)) involves double division which is
why 5 was computed.

The code below should output 10.000000.

int a = 2;
int b = 3;
int c = 4;
double result = 3 * a - 2 / (b + 5) + c;
printf("%f \n", result);
Explanation

The first step is to compute b + 5 (which is 8) because it is surrounded


by parentheses.
Next, do the multiplication and division going from left to right: 3 * a is
6.
2 divided by 8 is 0 (remember, the / operator returns an int when you
use two ints so 0.25 becomes 0).
Next, perform addition and subtraction from left to right: 6 - 0 is 6.
Finally, add 6 and 4 together to get 10.
Since result is of type double, 10.000000 is printed.

challenge

Mental Math
5 + 7 - 10 * 4 / 2
Solution
-8
5 * 8 - 7 % 2 - 18 * -1
Solution
57
9 / 3 + (100 % 100) - 3
Solution
0
12 - 2 * pow(2, 3) / (4 + 4)
Solution
10
Type Casting

Type Casting
Type casting (or type conversion) is when you change the data type of a
variable.

int numerator = 40;


int denominator = 25;
int number = 0;
cout << boolalpha << (bool) number << endl;
cout << numerator / denominator << endl;
cout << (double) numerator / denominator << endl;

numerator and denominator are integers, but (double) converts numerator


into a double. You can use (double), (int), and (bool) to cast any double,
integer, or boolean between each other. Note that casting an integer of 0 or
a double of 0.0 to a boolean will result in false. Any other integer or
double values will result in true.
challenge

What happens if you:


Assign number to 5?
Cast only denominator to a double?
Cast both numerator and denominator to a double?
Cast the result to a double (e.g. (double) (numerator /
denominator)?
Change the code to…

int numerator = 40;


int denominator = 25;
int number = 5;
cout << boolalpha << (bool) number << endl;
cout << numerator / denominator << endl;
cout << (double) numerator / denominator << endl;
printf("%d \n", numerator / denominator);
printf("%f \n", (double) numerator / denominator);
printf("%f \n", (double) (numerator / denominator));

More information
If either or both numbers in C++ division are doubles, then double division
will occur. In the last example, numerator and denominator are both ints
when the division takes place which results in an int of 1. An integer of 1
converted to a double is 1.000000 but cout removes the decimal point and
all of the trailing zeros.

Data Type Compatibility


Do you know why the code below will not work?

int a = 5;
string b = "3";
cout << a + b << endl;

In C++, you can add a combination of ints, doubles, and bools together.
Remember that a boolean is either 1 if it’s true or 0 if it’s false. In the
example above, adding a string to an integer results in an error. That’s
because a string has no numerical value and can only be added to other
strings. However, you can convert the string b to an integer to fix the
problem by using stoi(). stoi() acts as a function to convert a string into
an integer. The string or string variable goes into the () to be converted.
See below for a list of type-conversion functions.

int a = 5;
string b = "3";
string c = "3.14";
bool d = true;
cout << a + stoi(b) << endl;

List of commonly used type-conversion functions

Output
Function Input Type Example
Type
stoi() string int stoi(“10”)

stod() string double stod(“12.34”)

int, double, to_string(10), to_string(12.34),


to_string() string
or boolean or to_string(false)

challenge

What happens if you:


Replace stoi(b) with stoi(c)?
Replace stoi(b) with stod(c)?
Replace stoi(b) with to_string(d)?
Replace a + stoi(b) with b + to_string(d)?

important

IMPORTANT
You can convert the string "3.14" to an integer using stoi() which will
result in an int of 3. To retain the decimal places, use stod() instead. In
addition, the to_string() function will convert a boolean into the
string form of its numerical value. to_string(true) will convert true to
"1" instead of 1. This is why adding b, which is a string of "3", to
to_string(d) resulted in the string of "31".
Learning Objectives: Boolean
Operators

Recognize the difference between = and ==

Understand the && and || operators’ functions

Evaluate boolean expressions


Equal To & Not Equal To

Boolean operators are operators that return a boolean value (true or


false).

Equal To
C++ uses the == operator to determine equality. Beginners often confuse the
= and the == operators. Remember, = is the assignment operator.

int a = 5;
int b = 5;
cout << boolalpha << (a == b) << endl;

challenge

What happens if you:


Assign b to 1?
Change a to bool a = true; and b to bool b = false;?

Not Equal To
The != operator checks to see if two values are not equal.

int a = 5;
int b = 5;
cout << boolalpha << (a != b) << endl;
challenge

What happens if you:


Assign b to 1?
Change a to bool a = true; and assign b to 1?
Change b to bool b = false;?
Less Than & Less Than or Equal To

Less Than
The < operator is used to check if one value is less than another value.

int a = 5;
int b = 7;
cout << boolalpha << (a < b) << endl;

challenge

What happens if you:


Assign b to 1?
Assign b to 5?
Assign b to false?

Hint(s)
It is possible to declare and assign int b = false; because false is just a
value of 0. Since 5 is not less than 0, false is returned.

Less Than or Equal To


The <= operator is used to check if one value is less than or equal to another
value.

int a = 5;
int b = 7;
cout << boolalpha << (a <= b) << endl;
challenge

What happens if you:


Assign b to 1?
Assign b to 5?
Assign a to false and assign b to true?

Hint(s)
false is less than true because 0 is less than 1.
Greater Than & Greater Than or
Equal To

Greater Than
The > operator is used to check if one value is greater than another value.

int a = 9;
int b = 17;
cout << boolalpha << (a > b) << endl;

challenge

What happens if you:


Assign b to 1?
Assign b to 9?
Assign b to false?
Assign b to true?

Hint(s)
9 is both greater than the value of false, which is 0, and the value of true,
which is 1.

Greater Than or Equal To


The >= operator is used to check if one value is greater than or equal to
another value.

int a = 9;
int b = 17;
cout << boolalpha << (a >= b) << endl;
challenge

What happens if you:


Assign b to 1?
Assign b to 9?
Assign a to true and assign b to false?

Hint(s)
true is greater than false.
And

The && Operator


The && (and) operator allows for compound (more than one) boolean
expressions. All boolean expressions must be true in order for the whole
thing to be true. If at least one boolean expressions is false, then the whole
thing is false.

bool a = true;
bool b = true;
bool c = false;
cout << boolalpha << (a && b) << endl;

How do I type &&?


It is located towards the top of the keyboard, on the same key as the
number 7. Hold shift and press the 7 key to type &.

challenge

What happens if you:


Replace (a && b) in the code above with (a && c)?
Replace (a && b) in the code above with (b && c)?

Multiple && Statements


You can chain several && expressions together. They are evaluated in a left-
to-right manner.

bool a = true;
bool b = true;
bool c = false;
cout << boolalpha << (a && b && c) << endl;
challenge

What happens if you:


Replace (a && b && c) in the code above with (a && b && a && b
&& a)?
Replace (a && b && c) in the code above with (a && b && a && b
&& c)?

Hint(s)
c is the only variable is that is false. Thus, if c is involved in an &&
expression, the entire thing will evaluate to false. Any combinations of as
and/or bs will result in true.
Or

The || Operator
The || (or) operator allows for compound (more than one) boolean
expressions. If at least one boolean expression is true, then the whole thing
is true. To be false, all boolean expressions must be false.

bool a = true;
bool b = true;
bool c = false;
bool d = false;
cout << boolalpha << (a || b) << endl;

How do I type ||?


It is towards the right-hand side, below the backspace or delete key and
above the enter or return key. The | symbol is located on the same key as
the </code> symbol. Hold shift and press the </code> key to type |.

challenge

What happens if you:

Replace (a || b) in the code above with (a || c)?

Replace (a || b) in the code above with (c || d)?

Multiple || Statements

You can chain several || expressions together. They are evaluated in a left-to-
right manner.
bool a = true;
bool b = true;
bool c = false;
cout << boolalpha << (a || b || c) << endl;

challenge

What happens if you:

Replace (a || b || c) in the code above with (a || c || c || c || c)?

Replace (a || b || c) in the code above with (c && c && c && c && c)?
Not

The ! Operator
The ! (not) operator produces the opposite result of the boolean expression
that it modifies.

cout << boolalpha << (! true) << endl;

challenge

What happens if you:


Replace (! true) in the code above with (! true && false)?
Replace (! true) in the code above with (! (true && false))?
Replace (! true) in the code above with (! ! true)?

Hint(s)
The ! operator works similarly to how a - (negative) sign works in
mathematics. The - of a positive number is a negative number and the - of
a negative number is a positive number.

Order of Boolean Operators


Much like how arithmetic operators are evaluated in a certain order,
boolean operators also work according to their priority level. Boolean
operations are evaluated in the following order from highest to lowest
priority:

1. Parentheses ()
2. Not !
3. And &&
4. Or ||
Short Circuiting

Short Circuiting
If C++ can determine the result of a boolean expression before evaluating
the entire thing, it will stop and return the value.

.guides/img/ShortCircuiting

cout << boolalpha << (false


&&
/*C++ never reaches this line*/ true) << endl;

cout << boolalpha << (true


||
/*C++ never reaches this line*/ false) << endl;
Lab: Arithmetic Operators

Tutorial Lab 1: Arithmetic Operators


Arithmetic operations in C++ are mostly the same as what you learned in
math class. However, the symbols used in C++ may be different.

Operation Symbol Notes


Addition +
Subtraction -
Multiplication *
Division /
Returns the remainder after division is
Modulo %
performed.

Use the text editor on the left to enter the following code:

cout << 10 + 3 << endl;


cout << 10 - 3 << endl;
cout << 10 * 3 << endl;
cout << 10 / 3 << endl;
cout << 10 % 3 << endl;

Program results:
1) Addition works as expected.
2) Subtraction works as expected.
3) Multiplication works as expected.
4) Division with integers will return a truncated integer result.
5) Modulo returns 1 because that is the remainder (not the decimal) after
division is performed.
Lab: Strings

Tutorial Lab 2: Strings


You can use the + operator with strings, even though the result is not based
on math. Using the + operator with strings is called concatenation.

Use the text editor on the left to enter the following code:

string string1 = "hip ";


string string2 = string1 + string1;
string string3 = "hoo";
string string4 = "ray!";
string string5 = string3 + string4;
cout << string2;
cout << string5 << endl;

Below are the steps that C++ takes when evaluating the code above.
1) Assign the value "hip " to the variable string1. Note the inclusion of a
space after the word hip.
2) The variable string2 will have the value of "hip hip " because string1
+ string1 repeats the value of string1 two times.
3) Declare string3 and assign it the value of "hoo".
4) Declare string4 and assign it the value of "ray!".
5) Declare string5 and assign it the value of string3 combined with the
value of string4 ("hooray!").
6) Print the value of string2 ("hip hip ") without the newline character.
7) Print the value of string5 ("hooray!") to the end of string2.
Lab: Order of Operations

Tutorial Lab 3: Order of Operations


C++ uses PEMDAS when determining the order of operations.

.guides/img/PEMDAS

Modulo and PEMDAS


Since modulo is based on division, modulo operations happen at the time
of multiplication and division, going from left to right.

Use the text editor on the left to enter the following code:

cout << (5 * 8 / 3 + (18 - 8) % 2 - 25) << endl;

Below are the steps that C++ takes when evaluating the code above.
1) 5 * 8 / 3 + (18 - 8) % 2 - 25
1) 5 * 8 / 3 + 10 % 2 - 25
1) 40 / 3 + 10 % 2 - 25
1) 13 + 10 % 2 - 25
1) 13 + 0 - 25
1) 13 - 25
1) -12
Lab: Boolean Operators

Tutorial Lab 4: Boolean Operators


Boolean operators are used within expressions to return either true or
false.

Operation Symbol Notes


The = operator is
the assignment
Equal to == operator, not the
equality
operator.
Not equal to !=

Less than <

Less than or equal to <=

Greater than >

Greater than or equal to >=

Compares two
boolean
expressions.
Both must be
And &&
true for the
whole to be
true. Everything
else is false.
Compares two
boolean
expressions.
Both must be
Or ||
false for the
whole to be
false. Everything
else is true.
Returns the
opposite result
Not ! of an evaluated
boolean
expression.
The following code is available within the text editor on the left. Click the
TRY IT button below to see the printed result.

cout << boolalpha << ((5 > 7) && (false || 1 < 9) || 4 != 5 && !
(2 >= 3)) << endl;

Below are the steps that C++ takes when evaluating the code above.

Evaluate all arithmetic operators according to PEMDAS

1. (5 > 7) && (false || 1 < 9) || 4 != 5 && ! (2 >= 3)


2. false && (false || 1 < 9) || 4 != 5 && ! (2 >= 3)
3. false && (false || true) || 4 != 5 && ! (2 >= 3)
4. false && (false || true) || true && ! (2 >= 3)
5. false && (false || true) || true && ! false

Evaluate all boolean operators according to this order -


Parentheses (()), Not (!), And (&&), then Or (||)

6. false && true || true && ! false


7. false && true || true && true
8. false || true && true
9. false || true
10. true

==Note== that arithmetic operators are performed before boolean


operators.
Lab Challenge: Operators

Operators Challenge
Write a boolean expression that incorporates ONE of the equality
operators, ONE of the less than operators, ONE of the greater than
operators, and TWO of the logical operators. The result of your overall
boolean expression MUST be false. Make sure to use cout << boolalpha <<
in your code. Otherwise, the system will print 0 or 1 instead of false or
true.

Equality Less Than Greater Than Logical


== < > &&

!= <= >= ||

!
Learning Objectives: If Else
Statement

Describe if-else statement syntax

Explain the difference between an if statement and an


if-else statement
If Else Statement Syntax

If Else Syntax
The if-else statement checks to see if a condition is true, and then has
specific actions that take place. However, it also provides a specific set of
actions if the boolean expression is false. Use the else keyword to
introduce the code to run when false is evaluated. Note that else is aligned
with the if keyword (no indentation) and has its own set of curly braces {}.
You do not write another boolean expression with else.

.guides/img/IfElseSyntax

It is best practice to indent the lines of code within the curly braces to
differentiate them but the indention does not affect how the program runs.

if (5 > 4) {
cout << "Print me if true" << endl;
}
else {
cout << "Print me if false" << endl;
}

Code Visualizer
challenge

What happens if you:


Change 4 in the code above to 6?
Remove all the curly braces {}?
Add cout << "False" << endl; under cout << "Print me if
false" << endl; without any curly braces {} in the code?
Add cout << "True" << endl; under cout << "Print me if true"
<< endl; without any curly braces {} in the code?

Code Visualizer

important

IMPORTANT
You may have noticed that when there is only one command
associated with an if or else statement the curly braces {} become
optional.

When Are Curly Braces Mandatory?


Curly braces {} are mandatory whenever you have more than one
command that is associated with an if or else statement. Here is a code
snippet that will work without curly braces:

if (10 % 2 == 0)
cout << "10 is even" << endl;
else
cout << "10 is odd" << endl;

However, if you add more commands to the if or else statement, the


program will not run properly. The examples below will not print as
intended or will produce an error message.
if (10 % 2 == 0) if (10 % 2 == 0)
cout << "10 is even" << endl; cout << "10 is even"
else cout << "True" << endl
cout << "10 is odd" << endl; else
cout << "False" << endl; cout << "10 is odd" <<

Like indentations, it is best practice to always include curly braces even if


they are optional in certain situations.

if (10 % 2 == 0) { // mandatory curly braces


cout << "10 is even" << endl;
cout << "True" << endl;
}
else { // optional curly braces
cout << "10 is odd" << endl;
}
If Else Statement

If Else Statement
The if-else statement is used when you want something specific to happen
if the boolean expression is true and something else to happen if it is false.

bool my_bool = true;

if (my_bool) {
cout << "The value of my_bool is true" << endl; }
else {
cout << "The value of my_bool is false" << endl; }

challenge

What happens if you:


Assign my_bool to false?
Assign my_bool to ! true && ! false?
important

IMPORTANT
Did you notice that the code above has the closing curly brace } after
the the semi-colon ; instead of on the next line? Remember that curly
braces {} are optional if the if-else statement only includes one
command within the if and else bodies. However, they are mandatory
when there is more than one command. When using curly braces, the
decision of where to place them is entirely up to you. All of the
commands below work exactly the same way:

if (is_true) {
cout << "1" << endl;
cout << "2" << endl;
}

if (is_true) {
cout << "1" << endl; cout << "2" << endl; }

if (is_true) { cout << "1" << endl; cout << "2" << endl; }

Testing Multiple Cases


You will find yourself needing to test the same variable multiple times. To
simplify this, you can nest if-else statements – which means you can put
an if-else structure inside of another if-else structure (as shown on the
right below).

.guides/img/NestedElseIf
When nesting if and else together, use the keywords else and if side-by-
side (else if). This nesting drastically changes the way the program flows
once the correct case is found. On the left, the program checks every case
no matter the value of the variable. On the right, the nested structure
causes the program to jump out of the structure once the correct case is
found. This is able to occur because the other if cases are inside the else
statement, which will only run when the previous boolean expression is
false.

int grade = 62;


if (grade < 60) {
cout << "F" << endl; }
else if (grade < 70) {
cout << "D" << endl; }
else if (grade < 80) {
cout << "C" << endl; }
else if (grade < 90) {
cout << "B" << endl; }
else if (grade <= 100) {
cout << "A" << endl; }

Code Visualizer
Learning Objectives: Switch Case
Statement

Describe the switch case syntax

Identify when to apply switch case statements instead of


nested if-else
Switch Case Statement Syntax

Swith Case Statement Syntax


The switch case statement is a way to make a decision with multiple
possible outcomes. Instead of nesting or sequencing many if statements,
C++ allows you to write the following:

.guides/img/SwitchCase

Here are the rules for writing a switch case statement:

Start with switch followed by the variable that is going to be tested in


parentheses ().
All of the cases are surrounded by a set of curly braces {}.
Each case is followed by a numerical value and a colon :.
After each :, write the code that should run if the variable is equal to
that case’s value.
After each section of code per case, include break;.
As the very last case, use default: to specify what should happen if
none of the above cases are true.
int dayOfWeek = 3;

switch (dayOfWeek) {

case 1: cout << "Sunday"; //only prints if dayOfWeek == 1


break;
case 2: cout << "Monday"; //only prints if dayOfWeek == 2
break;
case 3: cout << "Tuesday"; //only prints if dayOfWeek == 3
break;
case 4: cout << "Wednesday"; //only prints if dayOfWeek == 4
break;
case 5: cout << "Thursday"; //only prints if dayOfWeek == 5
break;
case 6: cout << "Friday"; //only prints if dayOfWeek == 6
break;
case 7: cout << "Saturday"; //only prints if dayOfWeek == 7
break;
default: cout << "Invalid"; //only prints if none of the above
are true

Code Visualizer

challenge

What happens if you:


Assign dayOfWeek to 5?
Assign dayOfWeek to 0?
Assign dayOfWeek to 3 and remove all of the break; statements?

Code Visualizer
Switch Case vs. If Else

Switch Case vs. Else If


C++ allows you to use either switch case or a series of else if statements
to handle decisions with multiple outcomes. There are a couple of reasons
why you would use one method over the other.

#1: Else If is used for ranges of values - Switch Case is for


specific values

switch case can only check for equality (e.g. num == 5), so if you need to
check for a range of values (e.g. num > 50 && num <= 60), use else If
instead.

.guides/img/SwitchCaseElseIf

What is case 10: case 9:?

Sometimes, the code for multiple cases is the same. Instead of repeating
code, you can list multiple cases before the code. Here is another
example:
int month = 2;
int year = 2000;
int numDays = 0;

switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
numDays = 31;
break;
case 4: case 6:
case 9: case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
! (year % 100 == 0)) ||
(year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
cout << "Invalid month.";
break;
}
cout << "Number of Days = " << numDays << endl;

In some cases, as shown above, you can exploit patterns to force ranges
into a switch case, but frequently that is not possible and it also makes the
code less readable. For example, above, the user has to realize that
letterGrade is using integer division to retrieve the tens place of the
original grade.
int grade = 62;
int letterGrade = grade / 10;
switch (letterGrade) {
case 10: case 9: cout << "A";
break;
case 8: cout << "B";
break;
case 7: cout << "C";
break;
case 6: cout << "D";
break;
default: cout << "F";
}

Code Visualizer

#2: Else If is used for handling multiple variables

switch case can only compare against values - not variables. For example,
if you wanted to compare the inputted day of the week with the current
day of the week, you would need to use else if. switch case can handle
values (dayOfWeek == "Sunday") but not variables (dayOfWeek == today).

#3: Else If is used for compound conditionals

To check multiple conditions, an else if is needed.

Below is an example of a multiple choice grader using switch case:


int studentAnswer = 3;
string feedback1 = "This answer is wrong because....";
string feedback2 = "This answer is correct! You know this
because...";
string feedback3 = "This answer is wrong. While the first part
is correct...";
string feedback;

int correctAnswer = 2;
int points = 0;

switch (studentAnswer) {
case 1: feedback = feedback1; break;
case 2: feedback = feedback2; break;
case 3: feedback = feedback3; break;
default: feedback = "Invalid answer choice";
}

cout << feedback << endl;

challenge

Switch Case to Else If

Change the switch case statements above into else if statements.


Add a check to see if studentAnswer == correctAnswer.
If the student’s answer is correct, increment (++) the points
variable.
Print out the student’s earned points at the end of the program
using the points variable.

Code Visualizer

Sample solution
if (studentAnswer == 1) {
cout << feedback1 << endl;
}
else if (studentAnswer == 2) {
cout << feedback2 << endl;
}
else if (studentAnswer == 3) {
cout << feedback3 << endl;
}
else {
cout << feedback << endl;
}

if (studentAnswer == correctAnswer) {
points++;
}

cout << points << endl;


Lab: If Statement

Tutorial Lab 1: If Statements


The if statement allows for your program to make a decision about what it
should do. It asks a simple question: “Is this condition true?” If yes, then the
computer will execute certain commands.

int x = 5;

if (x < 10) {
cout << "Less than 10" << endl;
}

Code Visualizer

An if statement is comprised of the keyword if, followed by a boolean


expression surrounded by parentheses (). Any code that should run if the
boolean expression is true is surrounded by curly braces {}. It is best
practice to indent this code, but it does not affect how the code runs.

If the boolean expression is false, the code in curly braces is skipped, and
the program continues as normal.

int x = 20;

if (x < 10) {
cout << "Less than 10" << endl;
}

cout << "And the program continues...";

Code Visualizer

if statements can be used to test multiple conditions. These conditions


exist as boolean expressions inside the parentheses (). In addition, an if
statement can exist inside another if statement. Both blocks of code below
accomplish the same exact task.
int age = 15; int age = 15;

if (age < 20) { if ((age < 20) && (age > 10)) {
if (age > 10) { cout << "Teenager";
cout << "Teenager"; }
}

Code Visualizer
Lab: If Else Statement

Tutorial Lab 2: If Else Statements


The if else statement gives your program the ability to ask a question,
perform certain actions if the answer is true, and then perform another set
of actions if the answer is false.

int x = 10;

if (x > 50) {
cout << to_string(x) + " is greater than 50" << endl;
}
else {
cout << to_string(x) + " is less than 50" << endl;
}

Code Visualizer

The if part of the if else statement is written as before. The else keyword
is not indented; it should be aligned with the if keyword. else is followed
by an open curly brace {. You do not use a boolean expression with else.
All code that should run when the boolean expression is false should go
before the closing curly brace }.

Be careful when expressing your boolean expression in terms of “less than


or greater than”. This does not take into account when the values being
compared are equal. Consider the code from above, but with x having the
value of 50.

int x = 50;

if (x > 50) {
cout << to_string(x) + " is greater than 50" << endl;
}
else {
cout << to_string(x) + " is less than 50" << endl;
}

Code Visualizer
The output of the program does not make sense. 50 is not less than 50.
Sometimes using <= and >= need to be used. Another solution is to update
the output to be more inclusive such as replacing is less than 50 with is
less than or equal to 50. In either case, be sure to think through all of
the possible outcomes, and make sure your code can function properly in
all of those scenarios.
Lab: Switch Statement

Tutorial Lab 3: Switch Statement


The switch case statement gives your program the ability to perform
different actions based on the value of a given variable.

int size = 3;

switch (size) {
case 1: cout << "Short"; break;
case 2: cout << "Tall"; break;
case 3: cout << "Grande"; break;
case 4: cout << "Venti"; break;
case 5: cout << "Trenta"; break;
default: cout << "Grande";
}

Code Visualizer

The variable used to make the decision is in parentheses following the


switch keyword. Inside curly braces, the cases listing the different values to
check are followed by a : and then the code that should run if the variable
is equal to that case’s value comes next. The last case, default, runs if none
of the other cases are true. Each code segment except the last one ends with
break; to signal the program to jump to the closing curly brace.

Remember to include break; statements at the end of each case. Check out
what happens when you remove them.

int size = 3;

switch (size) {
case 1: cout << "Short";
case 2: cout << "Tall";
case 3: cout << "Grande";
case 4: cout << "Venti";
case 5: cout << "Trenta";
default: cout << "Grande";
}

Code Visualizer
The output of the program does not make sense because the program
continues through all of the cases after the initial case is matched to a
value. In the example above, the program prints the command for case 3
as well as all of the commands that follow.
Lab Challenge: Month of the Year

Conditionals Challenge
Write a program that determines the month of the year based on the value
of a variable called month. The variable will be a number from 1 to 12 (1 is
January, 2 is February, etc.). Use a cout << statement to write the month to
the screen.

Click to compile your code

Test your code with a few different values


Learning Objectives: For Loops

Explain for loop syntax

Identify the causes of an infinite loop

Identify the relationship between patterns, loops, and


output
For Loops

For Loop Syntax


Before you can start writing a loop, you need to be able to identify
recurring patterns. Let’s take something simple:

cout << "Hello" << endl;


cout << "Hello" << endl;
cout << "Hello" << endl;
cout << "Hello" << endl;
cout << "Hello" << endl;

The pattern is cout << "Hello" << endl;, and it is repeated five times.
Since we know that the loop needs to run exactly five times, a for loop can
be used. Here is how you write a for loop that repeats five times. Copy the
code below into the text editor on the left and then click on the TRY IT
button to see the output. You can also click on the ++Code Visualizer++ link
below to see how a for loop works behind the scenes. If the visualizer does
not boot up correctly, click on the Refresh code button to restart it. Use the
Forward > and Back < buttons to navigate the program.

for (int i = 0; i < 5; i++) {


cout << "Hello" << endl;
}

Code Visualizer

Like conditionals, for loops are code blocks. However, in addition to a


boolean statement(s), you also declare, initialize, and increment a variable
called the loop iterator. All of the code that will be repeated are placed
between the curly braces {}. It is recommended that you indent the code
within the curly braces, but it is not necessary for the loop to run.

Understanding the Loop Header


Copy the code below and TRY IT.
for (int i = 0; i < 5; i++) {
cout << "Loop #" << i << endl;
}

Code Visualizer

The loop ran five times, but the variable i did not start at 1. Instead, it
started at 0. C++ , like most programming languages, starts counting from 0
by default. C++ will continue counting up to, but not including, 5. The i++
tells the system to continue counting up by 1 and the i < 5 tells the system
to stop counting before reaching 5.

challenge

What happens if you:


Replace "Loop #" << i in the code above to "Loop #" << i + 1?
Replace i < 5 with i < 6 in the loop header and change the print
statement back to "Loop #" << i?
Replace i < 5 with i <= 5 in the loop header?
Replace i++ with i-- in the loop header?

Code Visualizer

Infinite Loops
If you aren’t careful, you can wind up with an infinite loop. This means
that you have a loop that never ends. In the example above, if you change
i++ to i– then i will decrease by 1 after every iteration. This causes the loop
iterator to never reach its specified value. The boolean expression
continues to be true and the system continues to print until it times out.
Always check your loop header to ensure that it does what you intend for it
to do.
Turtle Graphics

Before continuing with loops, we are going to learn how to create graphical
output with the Turtle Graphics library. Like a pencil on paper, the turtle
object leaves a line as it moves around the screen.

Turtle Syntax
The first step is to create a screen for the turtle to move around in using
the command TurtleScreen followed by a variable name to call that screen
(i.e. screen). In parentheses after screen, you can specify the dimensions of
the screen in terms of width and height respectively (i.e. 400, 300). Then
we can create our turtle using the command Turtle followed by a variable
name for that turtle (i.e. tina). Finally in parentheses, we put in screen to
associate the turtle with the screen that we created previously. The code
below produces a turtle and a screen for the turtle to move around in.

TurtleScreen screen(400, 300); //width 400 pixels and height 300


pixels
Turtle tina(screen); //creates a turtle named tina inside the
screen

important

IMPORTANT

You may have noticed that there are additional lines of code within the
file in the text editor to your left. It is very IMPORTANT that you DO
NOT edit the header as that will cause the program to run incorrectly.

#include <iostream>
#include "CTurtle.hpp"
#include "CImg.h"
using namespace cturtle;
using namespace std;

The header above enables you to use the Turtle Graphics library as
well as the C Image library. Thus, the header should never be altered.
Turtle Commands
In order to view the turtle object, it is not enough just to create it. You must
give instructions to the turtle object in order for it to “move” around the
screen. Here is a list of basic turtle commands that you can give to tina the
turtle object:

Command Parameter Description


Where n represents
tina.forward(n) Move the turtle forward
the number of pixels
Where n represents
tina.backward(n) Move the turtle backward
the number of pixels
Where d represents
tina.right(d) Turn the turtle to the right
the number of degrees
Where d represents
tina.left(d) Turn the turtle to the left
the number of degrees

Let’s try this very simple command below. Copy it into the text editor on
your left and then click the TRY IT button to see the graphical output.

TurtleScreen screen(400, 300);


Turtle tina(screen);
tina.forward(100);
screen.exitonclick();

What does the screen.exitonclick() command do?

By default, the screen will close itself automatically once the program
reaches the end of the code. However, if you want the screen to remain
open, you can use screen.exitonclick() to tell the program to keep the
screen open until the screen is clicked with a cursor. Go ahead and try
clicking on the screen.

Turtle Output
Below is an image highlighting what happens after the TRY IT button is
clicked.
.guides/img/TurtleGraphicsFlow

1. TRY IT button is clicked by the user.


2. The Terminal tab is opened.
3. The terminal runs the command to compile the program and to display
the graphical output.
4. The output is displayed as a screen on the bottom left panel. You can
click the screen to close the output.
5. Click on the turtleloop.cpp tab to go back to the text editor if you want
to make changes to the program.
Turtle Coding: For Loop

Customize Your Turtle


You may choose to change the dimensions of your turtle screen whenever
you’d like. Also, the following table provides additional commands you can
use to customize tina the turtle.

Command Parameter Examples


Where COLOR
represents the
red, orange, yellow,
tina.pencolor({"COLOR"}) track or line color
green, blue, purple
you want tina to
leave behind
Where W
represents how any positive integer
tina.width(W)
wide (in pixels) (e.g. 1, 10, 123, etc.)
tina’s track is
Where SHAPE
triangle, indented
tina.shape("SHAPE") represents the
triangle, square, arrow
shape tina takes
TS_FASTEST, TS_FAST,
Where SPEED
TS_NORMAL,
tina.speed(SPEED) represents how
TS_SLOW,
fast tina moves
TS_SLOWEST

Turtle Challenges
Now that you know how to customize tina, try to recreate the images you
see below using your knowledge of for loops.

Challenge 1
.guides/img/TurtleChallenge1

Hint
There are multiple ways to accomplish this task but the trick lies within
finding the pattern and then repeating it a specific number of times. One
pattern in particular is to:

1. Go forward (creating a long line).


2. Make a right turn.
3. Go forward (creating a small line).
4. Make a right turn.
5. Go forward (creating another small line).
6. Make a right turn.
7. Go forward (creating a final small line).
8. Repeat steps #1 through #7 three more times for a total of four
iterations.

The pattern should look something like this:

Challenge 2

.guides/img/TurtleChallenge2

Hint
Since a circle has 360 degrees, you will need a loop that repeats 360 times.
Be careful about how far the turtle moves forward and turns. The circle
can get very big, very quickly.
Challenge 3

.guides/img/TurtleChallenge3

Hint
The pattern here is to move forward and make a right turn.

The trick lies within the fact that the distance the turtle moves has to get
larger as the loop advances. Think of some operators that you can use to
make the loop iterator variable get bigger during each iteration.

info

NOTE

Due to the dynamic and graphical nature of the Turtle Graphics library,
jagged lines and spotty pixels may appear randomly as the output is
being drawn. This is completely normal!

.guides/img/CppJaggedLine

Still having trouble with creating the outputs above?


Here are some sample solutions:

tina.pencolor({"blue"});
tina.width(2);
tina.shape("arrow");
tina.speed(TS_SLOWEST);

for (int i = 0; i < 4; i++) {


tina.forward(75);
tina.right(90);
tina.forward(25);
tina.right(90);
tina.forward(25);
tina.right(90);
tina.forward(25);
}

tina.pencolor({"red"});
tina.width(2);
tina.shape("square");
tina.speed(TS_FASTEST);

for (int i = 0; i < 360; i++) {


tina.forward(1);
tina.right(1);
}

tina.pencolor({"green"});
tina.width(2);
tina.shape("triangle");
tina.speed(TS_NORMAL);

for (int i = 10; i <= 200; i+=10) {


tina.forward(i);
tina.right(90);
}
Learning Objectives: While Loops

Explain while loop syntax

Identify the causes of an infinite while loop

Describe the break statement as it relates to a while loop


While Loops

While Loop Syntax


while loops, like for loops, use curly braces {} and indents for all
commands that should be repeated. However, for loops generally contain 3
elements (an initialized variable, a boolean expression involving that
variable, and a change in the value of that variable) while a while loop
usually contains just a boolean expression. The for and while loops below
produce the same results.

for (int i = 0; i < 5; i++) { int i = 0;


cout << "Loop#: " << i << while (i < 5) {
endl;
cout << "Loop# " << i << endl
}
i++;
}

Note that the variable declaration and initialization happen before the start
of the while loop and any changes that occur to the variable happen within
the body of the curly braces {}. On the other hand, everything happens in
one step within parentheses () when using a for loop.

Here is another example of a while loop that prints Hello based on the
value of the variable count.

int count = 5; // some random number set by user


while (count > 0) {
cout << "Hello" << endl;
count--;
}

Code Visualizer
challenge

What happens if you:


Change the while statement to while (count > -1 * count)?
Replace count-- in the code above with count = count - 2?
Change the while statement to while (count < 10)?

How does while (count > -1 * count) work?


To understand how the loop works, it’s best to substitute values in for the
variable count. In the first iteration, we have while (5 > -1 * 5), this
statement is true so the print command is executed. Since count gets
decremented by 1 with each iteration, the while loop condition changes
slightly every time like as follow:

while (4 > -1 * 4)
while (3 > -1 * 3)
while (2 > -1 * 2)
while (1 > -1 * 1)

Once the condition gets to while (0 > -1 * 0), it no longer holds true and
the while loop ends. The result is 5 Hellos being printed to the screen.

Infinite Loops
Infinite loops are loops that do not have a test condition that causes them to
stop. The following is a common mistake that results in an infinite loop:

int count = 5; // some random number set by user


while (count > 0) {
cout << "Hello" << endl;
}

Since the variable count never gets decremented. It remains at 5, and 5 will
forever be greater than 0, so the loop will never stop.

warning

Copy the code above and TRY IT to see what happens. C++ will
eventually stop the loop due to an output limit, but it may take some
time before this happens.

Why Use a While Loop?


If a while loop does the same thing as a for loop, then what is the purpose
of having both? while loops are actually more useful when you are waiting
for a certain event to occur. Imagine you are making a video game. The
game should continue until the player loses all of their lives. You don’t
know how long this will take, so a while loop is more appropriate. On the
other hand, if you have more specific loop parameters, a for loop will be
better.

int player_lives = 3;

while (player_lives > 0) {


// video game code
// goes here
}
Turtle Coding: While Loop

Instead of a for loop, recreate the images below using a while loop.

Turtle Graphics Review

tina.forward(n) - Where n represents the number of pixels.


tina.backward(n) - Where n represents the number of pixels.
tina.right(d) - Where d represents the number of degrees.
tina.left(d) - Where d represents the number of degrees.
tina.pencolor({“COLOR”}) - Where COLOR represents the track or line
color you want tina to leave behind.
tina.width(W) - Where W represents how wide (in pixels) tina’s track is.
tina.shape(“SHAPE”) - Where SHAPE represents the shape tina takes.
tina.speed(SPEED) - Where SPEED represents how fast tina moves

Challenge 1

.guides/img/TurtleChallenge1

Hint
The pattern is still the same:

1. Go forward (creating a long line).


2. Make a right turn.
3. Go forward (creating a small line).
4. Make a right turn.
5. Go forward (creating another small line).
6. Make a right turn.
7. Go forward (creating a final small line).
8. Repeat steps #1 through #7 three more times for a total of four
iterations.

However, a while loop usually contains only a boolean expression(s) in its


header. Thus, you must initialize a counting variable before the start of the
while loop. Also, that counting variable should be incremented inside the
body of the loop. The pattern you are trying to iterate is still the same:

Challenge 2

.guides/img/TurtleChallenge2

Hint
Since a circle has 360 degrees, you will need a loop that repeats 360 times.
Be careful about how far the turtle moves forward and turns. The circle
can get very big, very quickly.

Challenge 3

.guides/img/TurtleChallenge3

Hint
The pattern here is to move forward and make a right turn.

The trick lies within the fact that the distance the turtle moves has to get
larger as the loop advances. Think of some operators that you can use to
make the loop iterator variable get bigger during each iteration.

Sample Solutions
Here are some sample solutions using while loops:

tina.pencolor({"blue"});
tina.width(2);
tina.shape("arrow");
tina.speed(TS_SLOWEST);

int i = 0;
while (i < 4) {
tina.forward(75);
tina.right(90);
tina.forward(25);
tina.right(90);
tina.forward(25);
tina.right(90);
tina.forward(25);
i++;
}

tina.pencolor({"red"});
tina.width(2);
tina.shape("square");
tina.speed(TS_FASTEST);

int i = 0;
while (i < 360) {
tina.forward(1);
tina.right(1);
i++;
}

tina.pencolor({"green"});
tina.width(2);
tina.shape("triangle");
tina.speed(TS_NORMAL);

int i = 10;
while (i <= 200) {
tina.forward(i);
tina.right(90);
i+=10;
}
info

NOTE

In most cases, for loops and while loops can be used interchangeably.
It is up to you to decide which one is better suited for your task.
Break Statement

Infinite Loops Are Bad, Right?


Well, that depends. If an infinite loop is caused because the counting
variable isn’t incremented, then it’s a bug. However, some programmers
purposely create a condition that will always evaluate to true. Therefore,
the loop will always run. In such cases, a break statement is used to stop the
loop at a particular point in the program.

Take a look at the following program (also shown in the text editor on the
left).

#include <iostream>
using namespace std;

int main() {

srand(time(NULL)); // start randomizer every time program runs


while (true) {
cout << "This is an infinite loop" << endl;
int randNum = rand() % 100 + 1; // generate random number
between 1 and 100

if (randNum > 75) {


cout << "The loop ends" << endl;
break; // stop the loop
} // end if condition
} // end while loop

cout << "The program ends" << endl;

return 0;

Then click on the TRY IT button below a few times to run the code and see
the resulting outputs. You can also click on the ++Code Visualizer++ link
below to see how the code runs behind-the-scenes.

Code Visualizer
Even though while (true) will always evaluate as a true statement, the
loop never becomes infinite because of the break statement.

challenge

What happens if you:


Remove break; from the program?
Add break; to the line before cout << "The loop ends" << endl;?

Code Visualizer

Comparing While Loops

The while loops introduced on the previous pages look different from the
while loop covered on this page; however, they both have the same
components and behave similarly.

.guides/img/WhileLoopComparison
Learning Objectives: Nested Loops

Explain nested loop syntax

Identify the relationship between the variables in each


loop with the output produced
Nested Loops

A nested loop is a loop that exists inside of another loop. An advantage of


using nested loops is that the loops can work together to create unique and
complex outputs. However, due to their complexity potential, it is rare to
see the implementation of more than two nested loops. If possible, it is
recommended that you re-factor your code to reduce this complexity.

Syntax

The code below will draw a rectangle of 100 # in a 10 x 10 grid. The first
loop controls the row of output, while the second loop prints 10 # to the
screen.

for (int row = 0; row < 10; row++) { //outer loop


for (int col = 0; col < 10; col++) { //inner loop
cout << "#";
}
cout << "" << endl; //adds new line
}

Code Visualizer

challenge

What happens if you:


Replace row < 10 with row < 5 in the code above?
Replace col < 10 with col < 20 in the code above?

Code Visualizer

Nested Loop Coding Challenge 1

Using nested loops, write some code that outputs the following:
###########
###########
###########
###########
###########
###########
###########

Code Visualizer

Hint
The output is the same character (#). Make sure that your nested loops have
the right numbers in the boolean expressions to get the appropriate
number of rows and columns.

Nested Loop Coding Challenge 2

Using nested loops, write some code that outputs the following:

<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<

Code Visualizer

Hint
The output is a < when the outer loop variable is even (0, 2, 4) and a > when
the outer loop variable is odd (1, 3).

Nested Loop Coding Challenge 3

Using nested loops, write some code that outputs the following:

1
22
333
4444
55555

Code Visualizer

Hint
Note how the pattern goes from 1 to 5 starting on line 1 (through line 5) and
prints the line number equal to the amount of times as that numbered line.
First, the outer loop should start at 1. Second, the inner loop should run the
same amount of times as the row number up to the row number’s limit.

Sample Solutions

There are multiple ways to solve the challenges above but here are some
sample solutions using various combinations of for and while loops:

int row = 0;
while (row < 7) {
int col = 0;
while (col < 11) {
cout << "#";
col++;
}
cout << "" << endl;
row++;
}

for (int row = 0; row < 5; row++) {


if (row % 2 == 0) {
int col = 0;
while (col < 10) {
cout << "<";
col++;
}
cout << "" << endl;
}
else {
int col = 0;
while (col < 10) {
cout << ">";
col++;
}
cout << "" << endl;
}
}
for (int row = 1; row <= 5; row++) {
for (int col = 1; col <= row; col++) {
cout << row;
}
cout << "" << endl;
}
Lab: For Loop

Tutorial Lab 1: Using the For Loop


Copy the code below into the text editor on the left. Then click on the TRY
IT button to see the resulting output and ++Code Visualizer++ link (below)
to see how the program runs line by line.

for (int x = 0; x < 11; x++) {


if (x % 2 == 0) {
cout << "Even" << endl;
}
else {
cout << "Odd" << endl;
}
}

Code Visualizer

Program Summary

1. The for loop runs through all the values of the variable x from 0 to 10
as specified in the loop header.
2. For each value of x, an expression is evaluated using a conditional if
statement.
3. If x modulo 2 evaluates to 0, then print Even followed by a newline
character.
4. If x modulo 2 does not evaluate to 0, then print Odd instead followed by a
newline character.
Lab: While Loop

Tutorial Lab 2: The While Loop


Copy the code below into the text editor on the left. Then click on the TRY
IT button to see the resulting output and ++Code Visualizer++ link (below)
to see how the program runs line by line.

int counter = 0;
while (counter < 10) {
cout << counter << endl;
counter = counter + 1;
}
cout << "while loop ended" << endl;

Code Visualizer

Program Summary

1. A counter variable is initialized to keep track of how many times the


loop will be executed.
2. The loop will run as long as counter is less than 10.
3. Each time the loop runs, the integer value of counter is printed to the
screen.
4. The value of counter is then incremented by 1.
5. When counter reaches 10, the boolean expression no longer evaluates
to true and the program will exit the loop.
6. Before the program terminates, a statement is printed to the screen,
indicating that the while loop has ended.
7. Recall that the while loop must have an exit condition. By incrementing
the counter variable, we ensure that the loop will eventually end. If we
do not increment counter in this loop, we will create an infinite loop
because counter will never reach 10 or greater.
Lab: Break Statement

Tutorial Lab 3: Breaking from the While Loop


Copy the code below into the text editor in the upper left panel. Then click
on the TRY IT button to run the resulting program in the Terminal in the
lower left panel.

What does cin >> input; do?


The cin >> input; command records what a user enters on the screen and
stores that information in the variable input. Note that input is of type
double.
What do cin.good() and cin.fail() do?
cin.good() checks to see if the input entered by the user was successful
while cin.fail() checks to see if the input failed. Since input is of type
double, only numerical values entered by the user will cause cin >> input
to be successful, anything else will cause the input to fail.

double result = 0;
double input;

while (true) {
cout << "Enter a number to add to sum. ";
cout << "Or enter a non-number to quit and calculate sum." <<
endl;
cin >> input;
if (cin.good()) {
result += input;
}
if (cin.fail()) {
cout << "Sum = " << result << endl;
break;
}
}

Program Summary

1. Declare the variable result and initialize it to 0. result will store the
total of the summation.
2. Declare the variable input. input will store the information that the
user enters.
3. Next we set up a while loop with true as the expression in the loop
header. We do this because we want the loop to continue running and
storing information from the user. Since we don’t know how much
information the user will enter, a while loop is best for the situation.
4. The user is prompted to enter some information and that information is
stored in the variable input which was declared earlier.
5. If the information was stored into input successfully, the value in input
will be added to the value in result, our total summation.
6. If the information was not stored into input successfully, then the
program will print out the total summation result and exit the while
loop.
Lab Challenge: Loop Patterns

Nested Loop Example


One of the benefits of nested loops is that they can be used to construct
complex patterns. Imagine a classroom full of students and they are
distributed evenly into smaller groups and asked to form a single line with
their groups. The outer loop is like the group leader (represent in red and
L) and the inner loop is like the rest of the group members (represented in
blue and M.

.guides/img/NestedLoopExample

for (int x = 0; x < 3; x++) {


cout << "L" << endl;
for (int y = 0; y < 3; y++) {
cout << "M" << endl;
}
}
What is the pattern described by the above example? There are 3 leaders
and each leader has 3 members. However, note that the example shows the
students standing in a vertical line. What if you want to arrange the
students in a horizontal line like this instead?

.guides/img/NestedLoopHorizontal

By removing the << endl commands from the code above, you can
accomplish this task. Alternatively, you can also make use of an if and else
statement instead of a nested loop. Both ways will produce the same result.

for (int x = 0; x < 3; x++) { for (int x = 0; x < 12; x++)


cout << "L"; if ((x == 0) || (x == 4) ||
for (int y = 0; y < 3; y++) {
{ cout << "L";
cout << "M"; }
} else {
} cout << "M";
}

Nested For Loop Challenge

challenge

Assignment:
For this challenge, you will use your knowledge of patterns,
conditionals, and nested for loops to produce the following output:
XOXOXOXOX
OXO
OXO
XOXOXOXOX
OXO
OXO
XOXOXOXOX
OXO
OXO

Requirement:
Your program must include at least two for loops, one nested within
another, in order to receive credit. In addition, you are only allowed to
use, at most, two cout statements.

Hint

You should start by determining a pattern that repeats itself. One


noticeable pattern is:

XOXOXOXOX
OXO
OXO

Try creating that particular pattern first, then iterate that pattern by
modifying the existing loop(s).

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy