PART 1
PART 1
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.
.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.
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
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(/).
*/
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
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.
1. a data type
2. a name
3. a value
We will discuss each of these parts over the rest of this reading assignment.
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.
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
challenge
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.
challenge
important
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.
challenge
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
.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.
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
int one = 1;
int two = 2;
int three = 3;
int four = 4;
two = one;
three = two;
four = three;
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
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.
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
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
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().
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
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
String Concatenation
String concatenation is the act of combining two strings together. This is
done with the + operator.
challenge
Subtraction
Copy the code below and TRY IT.
int a = 10;
int b = 3;
int c = a - b;
cout << c << endl;
challenge
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.
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.
Division
Division in C++ is done with the / operator.
double a = 25.0;
double b = 4.0;
printf("%f \n", a / b);
challenge
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
Multiplication
C++ uses the * operator for multiplication.
int a = 5;
int b = 10;
cout << a * b << endl;
challenge
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
int a = 2;
int b = 3;
int c = 4;
double result = 3 * a - 2 / (b + 5) + c;
printf("%f \n", result);
Explanation
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.
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.
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;
Output
Function Input Type Example
Type
stoi() string int stoi(“10”)
challenge
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
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
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
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
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.
int a = 5;
int b = 7;
cout << boolalpha << (a <= b) << endl;
challenge
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
Hint(s)
9 is both greater than the value of false, which is 0, and the value of true,
which is 1.
int a = 9;
int b = 17;
cout << boolalpha << (a >= b) << endl;
challenge
Hint(s)
true is greater than false.
And
bool a = true;
bool b = true;
bool c = false;
cout << boolalpha << (a && b) << endl;
challenge
bool a = true;
bool b = true;
bool c = false;
cout << boolalpha << (a && b && c) << endl;
challenge
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;
challenge
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
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.
challenge
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.
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
Use the text editor on the left to enter the following code:
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
Use the text editor on the left to enter the following code:
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
.guides/img/PEMDAS
Use the text editor on the left to enter the following code:
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
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.
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.
!= <= >= ||
!
Learning Objectives: If Else
Statement
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
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.
if (10 % 2 == 0)
cout << "10 is even" << endl;
else
cout << "10 is odd" << endl;
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.
if (my_bool) {
cout << "The value of my_bool is true" << endl; }
else {
cout << "The value of my_bool is false" << endl; }
challenge
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; }
.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.
Code Visualizer
Learning Objectives: Switch Case
Statement
.guides/img/SwitchCase
switch (dayOfWeek) {
Code Visualizer
challenge
Code Visualizer
Switch Case vs. If Else
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
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
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).
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";
}
challenge
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++;
}
int x = 5;
if (x < 10) {
cout << "Less than 10" << endl;
}
Code Visualizer
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;
}
Code Visualizer
if (age < 20) { if ((age < 20) && (age > 10)) {
if (age > 10) { cout << "Teenager";
cout << "Teenager"; }
}
Code Visualizer
Lab: If Else Statement
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 }.
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
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
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.
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.
Code Visualizer
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
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.
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:
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.
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
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:
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
tina.pencolor({"blue"});
tina.width(2);
tina.shape("arrow");
tina.speed(TS_SLOWEST);
tina.pencolor({"red"});
tina.width(2);
tina.shape("square");
tina.speed(TS_FASTEST);
tina.pencolor({"green"});
tina.width(2);
tina.shape("triangle");
tina.speed(TS_NORMAL);
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.
Code Visualizer
challenge
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:
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.
int player_lives = 3;
Instead of a for loop, recreate the images below using a while loop.
Challenge 1
.guides/img/TurtleChallenge1
Hint
The pattern 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
Take a look at the following program (also shown in the text editor on the
left).
#include <iostream>
using namespace std;
int main() {
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
Code Visualizer
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
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.
Code Visualizer
challenge
Code Visualizer
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.
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).
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++;
}
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
int counter = 0;
while (counter < 10) {
cout << counter << endl;
counter = counter + 1;
}
cout << "while loop ended" << endl;
Code Visualizer
Program Summary
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
.guides/img/NestedLoopExample
.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.
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
XOXOXOXOX
OXO
OXO
Try creating that particular pattern first, then iterate that pattern by
modifying the existing loop(s).