Hi! Great day! Welcome to this course. Thank you for taking an interest in this course. Learning from this course will help you become an IT Professional.
 
Basic CPP Structure

Topic 1

C++ Anatomy

Upon reaching your home, you cleaned up the place, took out the manual, and opened it. Surprisingly, the book came with a preface before the actual lesson. From there, it writes:

“Before you learn how to code in C++, you must first learn its foundations in order to fully understand how it works. For this reason, I, the author of this book, would like to introduce to you C++’s parts and pieces that make it function as a whole:

C++’s basic program structure.

The Basic C++ Structure

Before we get on to the different functions and statements used to program in C++, we have to first understand the basic structure of the code that we need to make for it to run.

This is how a basic C++ program looks like:

#include<iostream>

int main(void) {

         return 0;

}

Let’s break the different parts of the code above:

⬤ #include<iostream> – iostream is a “library” in C++. Think of a library as a toolbox. Inside a toolbox, just like in real life, lies many tools that you can use. Similarly, iostream is a toolbox developed by the programmers of the C++ language which contains “functions” that we could use in our own program (more on this later). By saying #include<iostream> we’re basically saying that we’re going to use the iostream toolbox in the program that we’re about to make.

⬤ int main(void) – for now, just don’t mind the int and the void (in the future programs/codes that you’ll be making in this course, just add them). The main basically is the entrypoint of your program. If we were to imagine that our whole program is a room, the main is basically the “door” of our program. So when our code is executed by the computer, it’ll find the main and will start executing all the code inside it (the ones inside the curly braces). For now, as you can see, there’s only one line of code inside the curly braces of the main which is the return 0;

⬤ return 0; – again, for now, just do this for the programs that you’ll be making in this course, but basically, this line of code is the exit status of our application. If we return 0 as the exit status, that means that our program worked fine until the end, without errors.

Did you know?

You can actually write the main() function without putting the word void inside its parentheses, and it will still work the same, like this syntax:

Code

Main.Cpp

#include<iostream>

int main() {

    return 0;

}

However, although it can be removed, it’s always better to place the void inside the parentheses for clarity and readability.

Header Files

C++ has a standard library that contains tons of built-in header files which can be useful when coding, but these can only function if we call it using the #include directive.

Before we are able to use any function in C++, we have to identify first which library is needed to use the function. Here are some of the most basic ones available:

<iostream>

Contains standard input-output stream functions. These functions are for taking inputs from the user and displaying output to the user.

<iomanip>

Contains output manipulators. These functions are used to manipulate the output of our program (e.g. formatting a decimal number to only display its 2 decimal places)

<cmath>

Contains common mathematical operations. These functions are for doing mathematical operations such as sqrt (squareroot), pow (power/exponent), cos (cosine), etc.

<cctype>

Contains functions to classify and transform individual characters.

<cstring>

Contains functions to manipulate “strings”. Strings are just multiple characters combined together such as words, phrases, and sentences.

There are still a lot of header files in C++ and you’ll get to know them as you continue learning. Don’t worry if you won’t be able to memorize them for now because this lesson only gives you an overview of the common library/header files that are used in C++. We will be getting to know more about each of these libraries in the future lessons, like when and how to use them, so just continue learning and keep going!

How to Print

Topic 1

How to Talk

Upon reading an overview of the C++ structure, your excitement to learn has increased more than ever. With such excitement, you couldn’t wait another day and immediately flipped the page to the next chapter of the book. From there, it says:

“It is not flexible movements nor is it a perfect human face that makes a creature more human-like; it is its ability to speak and communicate with other humans. With it, the robot will now be able to talk with humans about its name, or even just about the food he likes to eat every morning (sipping a glass of gasoline in the morning, I guess?). Hence, we will be starting off with C++’s own method of speaking – the std::cout function.”

std::cout Syntax

The std::cout statement is a built-in output function in C++ that allows the computer to print out on the screen a certain text or number. When printing strings (or text), it follows the following syntax:

std::cout << “Hello World”;

The text to be outputted is enclosed with a pair of double quotes (“) and the whole line of code ends with a semicolon (;).

However, we cannot use the std::cout function immediately without including the header file that we need to use these standard input/output functions. To do that, we have to make use of the built-in library!

From the previous lesson, we have known that the header file for input and output functions is iostream and to call it, we have to use #include and put the header file name inside a pair of angle brackets. Hence, at the top of your code before the main() function, we shall include this in the code:

#include<iostream>

So, when we want to greet the world using a program in C++, we can now do this:

Code

Main.Cpp

#include<iostream>

int main(void) {

    std::cout << “Hello World”; 

    return 0;

}


Did you know?

Every single-lined statement in C++, except for preprocessor directives, will always end with a semicolon, so don’t ever forget those little punctuations, or else you’ll get stressed out over failing to run you code successfully due to a syntax error! Here, let me show you what will happen if you forget one. Try running the code below:

Code

Main.Cpp

#include<iostream>

int main(void) {

    std::cout << “Hello World”

    return 0;

}

Sample Problem 1

Hello, Programmer!

Let’s try to make Cody emphasize his name when speaking!

The code needed to do that is already prepared for you. To see the magic happen, run the code by clicking on the Run Code button now!

Code

Main.Cpp

#include<iostream>

int main(void) {

    std::cout << “My name is ‘Cody’.”;

    return 0;

}

Topic 2

When to Pause

Feeling happy about your learning on how to print using C++, you then turned to the next page on the instruction manual. From there, it writes:

“Speaking is indeed a great skill of a robot and takes it a bit closer to being more human-like. However, humans get tired of speaking, too, and needs some time to pause or take a break before getting back to the topic. As such, if the robot talks endlessly for a long period of time, surely, it will sound monotonous and boring to others, and we wouldn’t want that to happen, do we?

Therefore, in order to let the robot learn how to take a break while speaking, we will program him with the use of C++’s basic escape sequences.”

Definition

Before we go on about the kinds of escape sequences, let us describe what it does first.

Escape sequences are special characters characterized by a backslash (\) and a letter or symbol beside it. It is used in std::cout statements to show spaces, new lines, or show symbols that cannot be outputted using the normal way of printing.

There are a lot of escape sequences available in C++, but we will only be tackling about the most basic ones.

Types

Each escape sequence has its own function when used in printing. Here are some basic ones that are made available for use in C++:

\t

Prints a horizontal tab space:

std::cout << "Hello\tWorld";
Output:
Hello    World

\n

Prints the proceeding text to a new line.

std::cout << "Hello\nWorld";
Output:
Hello
World!

\\

Prints a backslash

std::cout << "\\";
Output:
\

\”

Prints a double quote inside texts enclosed in double quotes.

std::cout << "\"";
Output:
"

Sample Problem 1

Give me Some Space!

When you want to let your words breathe when speaking, and to avoid sounding like a robot (even if you already are), you have to give your words some space, even just a little. But if you’d like to take longer pauses when speaking, you could use some help with the tab escape sequence.

Say, for example, you want to announce something, and you’d like to put some excitement with pauses, you do it like this!

Code

Main.Cpp

#include<iostream>

int main(void) {

    std::cout << “Are you ready \t to be the next \t Coding Hero?”;

    return 0;

}

Sample Problem 2

Making a Haiku

You know what’s the good thing about being human-like? Being creative! And one proof of being creative is writing a poem. For starters, let’s teach Cody how to make a haiku! It’s a 5-7-5 syllable poem composing of three lines. Oh! Speaking of lines, we need something to create them, and this calls for, the new line escape sequences!

Run the code to see the magic!

Code

Main.Cpp

#include<iostream>

int main(void) {

    std::cout << “I love my Cody\nIt’s part of my family\nIt makes me happy.”;      

    return 0;

}

Topic 3

Manipulating the Situation

The robot you’ve programmed, Cody, now learns how to speak and pause like a human kiddo! But you notice that there is still something else missing in order to complete his speaking ability. Eager to find out what it is, you then turned to the last page of the current chapter of the manual:

“Speaking and learning to pause are two essential skills that your robot needs to be able to talk like human, but there is one last recipe that completes the basic human-like speaking skills, and that is the ability to manipulate and construct properly the things it wants to say.”.

std::fixed and std::setprecision()

So far, we’ve been printing strings (or text) only. How about decimal numbers, how do we print them? It’s actually just the same process!

std::cout << 5.1534;

and the output, as you guess it, would be:

5.1534

But what if we want to manipulate it so that we can only display three of its decimal places, how do we do that?
To achieve that we need to use std::fixed from <iostream> and std::setprecision from <iomanip>. The code would look like this:

Code

Main.Cpp

#include<iostream>

#include<iomanip>

int main(void) {

    std::cout << std::fixed;

    std::cout << std::setprecision(3);

    std::cout << 5.1534;

    return 0;

}

Don’t get overwhelmed, it’s actually pretty easy to understand! Let’s break it down:

⬤ #include<iomanip> – to be able to use std::setprecision, we need to include the <iomanip> library

⬤ std::cout << std::fixed; – this is needed to change the default formatting of the numbers that are printed to “fixed-point notation”. I know, that sounds complex, but to make things simple, we need to do that because if we don’t, the next line (the std::setprecision) that actually sets the number of decimal places, will include the whole number as part of the specified number of digits. That means, in the above example, the output would be 5.15 (5.15 is 3 digits, including the whole number) and not 5.153 as what we are trying to achieve

⬤ std::setprecision(3) – this is the line that sets the number of decimal places to be printed.

We’re not done yet! You might be thinking that that’s a lot of lines of code just to format the number of decimal places, isnt’ there an easier way? Spoiler alert, there is and it looks like this:

Code

Main.Cpp

#include<iostream>

#include<iomanip>

int main(void) {

    std::cout << std::fixed << std::setprecision(3) << 5.1534;

    return 0;

}

Combining Strings and Numbers

Now, what about if we want to output strings and numbers at the same time? Would that be possible? You’re right, it sure is! Take a look at this one:

Code

Main.Cpp

#include<iostream>

int main(void) {

    std::cout << “Hello, my name is Cody.\n”;

    std::cout << “I am ” << 999999 << ” years old.\n”;

    std::cout << “I have been living in 1010 CC Street for over ” << 1000 << ” years.”;

    return 0;

}

Combining Strings and Numbers

Now, what about if we want to output strings and numbers at the same time? Would that be possible? You’re right, it sure is! Take a look at this one:

Code

Main.Cpp

#include<iostream>

int main(void) {

    std::cout << “Hello, my name is Cody.\n”;

    std::cout << “I am ” << 999999 << ” years old.\n”;

    std::cout << “I have been living in 1010 CC Street for over ” << 1000 << ” years.”;

    return 0;

}

But adding is sometimes not too clear because it’ll seem that it’s part of the message that we’re trying to print.

There’s actually another way and that is to use std::endl. Take a look at this one:

Code

Main.Cpp

#include<iostream>

int main(void) {

    std::cout << “Hello, my name is Cody.” << std::endl;

    std::cout << “I am ” << 999999 << ” years old.” << std::endl;

    std::cout << “I have been living in 1010 CC Street for over ” << 1000 << ” years.”;

    return 0;

}

Sample Problem 1

How Much?

There will come a time where Cody will need to buy something at a grocery or a convenience store with his human friends in the future, and for it to be able to recognize the money format with cents in the country, he has to learn to limit his digits into two decimal places, since it would be weird if he would just directly blurt out the amount of money in 6 decimal places, right?

Let’s apply what we just learned above! Let’s see how it works.

Let’s see how it works!

Code

Main.Cpp

#include<iostream>

#include<iomanip>

int main(void) {

    std::cout << “An apple costs P” << std::fixed << std::setprecision(2) << 20.252598;

    return 0;

}

Variables

Topic 1

No Dead Airs

Just a few days ago, your Cody acquired its human-like speaking ability! But what would happen if the robot is prompted to speak about common things, like its name or age? Wandering in thoughts, you took the manual from your side and began reading the second chapter. Starting off, it says:

“Being able to speak is one thing that makes a robot close to being human, but to speak instantly on basic things like its name, age, or an answer to a yes/no question, without taking too much time for such a thing, takes your robot to the next level at being human-like. But this cannot be achieved by merely typing in the data manually (that’s exhausting, you know), so this calls for the help of the “containers” of data in C++ – variables.”

Variable Declaration

Variables are objects that are used to store values. As an object, they act as containers or buckets where the data will be put into and stored. In C++, declaring a variable uses this kind of syntax:

data_type variable_name;

Variable declaration in C++ requires 3 parts:
⬤ the data type it will possess
⬤ the variable name of your choice, and
⬤ a semicolon at the end

Unlike other languages that allow their variables to change data types whenever the programmer wants to, C++’s variable data types are defined upon declaration and will always hold that data type afterwards. There are tons of data types available in C++, but here are the basic ones that you can use in variable declaration:

char

Character (a letter, symbol, or white space). This should be enclosed in single quotes. Example:

char letter = ‘A’;

int

Integer (whole number ranging between ±32767). Example:

int a = 5;

int b = -10;

float

Floating point values (real numbers that can handle up to 7 decimals). To indicate that it is float, you should add an `f` at the end of the value. Example:

float a = 5.5f;

float b = 10.3f;

double

Double floating point values (real numbers that can handle up to 15 decimals). Double is just the same as a Float but can hold larger numbers. Example:

double a = 1000.5356;

double b = 5134995;

bool

Truth values (true/false). Example:

bool a = true;

bool b = false;

Did you know?

If you wish to declare multiple variables of the same data type, you can actually just use one line declaration and separate each variable name with a comma, like this:

data_type varname1, varname2;

Or even initialize its values to your liking:

data_type varname1 = value, varname2 = value;

Don’t believe me? Then let’s try it in a real code! See this one below:

#include<iostream>

int main(void) {

         int num1 = 5, num2 = 10, num3 = 15;

         double val1 = 3.3, val2 = 4.4;

         bool val3 = true, val4 = false;

         return 0;

}

Note that a variable’s data type remains as it is once declared, so when you try to assign a letter to an integer variable, the character value will be converted into its integer equivalent. The same thing happens when you assign a float to an integer variable, it will only take the whole number from the assigned value.

To elaborate, try running the code below and see what’s the output:

Code

Main.Cpp

#include<iostream>

int main(void) {

    int n = 5.92;

    std::cout << n;

    return 0;

}

As you can see, the output is just 5 instead of 5.92. That’s because the data type of n is int and int’s can only hold integer (whole number) values, that’s why the decimal part was discarded.

Let’s try another one below:

Code

Main.Cpp

#include<iostream>

int main(void) {

    int letter_value = ‘A’;

    std::cout << letter_value;

    return 0;

}

As you can see in the code above, we tried to assign the character ‘A’ to the variable letter_value which is an int. When we tried running the code, the output became 65 and not A, why is that?

That’s because the character A was converted to its integer equivalent ASCII value, which is 65. All the characters (and by all, I mean including the spaces, the weird characters, the emojis), have their equivalent ASCII values. The capital A is 65, the capital B is 66. The small a is 97, the small b is 98.

If you want to know the equivalent ASCII values of all the characters, you can just look it up on every programmer’s best friend, Google! Just type, “ASCII Table” and you’ll see a lot of references in there.

Using Variables With Strings

To get a clearer view on the use of variables, let us take this one for example:

Code

Main.Cpp

#include<iostream>

int main(void) {

    // We create an int variable to represent age and assign 4 to it.

    int age = 4;

    std::cout << “I’m Cody and I am already ” << age << ” years old.” << std::endl;

    std::cout << “It has been ” << age << ” years since I have first seen the world.” << std::endl;

    return 0;

}

As you can see, we can now reuse a variable as much as we want to! It is a very efficient way to use the same word/value over and over in different contexts without manually typing it over and over again.

Imagine if we were printing the age in the above code 10000 times and then we decided to change the value of age to 5 (because Cody just had his birthday!), then we only need to change one line of code, not 10000 lines of code! Efficient, ain’t it?

Did you know?

The text after double slashes (//) that you see in the code above will not be executed because this is just a comment.

Comments are very useful as they serve as guides to the code especially when you want to look at your code again after a long time, or if someone else tries to read the code you’ve written, it would easily be understood by anyone who looks at it again.

Let’s see it again in action below:

Code

Main.Cpp

#include<iostream>

int main(void) {

    // haha, I can write anything here and

    // my code will not crash. I am so

    // AWEEEESOOOMEEEEEE!!! 😀

    std::cout << “Hello World!”;

    return 0;

}

Now, the comment with the double slashes (//) is called a single line comment. There’s another type of comment, and that is the multiline comment. Check this one out:

Code

Main.Cpp

#include<iostream>

int main(void) {

    /*

        haha, I can write anything here and

        my code will not crash. I am so

        AWEEEESOOOMEEEEEE!!! 😀

    */

    std::cout << “Hello World!”;

    return 0;

}

As you can see, multiline comments are done with the use of /* and */. Basically, anything in between them are comments so you don’t have to keep on typing double slashes in each line of code.

Comments are helpful because they help explain what your code does. They can also be used to conceal parts of your code instead of erasing it completely when testing other parts of code when debugging.

// Cool, we’re learning!

Changing Variable Values

Just like in other programming languages, we can change and overwrite the value assigned in C++ variables as well! The only thing we have to do is to follow the same syntax as when declaring a variable with an assigned value using the assignment operator, but without typing in the data type anymore, like this syntax:

variable_name = value;

For example, when we want to update the age that was initially assigned to the variable, we can do it like this:

Code

Main.Cpp

#include<iostream>

int main(void) {

    int age = 4;

    std::cout << “Current age: ” << age << std::endl;

    // let’s increase the age by 1

    age = 5;

    std::cout << “Age a year after: ” << age << std::endl;

    // let’s try doing it once more!

    age = 6;

    std::cout << “Age another year after: ” << age << std::endl;

    return 0;

}


Did you know?

You can also declare constant variables as well, using the const keyword! Constant variables are special type of variables whose values can’t be changed.

Declaring a constant variable using that follows this syntax:

const data_type CONSTANT_NAME = value;

Usually, the naming of constants are in all capital letters to easily identify that the variable is indeed a constant. See this sample code below where we made a constant:

Code

Main.Cpp

#include<iostream>

#include<iomanip>

int main(void) {

    const double PI = 3.1415926;

    std::cout << “PI with only 2 decimal places: ” << std::fixed << std::setprecision(2) << PI;

    return 0;

}

In the above code, if we try to change the value of PI, we’ll get an error. Try experimenting with it above!

There’s another way to define constants in C++, and that is with the use of preprocess directives. Check this one below:

Code

Main.Cpp

#include<iostream>

#include<iomanip>

#define PI 3.1415926

int main(void) {

    std::cout << “PI with only 2 decimal places: ” << std::fixed << std::setprecision(2) << PI;

    return 0;

}

The code above works exactly the same as the previous one. The only difference is how we defined the constant PI!

Sample Problem 1

First Day of Class

Let’s think about the time when Cody will now be able to blend in with humans, and speak just like a human kid. Since children of its age (from the time it was created) needs to go to school, we need to let it prepare for its introductory message on the start of classes! But to give it a twist, it only has to tell the first letter of its name and age.

Let’s try that out by using variables! Set his age and first letter of his name, and put it together with some cliché introductory statements, like this:

Code

Main.Cpp

#include<iostream>

int main(void) {

    char firstLetterOfName = ‘C’;

    int age = 4;

    std::cout << “The first letter of my name is ” << firstLetterOfName << ” and I am ” << age << ” years old.”;

    return 0;

}

Topic 2

How Should I Name You?

You finally learned how to declare variables, and that takes Cody one step closer towards a more natural way of speaking! But when you become forgetful about what you did in your code, how would you be able to properly identify what variables to use when the need arises? Looking for answers, you turned to the next page of the manual again, and there lies the answer which states:

“Robots speak without lagging out when they have ready-to-use information stored in variables. But how would it identify what data is stored in those variables? This is why proper variable naming is important. With clear, distinct names, the robot and you as the programmer would not be confused anymore as to which variable to use. In C++, we have to learn some naming conventions.”

Variable Naming Restrictions

You can name a variable anything as long as it makes sense to you, but it would definitely be much better if it explains what the data it holds is all about. For example:

// Not good:

int a = 15;

bool asd1 = false;

// Good:

int age = 15;

bool isAdult = false;

But when naming variables in C++, there are restrictions and guidelines to follow in order to make the best out of it. Here are some that are worth mentioning:

1) Variable names will only compose of letters, numbers, and/or a single symbol, underscore (_). Moreover, all names must always start with a letter or an underscore (A-Z, a-z, _).

// Not okay (will result to errors):

int 1num, my+age, $Dollars;

// Okay:

int num1, my_age, Dollars, _Dollars;

2) Avoid using lengthy names for a variable. As much as possible, just make sure that the first three letters of its name makes sense when you read it so that it will be easy to remember and easy to type as well.

// Not good:

int this_is_a_number, my_actual_age;

// Good:

int num, age;

3) On the other hand, also avoid using very short names for a variable that it won’t make sense the first time you read them.

// Not good:

int s, a;

// Good:

int num, age;

Did you know?

C++ is case-sensitive. In this sense, an uppercase letter and a lowercase letter are treated as two different characters!

Don’t believe me? Try this one to see it for yourself (take a good look at the name of the variables)!

Code

Main.Cpp

#include<iostream>

int main(void) {

    int age = 20;

    int AGE = 24;

    int aGe = 31;

    std::cout << “Age in small letters: ” << age << std::endl;

    std::cout << “Age starting with a capital letter: ” << AGE << std::endl;

    std::cout << “Age in weird casing: ” << aGe << std::endl;

    return 0;

}

Naming Styles

If there are rules and guidelines, then there are also different styles in naming variables! Feel free to use the style that best fits the data you will store in a variable. Here are a few common styles used:

Flat Case

All words are in lowercase but connected directly. Examples:

int variablename;

bool anothervariablename;

Camel Case

Uncapitalized first word, capitalized proceeding words (like a camel shape) and connected directly. Examples:

int variableName;

bool anotherVariableName;

Pascal Case

All words are capitalized and connected directly. Examples:

int VariableName;

bool AnotherVariableName;

Snake Case

All words are in lowercase and connected by an underscore (_). Examples:

int variable_name;

bool another_variable_name;

Macro Case

All words are in uppercase and connected by an underscore (_). This casing is often used in constants. Examples:

int VARIABLE_NAME;

bool ANOTHER_VARIABLE_NAME;

Whichever style you choose to use when naming variables, just stick to that one style to avoid confusion and to observe naming consistency, okay?

Arithmetic
Topic 1

Basic Math

Cody has finally stepped up on acting and sounding more human-like than from when he started! Now it shall master another basic element of speaking: numbers! And so, you opened the instructions manual to its fourth chapter which says:

“Words are enough for speaking, but when solving problems in school or in life in the future years, a robot must have the ability to do basic math and handle numbers! Well, computers are actually capable of simple and complex calculations, but it won’t ever work if the programmer does not know how to code it! Hence, in order for your learn math basics, we have to get familiar with some basic arithmetic operations in C++.”

The Symbols

Just like your elementary mathematics, C++ also has its similar set of math operations, with an addition of some other set of symbols for specified purposes. Here are the following:

+

Adds numbers on both sides of the operator. Examples:

int a = 5;
int b = 10;
int total1 = a + b;
std::cout << total1; // output would be 15
 
// we could also add a variable with a number
int total2 = a + 20;
std::cout << total2; // output would be 25
 
// we could also print immediately the sum
std::cout << 100 + 100; // output would be 200

Subtracts the right operand from the left operand. Examples:

int a = 5;
int b = 10;
int total1 = a - b;
std::cout << total1; // output would be -5
 
// we could also subtract a variable with a number
int total2 = a - 1;
std::cout << total2; // output would be 4
 
// we could also print immediately the difference
std::cout << 100 - 50; // output would be 50

*

Multiplies numbers on both sides of the operator. Examples:

int a = 5;
int b = 10;
int total1 = a * b;
std::cout << total1; // output would be 50
 
// we could also multiply a variable with a number
int total2 = a * 5;
std::cout << total2; // output would be 25
 
// we could also print immediately the product
std::cout << 100 * 50; // output would be 5000

/

Divides the left operand by the right operand. If the holder of the result is an int, the decimal part is discarded. Examples:

int a = 10;
int b = 5;
int total1 = a / b;
std::cout << total1; // output would be 2
 
a = 13
b = 4;
int total2 = a / b;
std::cout << total2; // output would only be 3 (the decimal part is discarded)
 
double c = 13;
double d = 4;
double total3 = c / d;
std::cout << total3; // output would be 3.25
 
// we could also print immediately the quotient
std::cout << 100 / 50; // output would be 50

%

This is the modulo operator. Gets the remainder of the division (not the quotient). This operator only works if both the left and the right operands are integers. Examples:

int a = 10;
int b = 3;
int total1 = a % b;
std::cout << total1; // output would be 1
 
// we could also use the operator with a variable and a number
int total2 = a % 5;
std::cout << total2; // output would be 0
 
// we could also print immediately the remainder
std::cout << 100 % 51; // output would be 49
 
// this one below would result to an error because
// the right operand is a double
int c = 5;
double d = 5.2;
double total3 = c % d; // ERROR!
 
// even if the value of the double is a whole number,
// it still won't work
int e = 5;
double f = 5;
double total4 = e % f; // ERROR!

Shortcuts in Overriding

Now, there are times when we wish to perform calculations on the value of a variable and then overwrite the value of the variable by the result it garnered. Normally, we can do so by doing these:

varName = varName + value;
varName = varName - value;
varName = varName * value;
varName = varName / value;
varName = varName % value;

But there is actually a shortcut to writing these codes, and that is through directly typing together the assignment operator and arithmetic operator to be used, like these:

+=

This is an equivalent of var = var + value.

Syntax:

var += value;

-=

This is an equivalent of var = var – value.

Syntax:

var -= value;

*=

This is an equivalent of var = var * value.

Syntax:

var *= value;

/=

This is an equivalent of var = var / value.

Syntax:

var /= value;

%=

This is an equivalent of var = var % value.

Syntax:

var %= value;

Increment and Decrement Operators

Incrementing a number is basically increasing it by 1. Decrementing on the other hand is decreasing it by 1.

In C++, you can do it by doing:

varname = varname + 1;
varname = varname - 1;

But that’s not so cool, isn’t it? There’s actually an increment and decrement operator in C++ and it looks like this:

varname++;
varname

The first line above is the same as varname = varname + 1 and the second line above is the same as varname = varname – 1;

Sample Problem 1

Paycheck

I want Cody to help me evenly divide my PHP 143,000 salary into 3 people. However, it is good to remember that money will only contain 2 decimals as centavos in Philippine Peso.

Now, we need to recall again how to format the number of decimal places. Still remember that?

Code

Main.Cpp

#include<iostream>

#include<iomanip>

int main(void) {

    double salary = 143000;

    double numberOfPeople = 3;

    double sharePerPerson = salary / numberOfPeople;

    std::cout << “Share per person = P” << std::fixed << std::setprecision(2) << sharePerPerson;

    return 0;

}

Sample Problem 2

Area of Triangle

In mathematics, there are lots of formulas that you need to remember, especially in perimeters, areas, and volumes. For now, let’s train Cody to master how to get the area of a triangle with one decimal place!

It’s actually simple, though, if you know the formula, and here it is!

Area of Triangle = (base*height)/2

In this case, the base and height can be a decimal so it has to be a double or a float. It also cannot be negative (that’s impossible for shapes to exist), but if it comes to that situation, always remember that multiplying and dividing values of the same sign returns a positive value, while those of opposite signs returns a negative one.

For the meantime, study the code below and try running it:

Code

Main.Cpp

#include<iostream>

#include<iomanip>

int main(void) {

    double base = 10;

    double height = 2.5;

    double area = (base * height) / 2;

    std::cout << “Area of the triangle: ” << std::fixed << std::setprecision(1) << area;

    return 0;

}

Topic 2

Like a Scientific Calculator

Being able to perform basic math would let Cody keep up with early elementary kids, but what would happen if it were to face complex math involving exponents, square roots, and the like? Surely, there must be some way. Pumped up from the piled-up curiosity in you, you then looked for help in the manual and found your answer on the third chapter’s second topic:

“If C++ has its ready-to-use basic operations, then there should also be built-in complex math operations as well! C++ does have some built-in functions that a scientific calculator has, all in one library. Therefore, today we shall learn how to let the robot access this library and use some basic math operations.”

The cmath Header File

Before we can use some of the functions that are found on a scientific calculator, we have to include the library where those functions are contained, into the code. C++ has tons of header files in store that can actually be used when needed (we already talked about the most common ones on the first chapter, remember?).

Let us first recall how to include a built-in header file into the C++ code. To do that, we shall write it just like including the iostream library, like this:

#include<iostream>

And in our case, since we need some mathematical functions to be made available for use in C++, we’re going to use cmath, just like this:

#include<cmath>

With this, you can now use mathematical functions in your code!

When including header files in your code, it is good to note that we should only do so on the topmost part of the code by convention. Once it’s already typed in there, then it is good to use! We shall also only include header files only if we use them for good programming practice.

Basic Math Functions

The cmath header file contains a lot of advanced math functions that can be used for specific purposes. But for starters, here are some basic ones that are commonly used:

pow()

Returns the value of the left operand (base) raised to the power of the right operand (exponent). Example:

Syntax:

pow(base, exponent)
#include<iostream>
#include<cmath>
 
int main(void) {
         std::cout << pow(2, 3) << std::endl;
         std::cout << pow(8, 2) << std::endl;
         std::cout << pow(2.5, 4) << std::endl;
 
         return 0;
}
Output:
8
64
39.0625

sqrt()

Returns the square root of a number. Example:

Syntax:

sqrt(num)
#include<iostream>
#include<cmath>
 
int main(void) {
         std::cout << sqrt(9) << std::endl;
         std::cout << sqrt(25) << std::endl;
         std::cout << sqrt(3) << std::endl;
 
         return 0;
}
Output:
3
5
1.73205

floor()

Rounds down a number to the largest integer less than or equal to the number. Example:

Syntax:

floor(num)
#include<iostream>
#include<cmath>
 
int main(void) {
         std::cout << floor(3.3) << std::endl;
         std::cout << floor(7.5) << std::endl;
         std::cout << floor(2.9) << std::endl;
         std::cout << floor(10) << std::endl;
 
         return 0;
}
Output:
3
7
2
10

ceil()

The opposite of floor. Rounds up the number to the smallest integer greater than or equal to the number

Syntax:

ceil(num)
#include<iostream>
#include<cmath>
 
int main(void) {
         std::cout << ceil(3.3) << std::endl;
         std::cout << ceil(7.5) << std::endl;
         std::cout << ceil(2.9) << std::endl;
         std::cout << ceil(10) << std::endl;
 
         return 0;
}
Output:
4
8
3
10

fabs()

Returns the absolute, positive value of num. Example:

Syntax:

fabs(num)
#include<iostream>
#include<cmath>
 
int main(void) {
         std::cout << fabs(-3.2) << std::endl;
         std::cout << fabs(5.9) << std::endl;
         std::cout << fabs(-15) << std::endl;        
 
         return 0;
}
Output:
3.2
5.9
15


These are just some of the functions found in the cmath library. There’s actually a lot more and if you want, you can just google the cmath library.

Did you know?

The values generated by cmath functions are of data type double by default. That means that you need to use double variables to store their results. See this one below:

Code

Main.Cpp

#include<iostream>

#include<cmath>

int main(void) {

    double squareRootResult = sqrt(9.3);

    double powerResult = pow(5.5, 2);

    std::cout << squareRootResult << std::endl;

    std::cout << powerResult << std::endl;

    return 0;

}

However, if you wish to transform that value into some other data type, like making it an integer to perform math calculations and more, you can typecast the result into an integer, like this:

Code

Main.Cpp

#include<iostream>

#include<cmath>

int main(void) {

    int squareRootResult = (int) sqrt(9);

    int powerResult = (int) pow(5.5, 2);

    // check the output here and compare them with 

    // the ones above from the previous code

    std::cout << squareRootResult << std::endl;

    std::cout << powerResult << std::endl;

    return 0;

}

Sample Problem 1

Exploring Exponents

Let’s try out exponents this time! Are there wonders in this one as well?

You see, all mathematical operations used here are what is applied in human math. Therefore, when talking about exponents, when we raise it to 0, no matter the base, the value will always return 1. Moreover, if a number is raised by 1, then the result will always be the value of the base.

In addition, when we put a negative number on the base side, it will return the same value as it was just a normal value, and will carry out the sign of the number as positive when exponent is even and negative when exponent is odd.

When putting negative numbers on the exponent side, on the other hand, it means that entire result (regardless of signs) is put as a denominator of a fraction with numerator 1 (1/n).

We’ve given the code out for you to try out:

Code

Main.Cpp

#include<iostream>

#include<cmath>

int main(void) {

    std::cout << “4^0 = ” << pow(4, 0) << std::endl;

    std::cout << “4^1 = ” << pow(4, 1) << std::endl;

    std::cout << “-4^0 = ” << pow(-4, 0) << std::endl;

    std::cout << “4^-2 = ” << pow(4, -2) << std::endl;

    return 0;

}

Topic 3

Which to Solve First?

Cody is now one more step away from mastering number manipulation! Eager to know the last recipe to mastering this, you turned to the last page of the current chapter, which writes:

“Just like ordinary mathematics’ PEMDAS rule, C++ also follows a similar order of priority when calculating. This concept is a vital part of mastering number manipulation since it would greatly affect the results of calculations if this was not properly understood. Therefore, we must understand which operation need to be solved first, and in programming, we call this the order of precedence.”

The Order

Just like ordinary math, C++ also follows a similar order of precedence when performing the operations. To illustrate, we visualize the order as a staircase that needs to be taken step by step before being able to go to the bottom part, like this:

Keep in mind that as shown in the illustration, those in the same box are of the same ranking in the order of precedence, that is, when faced with those operations in one event, the computer will read it directly from left to right (unless enclosed by a parentheses).

Sample Problem 1

Guess the Answer

Let’s try the usual math tricks using the combination of arithmetic operations and have a try at how the order of precedence works!

The rule is to pick any integer from 1-9 and perform the following:

a) Multiply it by 2

b) Add six to the result

c) Divide the result by 2

d) Subtract the result by the original number you have chosen.

And magically, it will always result to the number 3!

However, it is important to follow the method step by step, especially since the third step involves division, which is of higher precedence than the second step, addition. In here comes the great use of parentheses, like this one below:

Code

Main.Cpp

#include<iostream>

int main(void) {

    // an example number value

    int num = 4; 

    std::cout << ((num * 2 + 6) / 2 – num);

    return 0;

}

Asking For Input

Topic 1

Learn to Listen

After days of programming your Cody, it has finally mastered human speech! (with your code, of course) However, as what a human quote says, there is something better than speaking, and that is…what the fifth chapter is about, which you opened and read aloud:

“Speaking is one great human ability, but in order to live a harmonious life together in the human world, it would be strange if every human would just talk and do nothing else, right? That is why, as social beings, there is also another important ability that lets them understand other human beings – listening. And luckily, we have just the thing that we need in C++: the std::cin function.”

The Syntax

The std::cin function works just like listening to another person in human sense, such that, it receives what the other person says.

Similarly, in C++, this function will allow the user to type in or input a specific data that is asked by the program. We shall also remember that since this is a standard input function, it will need the preprocessor directive, #include<iostream> for it to work.

By convention, we must create a variable that will store the value to be inputted using the std::cin function. After creating the variable that will serve as the container, we can now use the std::cin function by following this syntax:

std::cin >> variable_name;

The syntax presented above looks like a std::cout function except that the arrows are going the other direction. Recall that std::cout looks like this:

std::cout << variable_name;

The difference between the two, however, is that std::cin gets a value from the user and stores it to the variable while std::cout gets the value of the variable and prints/outputs it to the screen.

On most compilers that have terminals to run the code real-time, the std::cin function will only end once the user pushes the ENTER key in the keyboard and then proceed to the next lines of code. However, CodeChum’s coding environment works differently, since our compiler requires you to type in your custom inputs first in the input area before you run the code for it to work as you expect it to be.

To explain further on CodeChum’s input mechanism, here’s a simple guide example on how it works:

Code

Main.Cpp

#include<iostream>

int main(void) {

    // declare the variable to be used in the std::cin function first

    int num;

    // and then use it in std::cin to receive the inputted value

    std::cin >> num;

    // now let’s see if the value is really stored inside the variable

    std::cout << “The inputted number is: ” << num;

    return 0;

}

Try changing the value in the Custom Input above and run the code again. You should see that the output also changed based on the new value you placed on the Custom Input. Cool right?

If you want to experiment and explore on CodeChum’s way of taking inputs, you can write your own code that takes some inputs in our Playground!

Did you know?

You can also take multiple inputs in one line using the std::cin function! Well, it actually works just the same way, but with more than one variable like this:

std::cin >> variable_name1 >> variable_name2 >> variable_name3;

Taking multiple inputs in one line doesn’t have to be of the same data type. Just don’t forget to also type it with spaces too in the input area for the compiler to distinguish which is which. And oh, take note of the arrangement of inputs as well to avoid errors and miscalculations on your code!

Let’s try applying this with the code below:

Code

Main.Cpp

#include<iostream>

int main(void) {

    int num1, num2;

    char letter1;

    // let’s take in two integer inputs

    std::cin >> num1 >> num2;

    // and a char input

    std::cin >> letter1;

    // now let’s print all the values we just inputted

    std::cout << “Number1: ” << num1 << std::endl;

    std::cout << “Number2: ” << num2 << std::endl;

    std::cout << “Letter1: ” << letter1 << std::endl;

Sample Problem 1

Code Names

Have you ever heard of Manito Manita? On Christmas parties, human kids like to give presents to their classmates but to give some mystery and surprise, they like to randomly select who they give a present to!

To keep the real name as a secret when handing out presents, a code name is given to each person, which comprises of their favorite letter and the day they were born. And for this task, I want Cody to spearhead on this human-like celebration!

Now, in order for Cody to ask for something, we use the std::cin function! But we are going to take on two things: a letter (character), and a number (integer).

Now, let’s try it out!

Code

Main.Cpp

keyboard_arrow_leftkeyboard_arrow_right

#include<iostream>

int main(void) {

    char letter;

    int num;

    std::cin >> letter >> num;

    std::cout << “Your codename is: ” << letter << “-” << num;

    return 0;

}

Sample Problem 2

Quadratic Equation

In algebra, one of the basic things that a student has to know is to evaluate values, and this time, I want Cody to evaluate the value of y in a quadratic equation y = ax^2 + bx + c.

Now, in order to solve this problem, we have to take four inputs from the user – the values of a, b, c, and x, respectively, in one line only, and it has to be an integer.

I’ve already prepared a simple code for you. Take a look this:

Code

Main.Cpp

keyboard_arrow_leftkeyboard_arrow_right

#include<iostream>

#include<cmath>

int main(void) {

    int a, b, c, x;

    std::cin >> a >> b >> c >> x;

    int y = (a * pow(x, 2)) + (b * x) + c;

    std::cout << y;

    return 0;

}

Conditions

Topic 1

Making Decisions

Cody is now able to speak and listen to humans, which means that he is now quite geared up to blend in to human society! But Cody is not fully-equipped though, since there are still a lot of things that it needs to learn, like making its own decisions based on certain circumstances. But how would it be possible for a robot to decide on its own? Looking for answers, you opened the instruction manual again and began reading the sixth chapter which wrote:

“Robots have the capacity to follow what the programmer has told it to do, but never the ability to decide solely without the programmer’s guidance. However, there is one other way to make decision-making possible for robots to do, and that is by preparing a set of conditions on its program, given the situation that it is faced with. To be able to do that, we have to begin with exploring C++’s methods in making conditional statements.

Introduction

Before we head on to the different types of conditional statements available in C++, we have to learn on some operators to be used first.

There are actually different kinds of operators in C++. To recall, we have already encountered the assignment operator (=) and the arithmetic operators (+, -, *, /, %).

However, there are two other important operators which will be widely used in making conditions in your program, and those are called conditional operators and logical operators.

Conditional Operators

Conditional operators are used to evaluate certain conditions if they are true or false. In C++, the supported conditional operators are the following:

==

Returns true if value1 and value2 are equal. Note that this is different from the assignment operator

Syntax:

value1 == value2

Returns true if value1 is greater than value2

Syntax:

value1 > value2

>=

Returns true if value1 is greater than or equal to value2

Syntax:

value1 >= value2

Returns true if value1 is less than value2

Syntax:

value1 < value2

<=

Returns true if value1 is less than or equal to value2

Syntax:

value1 <= value2

!=

Returns true if value1 and value2 are not equal

Syntax:

value1 != value2

Logical Operators

On the other hand, logical operators are useful when we need to evaluate two or more conditions before a code is proven to be true or not. Here are the following:

!

Returns true if the condition is false

Syntax:

!condition

&&

Returns true only if both conditions are true

Syntax:

condition1 && condition2

||

Returns true if at least one of the conditions is true

Syntax:

condition1 || condition2

The if() Syntax

Now that you already know about the conditional and logical operators, let’s now proceed with the if() statement.

When you want to check some condition first before doing something, then the if() statement is right for the situation. if() statements are conditional statements that involve a condition to be met in order for the code inside it to be performed.

This type of conditional statement follows the following syntax:

if(condition) {

         // code here will be performed if the ‘condition’

         // is true. Otherwise, the code here will be ignored

}

Note that the line of code inside the curly braces of the if() statement will only be run if the condition put inside the parentheses is true; otherwise, it will just skip those lines of code. Moreover, we must also remember to put our conditions in parentheses or else, we will encounter an error in our code!

For now, as an example, see this program below that prints a statement if a condition passed is true (i.e. if age < 18 is true):

Code

Main.Cpp

#include<iostream>

int main(void) {

    int age;

    std::cin >> age;

    if(age < 18) {

        std::cout << “Sorry, no beer for you yet, bud.”;

    }   

    return 0;

}

Try running the code above and see that the message was indeed printed because our input was 17 and 17 is less than 18.

Now try changing the input to something that is not less than 18, like 24 for example, and run the code again. This time, you’ll see that the message isn’t printed anymore because the condition is now false.

Which leads us to the question, what if we wanted to do something else if the if() statement’s condition turns false, like an alternative? Watch out for another conditional statement in the next topic, and keep moving forward!

Did you know?

You can actually remove the curly braces of the if() statement and it will work the same way!

But there’s a catch to it though. The condition would only apply to the first line after the if() statement. If there are multiple lines of code that should be run only when the condition is true, then it is required to put those curly braces when you code, or else, the only statement that will be affected by the condition is the first line after it.

So it’s good programming practice to always put curly braces no matter how many lines in order to avoid logical errors!

But for now, to illustrate what I just explained, take a look at this code below:

Code

Main.Cpp

#include<iostream>

int main(void) {

    int a = 0, b = 2;

    if(a > b)

        std::cout << “YES”;

        std::cout << “GREATER”;

    return 0;

}

Try running the code above and observe the output. As you can see, the message “GREATER” has been printed even though a was not greater than b. Again, that is because the only statement (or line of code) affected by the if() statement is the first print code, which is the std::cout << “YES”;

Sample Problem 1

Only When It’s Even

You set Cody’s favorite number to be an even number. Then, in its class in math, they were tasked to find a classmate with the same type of favorite number and pair up with him/her for an activity. When it finds that one, it has to shout in uppercase letters, the words “I found you!”. It’s now time to test your knowledge on the past lessons we’ve covered in here.

For this task, we have to take the other person’s favorite number and then evaluate if it is even. Only then will it be saying the phrase. This calls in for the combination of if() statements and the arithmetic and conditional operations!

I’ve prepared the code for you. Run it and see the magic happen!

Code

Main.Cpp

#include<iostream>

int main(void) {

    int faveNum;

    std::cin >> faveNum;

    // this condition checks if ‘faveNum’ is an even number.

    if(faveNum % 2 == 0) {

        std::cout << “I found you!.”;

    }

    return 0;

}

Try running the code above. It should print the message as expected because the number 4 is an even number. Try changing it to an odd number like 5 or 7 and run it again. Obviously it won’t print the message anymore because the condition becomes false.

Note: Doing % 2 on an integer will result to 0 if the number is even. To understand why, recall that the % operator returns the remainder of the division, not the quotient. And dividing any even number by 2 will always result to a remainder of 0.

On the other hand, dividing any odd number by 2 will always result to a remainder of 1. Therefore, to check if a number is odd, you can just do num % 2 == 1 or num % 2 != 0.

Topic 2

Torn Between the Two

You have now “taught” Cody on how to make a decision when faced with one true condition! But how can he respond quickly on a situation where the condition is not true? To find out how, you flipped the next page of the sixth chapter of the instruction manual, which says:

“Deciding on one thing is easy, especially when you are only needed to respond when the condition given is true, but there are times when you need to act on something when the condition turns to be false as well, because when you are asked by a yes/no question, you can’t just stare blankly into space when your answer is no, right? Therefore, to make Cody act that way like humans do, we also have to teach him how to respond on false conditions with the use of C++’s if statement counterpart: the else statement.”

The If Else syntax

We already know that when we want to run some lines of code only when the condition is true, we use a single if() statement. However, when we also have to run some other code if the if() statement’s condition is false, we have to add some else statement.

else statements function just like the if() statement, but it doesn’t need its own condition because it will only run the codes inside it when the condition of the if() statement is false.

To elaborate, it follows this syntax where there will always be an if() statement before it:

if(condition) {

         // code to be executed if condition is true

} else {

         // code to be executed if condition is false

}

Thus, since it is dependent to the if() statement’s condition, the else statement can only function when preceded by an if() statement and cannot set a condition of its own.

So for example, when answering a yes/no question, you are now able to do so, like this one, when testing if the number is positive or not:

Code

Main.Cpp

#include<iostream>

int main(void) {

    int num;

    std::cin >> num;

    if(num > 0) {

        std::cout << “Positive”;

    } else {

        std::cout << “Negative”;

    }

    return 0;

}

Note that an else statement will only be used when you need to run some lines of code when a condition is false. If not needed, then do not write it in your code for good programming practice.

But what if we have three options to consider?

Like for example, in the above problem, what if the value to be inputted is zero? It’s neither positive nor negative in nature.

We shall know what can be done to solve this loophole in your code in the next topic ahead, so keep learning!

Sample Problem 1

Odd or Even

The last time, Cody was tasked to find a partner with an even number as its favorite number. Now, since their math teacher is fond of odd and even numbers, he gave them homework on it as well! This time, Cody has to write if the number is even or odd based on the given number.

Let’s make use of what we’ve recently learned on the two conditional statements!

I’ve laid out the code for you already. Try it out and see!

Code

Main.Cpp

#include<iostream>

int main(void) {

    int num;

    std::cin >> num;

    if(num % 2 == 0) {

        std::cout << “Even”;

    } else {

        std::cout << “Odd”;

    }

    return 0;

}

Topic 3

If Not That, Then What?

Cody’s getting better at making decisions, eh? But there is still more than what you have already learned when making decisions, and that is, when you encounter multiple options at the same time. Looking for answers, you found yourself looking at the third chapter of the book:

“Your robot’s now able to answer things when faced with a condition that can be either true or false, but what can it do when it is faced with more than one condition and only one has to be met? This calls for the help of one other conditional statement that offers the option of having another condition if the if() statement’s condition is false – C++’s else if() statement.”

The Else If syntax

else if() statements are conditional statements that are used to put another condition if the if() statement’s condition is not met.

It quite functions like an if() statement as it can also have a condition of its own, but it is also like an else statement that needs an if() statement before it. Therefore, else if() statements cannot exist without a preceding if() statement.

It follows the following syntax:

if(condition1) {

         // code to be executed if condition1 is true

} else if(condition2) {

         // code to be executed if condition2 is true

} else {

         // code to be executed if condition1 and condition2 are false

}

However, else if() statements can function well without anelse statement after it, and can even be used multiple times when we need to have multiple conditions, like this syntax:

if(condition1) {

} else if(condition2) {

} else if(condition3) {

} else if(condition4) {

} else if(conditionN) {

}

else if() statements are best used when faced with a problem that needs to be evaluated over several conditions, such as evaluating if an integer is positive, negative, or zero. In this problem, an if-else statement would not be enough as there is another case to be handled, which is zero because it is neither negative nor positive. Hence, we have to utilize the use of else if() statements for it, like this:

Code

Main.Cpp

#include<iostream>

int main(void) {

    int num;

    std::cin >> num;

    if(num > 0) {

        std::cout << “Positive”;

    } else if(num < 0) {

        std::cout << “Negative”;

    } else {

        std::cout << “Zero”;

    }

    return 0;

}

Remember that the condition inside an else if() statement will only be evaluated if the previous condition from an if() or a preceding else if() (if such exists) statement is false. By understanding this concept, we can now avoid repeating conditions that were already eliminated by the previous conditions given.

For example, take a look at this code below:

#include<iostream>
 
int main(void) {
         int num;
         
         std::cin >> num;
 
         if(num >= 10) {
                 std::cout << "Greater than 10";
         } else if(num < 10 && num > 5) {
                 std::cout << "Greater than 5 but lesser than 10";
         } else {
                 std::cout << "Lesser than 5";
         }
 
         return 0;
}

As you can see, the condition in the else if() is not the best one because it is redundant. Again, the else if() is only checked if the previous if() or else if() is false. In the code above, the condition in the first if() is num >= 10. If that is false, therefore even without checking, we already know that num is definitely < 10 (anything that is not >= 10 is < 10 right?)

A better code therefore would look like this:

#include<iostream>
 
int main(void) {
         int num;
         
         std::cin >> num;
 
         if(num >= 10) {
                 std::cout << "Greater than 10";
         } else if(num > 5) { // take a look at this updated condition
                 std::cout << "Greater than 5 but lesser than 10";
         } else {
                 std::cout << "Lesser than 5";
         }
 
         return 0;
}

By understanding that concept, we would now be able to make better conditions through these conditional statements.

Sample Problem 1

The Largest One

Today, we need to find out the largest number among all three numbers that are to be given by the user. To do that, we have to use a lot of conditions, which calls for the help of else if() statements! We also need to make use of the logical operators we’ve learned in the previous lessons.

I’ve laid out a simple code for you already. Try it out and see!

Code

Main.Cpp

#include<iostream>

int main(void) {

    int a, b, c;

    std::cin >> a >> b >> c;

    if(a >= b && a >= c) {

        std::cout << “Largest: ” << a;

    } else if(b >= a && b >= c) {

        std::cout << “Largest: ” << b;

    } else {

        std::cout << “Largest: ” << c;

    }

    return 0;

}

There is also another way to solve this problem by using single if() statements only (without any else if()‘s)! Just assume that one of them is the largest value and then compare them one by one. Check this improved version below:

Code

Main.Cpp

#include<iostream>

int main(void) {

    int a, b, c;

    std::cin >> a >> b >> c;

    // we assume that one of them is the largest

    // In this case, we assumed that a is the largest

    int largest = a;

    // then we check the other numbers if they are greater

    // than the existing largest, one by one. We start,

    // by checking b against the existing largest

    if(b > largest) {

        largest = b;

    }

The second code is better because if the problem is updated to comparing 4 or 5 or even 6 numbers, it’s very to update; we just add more if() statements! Compared to the previous version, we need to add a lot of else if() and we need to compare each number to every other number, one by one. Imagine the inefficiency!

Topic 4

Finding the One

Cody’s almost at the peak of mastering making decisions (with the help of your code, of course)! But there is still something more than meets the eye. Remembering that there is still one other type of conditional statement in C++, you began reading the last page of the current chapter:

“Your robot’s now able to answer things when faced with different types of conditions, right? But what could the best solution be if you are going to test a single value and run a code if the value is equivalent to the condition? Surely, having lots of if(), else if(), and else statements would do the trick, but it’s just too lengthy, don’t you think? That is why C++ offers one other conditional statement alternative that allows you to do so: using the switch() statement.”

The Switch() Syntax

Just like any other conditional statements, the switch() statement tests a single value on a number of conditions. However, the conditions that a switch statement can only deal with are those pertaining to equality of a set of values.

To put it simply, it allows us to test one value among many alternative values. Each of the alternative values that are to be compared with the value put under the condition of the switch() statement which we refer to as a case.

To elaborate, it follows the following syntax:

switch(n) {

         case value1:

                 // code here will be executed if n is equal to value1

                 break;

         case value2:

                 // code here will be executed if n is equal to value2

                 break;

         case value3:

                 // code here will be executed if n is equal to value3

                 break;

         default:

                 // code here will be executed if n is not equal to

                 // value1, value2, and value3

}

The switch() statement works by comparing the value to the alternative values of each case. If the alternative value equals to the value that is tested by the switch case, it will then proceed to executing the code after the case’s colon.

If no alternative value equals to the value, it will then execute the default case given at the end of the statements. It is good to know, however, that a default case is not required to be put in a switch() statement since it will work just fine even without it.

It is also important to put a break keyword after each case to ensure that when the condition is met for one case, it would not execute on the proceeding cases anymore.

The break keyword functions as a stopper to the switch code, so whenever the compiler encounters this inside the switch statement, it will stop the processes happening inside the switch statement and exit it, then proceed to the remaining lines of code after the switch() statement.

Did you know?

When you don’t put the break keyword after every case in a switch() statement, any other statements put in other cases after the case constant that makes the condition true will also be executed (even though the value checked does not match the other cases)!

Here’s what will clearly happen when you do forget your break;

Code

Main.Cpp

#include<iostream>

int main(void) {

    int num = 2;

    switch(num) {

        case 1:

            std::cout << “1”;

        case 2:

            std::cout << “2”;

        case 3:

            std::cout << “3”;

        case 4:

            std::cout << “4”;

    }

    return 0;

Take a look at this another example. We want to know the evaluation of a student based on its grade in letters, we can make a solution in a more efficient way using the switch statement, like this:

Code

Main.Cpp

#include<iostream>

int main(void) {

    char grade;

    std::cin >> grade;

    switch(grade) {

        case ‘A’:

            std::cout << “Excellent”;

            break;

        case ‘B’:

            std::cout << “Good”;

            break;

        case ‘C’:

            std::cout << “Satisfactory”;

            break;

It is also important to remember that a switch statement can only evaluate a value that can either be a character or an integer. Other than that, it cannot work on other data types.

Did you know?

You can actually put more than one statement inside a case constant in a switch() statement! Just try to practice good indention to neatly see where each statement belongs to, and don’t forget the break keyword, too! The syntax looks like this:

switch(num) {

         case 1:

                 // line of code

                 // line of code

                 break;

         case 2:

                 // line of code

                 // line of code

                 // line of code

                 break;

}

Loops

Topic 1

Until It Doesn’t Fit

At this point, Cody is now able to freely “decide on its own” with your application on conditional statements! Now we shall move on to making repetitive movements and decisions. In search for the next mission, you turned to the second-last chapter of the manual, which read:

“Don’t you wonder how it would be able to repeat something more quickly and efficiently? Up until now, the only way you can program your robot to do so is by duplicating statements manually. It works just fine, but just not when it has to be repeated a hundred times. To easily repeat statements requires our program to use a function in C++ that can perform repetitions at a given condition – a function we refer to as loops. There are a lot of types of looping structures, but for now we shall tackle the first one that deals with repeating steps until a condition is met, a kind of loop mostly known as a pre-checked loop – the while() loop.”

While Loop Syntax

Loops are like car wheels – they continue to turn around unless the driver steps on the brake whenever it arrives at the destination, pauses for a stoplight, or when a dog unexpectedly walks in front of the car. In the same light, loops in C++ work the same way like the car wheels, in which certain steps are done repeatedly until a certain condition is no longer met, or until a given sequence of numbers is finished.

There are three types of loops that are available in C++: the while() loop, the do-while() loop, and the for() loop. Each loop in C++ works differently in some ways and are used for different purposes as well. To start off, we shall talk about the first type: the while() loop.

while() loop is used to execute lines of code inside it repeatedly until the condition it contains becomes false. Also known as a pre-checked loop, it functions in a way that it has to test if the condition is true before executing the lines of code inside it.

This is commonly used when the value you put in the condition statement is manipulated inside the loop until it reaches a value that falsifies the condition.

By convention, it follows the following syntax:

while(condition) {

         // code here will be repeatedly executed

         // until the ‘condition’ is false

}

Basically, a while() loop’s structure looks and functions exactly like an if() statement, only that, it is executed repeatedly until the condition becomes false.

To clearly see how a while() loop works, let us use it to print the string, “Hello World” 10 times:

Code

Main.Cpp

#include<iostream>

int main(void) {

    int times = 0;

    while(times < 10) {

        std::cout << “Hello World” << std::endl;

        times++;

    }

    return 0;

}

In the code above, we created a times variable which will keep track of how many times we have already printed the message. By default, it is initialized to 0 because we haven’t started printing the message yet.

Then, the condition inside the while is checked: is times < 10 true? Since it is (because 0 is less than 10), the execution went inside the while loop and "Hello World" is printed once.

Finally, we incremented the times variable by 1 because if we don’t, then the value of times will always be 0 and the condition will always be true. This will result to an infinite loop or a forever loop. Try removing the times++ in the code above and run the code to see what happens.

Sample Problem 1

While True, I Love You

Cody is a robot, but who’s to say the robot’s are not capable of love?

Just as we all love Cody, Cody actually also loves us! But since he’s still a robot, we need to supply him with an integer so that he will be able to love us.

Take a look at this code below:

Code

Main.Cpp

#include<iostream>

int main(void) {

    int n;

    std::cin >> n;

    while(n > 0) {

        std::cout << n << “.) I love you!” << std::endl;

        n–;

    }

    return 0;

}

Topic 2

Until You Say So

Cody has successfully acquired his first looping skill using while() loops! It really comes in handy when you want to manipulate a number repeatedly inside a loop or perform it for a given sequence with the help of incrementors. However, thinking about it, how can we loop something for an unknown number of times and stop when the user inputs something that will falsify its condition? Looking for answers, you find yourself reading the 2nd topic of the current chapter which states:

“If there are while() loops that check the condition of a loop before it executes the line of code inside it, also known as a pre-checked loop, then there are also post-checked loops in C++, and these are what we will be discussing in this chapter: the do…while() loops.

The Do While Syntax

do…while() loop serve the same purpose as the while() loop, as it will run the code repeatedly until the condition becomes false, only that, since this one is a “post-checked loop” (meaning it executes the code first and then, checks the condition), it guarantees that the code shall be executed at least once.

By convention, it follows the following syntax:

do {

         // code here will be executed first before the condition

         // is checked. And then once the condition is checked and

         // it is still true, the code here will be executed again

} while(condition);

One useful example of this loop is when we wish to ask for some random value from the user and loop that action until the user inputs a value that falsifies the condition, like this:

Code

Main.Cpp

#include<iostream>

int main(void) {

    int num;

    do {

        std::cin >> num;

        std::cout << “Inputted number: ” << num << std::endl;

    } while(num > 0);

    return 0;

}

Sample Problem 1

Sum of Odds

Cody’s teacher will be giving them a math activity tomorrow on addition! The twist to it, though, since their teacher is so fond of odd and even distinction, is that the only numbers that you need to add together from anything he gives are those that are odd! You stop adding, though, when he gives you 0 as given.

Now, since it doesn’t have any fixed number of times to loop a thing and we cannot have an initial value first before asking for the code, it won’t work quite well with while() loops.

So, since we need to at least ask for the input before testing if it isn’t zero yet, it means that we have to make use of the do…while() loop!

I’ve prepared the code for you. Run it and see the magic happen!

Code

Main.Cpp

#include<iostream>

int main(void) {

    int num;

    // this will hold the sum of all the odd numbers.

    // Since we haven’t added anything yet, initially,

    // the value is 0

    int sum = 0;

    do {

        std::cin >> num;

        // we check if the num inputted is odd. 

        // If it is, we add it to the sum

        if(num % 2 == 1) {

            sum += num;

Topic 3

Counting

Your Cody already knows how to repeat things until the condition becomes false, but how about repeating things until a given sequence is finished? Sure, a while() loop can do that, but is there really no other type of loop that simplifies that action? Eager to figure out the answer to your queries, you turned to the third chapter of the current lesson which states:

“You now know that while() and do…while() loops are used when you want to repeat something up until the condition becomes false, but when you want to loop through a sequence of numbers in either ascending or ascending order, we need some other loop to do the trick. This calls for the help of C++’s one last type of loop structure – the for() loops.”

For Loop Syntax

for() loop works the same as when using a while() loop to loop through a definite number of times while incrementing inside it, but this type of loop makes that code simpler, with all of its conditions put in just one statement.

Just like the while() loop, a for() loop requires you to use a counter variable, which is incremented/decremented for each loop iteration. Hence, we shall first declare a counter variable, and since its purpose is to count, it has to be an integer at all times. Something like this:

int ctr;

The counter variable can be set to any name, but most counter variables use at least a letter to represent it, like i, a, c, or a shorter term for counter, ctr, just like the one above.

It then follows a syntax like this one:

for(initialization; condition; increment/decrement) {

         // code to be executed repeatedly, while the

         // ‘condition’ is still true

}

The first statement inside the for() loop’s parentheses is used to initialize the counter variable by assigning it to a number that will serve as the starting point of the loop. Upon entering the loop, this initialization will only happen once in the entire execution. It looks something like this:

int ctr;

for(ctr = 1; condition; increment/decrement) {

         // code to be executed repeatedly, while the

         // ‘condition’ is still true

}

In C++, the code above can actually be simplified into something like this:

for(int ctr = 1; condition; increment/decrement) {

         // code to be executed repeatedly, while the

         // ‘condition’ is still true

}

But be careful though, in the updated code above, the ctr only exists inside the loop. For example, if you print the value of ctr after the loop, you’ll get an error:

for(int ctr = 1; condition; increment/decrement) {

         // code to be executed repeatedly, while the

         // ‘condition’ is still true

}

// ERROR!

std::cout << ctr;

The second statement will serve as the stopper of the loop, as it gives out the condition that has to stay true for the loop to work, until it becomes false. It’s basically almost the same as the while loop.

Usually, the value that it has to test per loop iteration is the counter variable that we used for the loop and it is usually compared by a number that will serve as the ending point of the loop.

Moreover, since it is indeed a condition, just like conditional statements, it makes use of conditional operators (see Lesson 6) for the condition to work, like this one:

int ctr;

for(ctr = 1; ctr <= 5; increment/decrement) {

         // code to be executed repeatedly, while the

         // ‘condition’ is still true

}

The loop above will continue executing while ctr is less than or equal to 5. And that is where the increment/decrement section is needed.

The last part of the statement inside the parentheses of a for() loop is the most important part of the loop for it to avoid looping forever. In this statement, all we have to do is to increase or decrease the value of the counter variable for it to get closer to the value set in the condition, and finally terminate the loop.

Usually, it utilizes the increment/decrement operators that was discussed in the previous chapter. For example, if we want to increase the counter, ctr variable, value by 1, we can use this kind of syntax:

int ctr;

for(ctr = 1; ctr <= 5; ctr++) {

         // code to be executed repeatedly, while the

         // ‘condition’ is still true

}

Always remember that all of the statements inside the for() loop’s parentheses, except the increment/decrement, end with a semicolon. If another symbol is to be put by mistake in place of the semicolon, it will instead generate an error, so always keep that in mind, okay?

So, this works well when you want your program to count off from a certain number to another, and it is commonly used when we want to loop a set of instructions for a fixed number of times.

Now that we have understood how it works, let us see how a for() loop makes the code more efficient than we thought it could be!

For example, when you wish to print all even numbers from 10 to 20, you can achieve the result by typing in the std::cout function repeatedly and you have to memorize the even numbers, too:

std::cout << 10 << std::endl;

std::cout << 12 << std::endl;

std::cout << 14 << std::endl;

std::cout << 16 << std::endl;

std::cout << 18 << std::endl;

std::cout << 20 << std::endl;

But with a for() loop, what used to be 5 lines of std::cout statements, can now be reduced to just one, like this!

for(int ctr = 10; ctr <= 20; ctr++) {

         // we only print the even numbers

         if(ctr % 2 == 0) {

                 std::cout << ctr << std::endl;

         }

}

Now the code above can still be improved. Remember that even numbers are separated by 2. That means instead of increasing the ctr by one with the ctr++, we can just increase it by 2 instead like this:

for(int ctr = 10; ctr <= 20; ctr += 2) {

         // now, we don’t have to check if the current value

         // of ctr is even because it is already guaranteed

         // that it is even because it is being increased by 2’s

         std::cout << ctr << std::endl;

}

Efficient, ain’t it?

Did you know?

You can also perform a loop inside a loop too! These are what we call as nested loops, where the inner loop(s) acts as an “egg” that is enclosed by the outer loop that acts as a “nest” to the inner loop(s).

In C++, it is usually treated like a table, where the outer loop is usually referred to as the row, and the inner loop, the column.

It follows the following syntax:

for(initialization; condition; increment/decrement) {

         for(initialization; condition; increment/decrement) {

         }

}

This works just like a normal loop, but the difference is that the inner loop must be executed first before re-looping the outer loop. Therefore, the outer loop can only repeat the lines of code inside it when the inner loop is done executing its own.

For example, let us try making a 6×6 rectangle using asterisks!

Code

Main.Cpp

#include<iostream>

int main(void) {

    for(int row = 1; row <= 6; row++) {

        for(int col = 1; col <= 6; col++) {

            std::cout << “*”;

        }

        std::cout << “\n”;

    }   

    return 0;

}

This technique is incredibly useful when making two-dimensional patterns using C++.

So far, we’ve only tried looping in an ascending order, with the help of the increment operators. Let’s now try creating something in descending order.

When we want too loop in descending order, the counter variable must be initialized to a value greater than the value in the condition statement, and it usually uses either the greater than (>) or the greater-than-or-equal-to (>=) conditional operators.

Moreover, it usually uses the decrement operators involving subtraction (-) and division (/) to decrease the value of the initialized counter variable for every iteration.

Hence, if we would like to print from 10 to 1 instead, we can do this:

Code

Main.Cpp

#include<iostream>

int main(void) {

    for(int ctr = 10; ctr >= 1; ctr–) {

        std::cout << ctr << std::endl;

    }   

    return 0;

}

Understanding this concept will help you get more familiar with using for() loops in your code, so feel free to practice executing for() loops for better learning through experience, okay?

Sample Problem 1

Multiples of 5

Cody’s teacher handed out an assignment about identifying the multiples of 5 from 0 to 50. Now, I need you to make Cody’s math struggles a little easier to handle with your new knowledge on loops.

To do that, we have to have loops, with conditions inside it! When Cody finds out that a number is a multiple of 5, he prints it.

Let’s try this now!

Code

Main.Cpp

#include<iostream>

int main(void) {

    for(int ctr = 0; ctr <= 50; ctr++) {

        // we only print the values that are divisible by 5

        if(ctr % 5 == 0) {

            std::cout << ctr << std::endl;

        }

    }

    return 0;

}

To improve the code above, you could actually just have an increment of 5 for every iteration and directly print, like this:

Code

Main.Cpp

#include<iostream>

int main(void) {

    for(int ctr = 0; ctr <= 50; ctr += 5) {

        std::cout << ctr << std::endl;

    }

    return 0;

}

To improve the code above, you could actually just have an increment of 5 for every iteration and directly print, like this:

Code

Main.Cpp

#include<iostream>

int main(void) {

    for(int ctr = 0; ctr <= 50; ctr += 5) {

        std::cout << ctr << std::endl;

    }

    return 0;

}

Using this method instead of looping through the entire string will increase efficiency of code and lessen the amount of time it takes the code to process everything, but remember to use it only when you need it, okay?

How To Continue

A break statement is used to immediately stop a loop. But what if we just want to ignore or skip a value when a certain condition is met and then go on with the loop until it ends (i.e. until the condition is actually false)? This is where we use the keyword continue.

This helps when we want to skip or leave out a certain value from becoming part of an execution or when we want to skip out on all other parts of code below this keyword before looping again.

For example, when we don’t want to print out multiples of 3 in our code, we can use continue to ignore multiples of 3 and then loop again, like this:

Code

Main.Cpp

#include<iostream>

int main(void) {

    for(int ctr = 1; ctr <= 20; ctr++) {

        // if the value of ctr is divisible by 3,

        // we immediately go to the increment part

        // of the loop

        if(ctr % 3 == 0) {

            continue;

        }

        std::cout << ctr << std::endl;

    }   

    return 0;

}

Remember that when the continue statement is encountered, it only skips an execution of a loop but it does not fully terminate the entire loop unlike the break statement. Instead, it proceeds immediately to the increment/decrement part of the loop.

Sample Problem 1

Don’t “Even” Want To See You

Cody’s teacher is in a bad mood today with even numbers since it reminds him of his ex-partner’s special dates as a couple. To make it worse, he gave out an assignment to isolate all even numbers from 1 to 20.

Now, we have to teach Cody how to complete this assignment with the use of our newly-discovered control statement that allows skipping – continue!

Now, try to run the code and see the action happen real-time!

Code

Main.Cpp

#include<iostream>

int main(void) {

    for(int ctr = 1; ctr <= 20; ctr++) {

        // we skip the even values

        if(ctr % 2 == 0) {

            continue;

        }

        std::cout << ctr << std::endl;

    }

    return 0;

}

Arrays

Topic 1

How to Make an Array

Cody has learned a lot of things that humans usually do – from speaking, to listening, to mastering strings and numbers, deciding for itself, and even on repeating things efficiently. But to complete the package of skills that will allow him to become perfectly ready to blend into human society, he has to learn one last basic concept. You then opened the instruction manual to its final chapter and read:

“You are finally close to preparing Cody for the human world and also close to being a real C++ programmer! Now, we shall talk of one of the most important concepts in C++ that will be instrumental in making efficient programs and in optimizing Cody to function better as a human-like kid. When humans want to jot down things and store them for reuse in the future, they often write it down as a list of items. Similarly, in order to store strings or numbers as a group in order, we have to get hold of C++’s flexible multi-container of values: arrays.”

What’s an Array?

As far as we have known, when we want to store multiple values of the same data type in a program, we can just have some remedy by making multiple variables to store each of them. However, it would be unimaginable to do so if we have to store a hundred of values in one sitting, right? What’s more, it would also cause a big headache when maintaining the code when we have to change something from each of the values. This is where arrays enter the scene to solve this type of problem.

An array is basically an ordered collection of values having the same data type. It functions like a big container, which has sub-containers that store each value that is put inside it, and has a fixed size once declared in the program. Since it is an “ordered” collection of values, each value has its own “index positions” inside the array where it belongs to, with the position number starting from 0 until one less than the array size (array_size – 1), in ascending order.

Therefore, we can think of arrays as something like this one:

Making an Array

In C++, arrays are created by declaring it just like a normal variable, but with an addition of the array size beside the variable name. To illustrate, the most common way to make an array is by doing this:

data_type arrayName[size];

The data_type above is just the same data_type as of a normal variable (e.g. it can be int, double, bool, etc.). Similarly, the arrayName is also the same as of a normal variable. The only difference is the size part which basically indicates how many elements/items/values the array can hold. For example, the array in the code below has a size 5 so it can hold 5 elements.

#include<iostream>

int main(void) {

         // we just declared an array here of size 5

         int myArray[5]; 

         return 0;

}

Now, the array we declared above has no initial values (i.e. it has a size of 5 but initially, it is empty because there are no values inside it). You can also make an array and assign it with its initial values as well! Just put the values inside a pair of braces ({}) and separate it with commas (,), like this:

#include<iostream>

int main(void) {

         // we just declared an array here of size 5

         // but this time, with initial values

         int myArray[5] = {20, 24, 31, 22, 28};     

         return 0;

}

Note that the size of the array put inside the square brackets must always be a positive integer and the number of values to be put inside an array must not go beyond its size for good programming practice.

Data Types of an Array

Unlike other programming languages that allow data type flexibility on its arrays, C++ is data type-specific, meaning, all values that are put inside an array must be of the same data type as the array itself.

A C++ array can be an ordered group of numbers, with its data type either in int, float, or double. When initializing these values in an array, we can just simply write it as the normal array initialization, like these examples below:

int numArr[10] = {-1, 2, -3, 4, -5, 6, -7, 8, -9, 0};

float numArr2[5] = {3.14, 9,8, 10.5, 0.4, -23.23};

On the other hand, arrays could also be an ordered group of characters, commonly known as a string, with data type char. Arrays of this data type can also be initialized using the same method as with numbers, only that each characters must be enclosed with single quotes, like this:

char charArr[10] = {‘C’, ‘o’, ‘d’, ‘y’, ‘\0’};

But take a look at that last character above, what is that?

Strings

The ‘\0’ you saw above is a null terminating character. But before we talk about it, let’s talk about strings first.

string is simply a sequence of characters. To create a string, we need to have multiple char’s or in other words, a char array.

Strings however are special because they need to have a null terminating character at the end. Basically, the null terminating character is a special type of character which represents the end of the string. Every time we create a string using the first method of creating a string (that is, using a char array), we need to add a null terminating character at the end. Always remember that!

Oh I said “first method” because there’s a second method (and even a third!). The second method is still by using a char array but instead of manually adding all the characters, you just simply place the whole string content instead inside double quotes, like this:

char name[10] = “Cody”;

With that method above, you don’t need to add a null terminating character at the end because it’ll be automatically added for you. Also, just to reiterate, with the second method, you need to use double quotes, not single quotes because single quotes are for characters, not strings.

Now there’s a third method in C++ which involves another library, the string library.

The string Library

The string library contains functions that are related to strings (obviously!). To create a string using the string library, you need to include the library first before you can create one. Here’s how it looks like:

#include<string>

int main(void) {

         std::string name1 = “Cody”;

         std::string name2 = “Jude”;

         return 0;

}

As you can see, it’s almost the same with the second method of creating a string (the one where we used the char array and used double quotes). So why do we nee to go through the hassle?

The reason is because there are a lot of other helper functions inside the string library that we can make use of to process the strings. Here are some of them:

int length()

Returns the length of a string. Example:

Code

Main.Cpp

#include<iostream>

#include<string>

int main(void) {

    std::string sentence = “CodeChum is awesome!”;

    int length = sentence.length();

    std::cout << length;

    return 0;

}

bool empty()

Checks whether the string is empty or not. Example:

Code

Main.Cpp

#include<iostream>

#include<string>

int main(void) {

    std::string sentence = “”;

    if(sentence.empty() == true) {

        std::cout << “The sentence is EMPTY”;

    } else {

        std::cout << “The sentence is NOT EMPTY”;

    }

    return 0;

}

int compare(string str2)

Compare two string objects. If the caller of the compare function is “less than” the passed second string str2, it will return -1. If it is “greater than” the passed second string str2, it will return 1. If they’re equal, it’ll return 0. This is a very helpful function in sorting strings or to check if strings are equal or not. Example:

Code

Main.Cpp

#include<iostream>

#include<string>

int main(void) {

    std::string word1 = “coding”;

    std::string word2 = “programming”;

    if(word1.compare(word2) == -1) {

        std::cout << “word1 is lesser than word2”;

    } else if(word1.compare(word2) == 1) {

        std::cout << “word1 is greater than word2”;

    } else if(word1.compare(word2) == 0) {

        std::cout << “word1 is equal to word2”;

    }

    return 0;

}

Try playing around the compare function in the sample code above by changing the values of word1 and word2.

To end this section, we will talk about how to take user string inputs. So far, in all of the three methods above, what we’ve done is initialize them immediately after declaring them. But what if we take some string input/s, say for example, taking in the name of the user? We do it like this:

Code

Main.Cpp

#include<iostream>

int main(void) {

    std::string name;

    std::cin >> name;

    std::cout << “Name: ” << name;

    return 0;

}

Now, the code above works but it only works if the name or string input is one word. If the input consists of multiple words, it’ll only take in the first word. To solve that issue, we use the getline function from the string library, just like this:

Code

Main.Cpp

#include<iostream>

#include<string>

int main(void) {

    std::string name;

    // this will take in all the words of the input

    std::getline(std::cin, name);

    std::cout << “Name: ” << name;

    return 0;

}

Topic 2

An Array Element

Cody now knows how to make an array of things, just like a normal human! But did you know that you can actually access, change, or manipulate any item from an array of any data type? To know how to do it, you read the second topic of the last chapter of the manual which states:

“Arrays are so efficient that we can put similar things together if we need to, like a list of numbers or letters! But when we want to change something or know about the contents inside an array, there is one method in C++ where we can do just what we need: through accessing array indices.”

Accessing an Element

arrName[index_position];

We must always remember though, that an array index always start off with 0 and ends with its size – 1. Therefore, in an array of 5 integers, we can only access from 0 – 4, and if we access more than that, although we won’t get an error in C++, we can get some random value instead.

Here’s an example code where we access the elements of the array one by one:

Code

Main.Cpp

#include<iostream>

int main(void) {

    int arr[5] = {20, 24, 28, 31, 8};

    std::cout << “Element at index 0: ” << arr[0] << std::endl;

    std::cout << “Element at index 1: ” << arr[1] << std::endl;

    std::cout << “Element at index 2: ” << arr[2] << std::endl;

    std::cout << “Element at index 3: ” << arr[3] << std::endl;

    std::cout << “Element at index 4: ” << arr[4] << std::endl;

    return 0;

}

Try editing the code above by printing what’s on index 5 or index 6 or index 99 and see the random value.

How about a string, how do we access its contents? Well, it’s basically just the same, through the use of indices. Take a look at this one below:

Code

Main.Cpp

#include<iostream>

#include<string>

int main(void) {

    std::string word = “Cody”;

    std::cout << “Character at index 0: ” << word[0] << std::endl;

    std::cout << “Character at index 1: ” << word[1] << std::endl;

    std::cout << “Character at index 2: ” << word[2] << std::endl;

    std::cout << “Character at index 3: ” << word[3] << std::endl;

    return 0;

}

Setting an Element

If we can access an element and print it out, we can also set a value for a certain index in the array and it’s nothing hard really. Take a look at this example below where we are manually setting the values of the array:

Code

Main.Cpp

#include<iostream>

int main(void) {

    int arr[5];

    arr[0] = 10;

    arr[1] = 20;

    arr[2] = 30;    

    arr[3] = 40;

    arr[4] = 50;

    std::cout << “Element at index 0: ” << arr[0] << std::endl;

    std::cout << “Element at index 1: ” << arr[1] << std::endl;

    std::cout << “Element at index 2: ” << arr[2] << std::endl;

    std::cout << “Element at index 3: ” << arr[3] << std::endl;

    std::cout << “Element at index 4: ” << arr[4] << std::endl;

We could even create an array with initial values and then change only one or a few elements in the array, like this:

Code

Main.Cpp

#include<iostream>

int main(void) {

    double arr[5] = {1.5, 3.2, 4.1, -5.5, 0};

    // update the element at index 2

    arr[2] = 9999;

    std::cout << “Element at index 2: ” << arr[2] << std::endl;

    return 0;

}

Topic 3

Traversing the Array

You already know how to make and manipulate arrays now, and you might think that your C++ journey has come to an end, but there is actually still one more thing you need to learn to program Cody more efficiently when it comes to storing and changing arrays repetitively. Excited to read the final topic of the final chapter, you took the instruction manual and from there, it writes:

“You are now one step away from the goal which you started when you first read this manual, are you? Now, let me teach you the art of combining arrays and repetitive actions with the use of loops. This will be a very important concept especially when adding or manipulating values inside the array. Hence, let me introduce you to one final concept of array manipulation in C++ in repetition – the combination of loops and arrays.”

Add Items to Array

We now know that we can add items to an array by either initializing it all together in one single line, but how can we add values in the array based on the inputted values from the user, one at a time?

This is where loops play an important role in making your task possible. For example, when we want to add values one by one, we can incorporate the concept of accessing index positions and continuous std::cin in a loop, like this:

Code

Main.Cpp

#include<iostream>

int main(void) {

    int arr[5];

    // 1. SCANNING

    // we start looping at i = 0 since array index starts at 0

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

        std::cin >> arr[i];

    }

    // 2. PRINTING

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

        std::cout << “arr[” << i << “]: ” << arr[i] << std::endl;

    }

Array Manipulation via Loops

There are times when you want to change each of the values inside an array and it can actually be done manually by accessing the value by index position then overwriting it, but it’s quite tiring to do that when you have more than 10 items on the array, right?

But with loops, doing so have never been easier.

For example, when we want to change the values of the array into the square of its original value, we can easily do it like this:

Code

Main.Cpp

#include<iostream>

int main(void) {

    int arr[10] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};

    // 1. UPDATING ELEMENT VALUES

    // we start looping at i = 0 since array index starts at 0

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

        arr[i] = arr[i] * arr[i];

    }

    // 2. PRINTING

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

        std::cout << “arr[” << i << “]: ” << arr[i] << std::endl;

    }

    return 0;

Sample Problem 1

Factorials

To get a factorial of a given number, you have to multiply from 1 to the number given to get the desired result. Let’s try doing that on values in an array.

Here, I’ve given you a sample code. Try it out!

Code

Main.Cpp

#include<iostream>

int main(void) {

    int nums[3] = {1, 3, 5};

    // 1. COMPUTATION OF THE FACTORIALS

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

        // this will hold the factorial result

        int factorialResult = 1;

        // now, we need to do another loop here

        // to compute for the factorial of the number

        for(int ctr = 1; ctr <= nums[i]; ctr++) {

            factorialResult *= ctr;

        }

Just a tip by the way! It’s usually better to separate the computations from the printing. Meaning, it’s better to create separate loops for each of them so that each loop will do only one thing and it’ll be easier to debug your code if there are errors.

This is not always the case though, so try to think if it’s indeed better to separate them or not. Don’t worry if you won’t know for now because that’s perfectly normal as you’re still starting to learn programming.

Assignments:

Go to https://code.sololearn.com/cpp , sign up, sign in, and start coding to do the assignments then submit to Google Classroom:

1. A Missing Piece

by CodeChum Admin

Something’s wrong with the program I’m making and I just can’t seem to figure it out. Will you please fix it for me?

Instructions:

  1. There seems to be some things missing from the basic C++ structure code in the code editor. Your task is to find out what’s missing from the code and fix it to prevent making errors when running your code.

2. Morning Greetings

by CodeChum Admin

I’m feeling good today! The sun is up and shining, and the cold breeze of air sweeps through my body as I step out to the outside world. It makes me want to scream and greet the world now, but it’s still 6AM in the morning and my neighbors might scold at me for shouting so early in the morning, you know?

But I really want to at least say hello to the world in a quiet way, so can you help me with this little request for a bit?

Instructions:

  1. Your task is to output “Hello, World!” in your program. An initial std::cout function is already provided for you in the code editor on the side, so all you have to do is to use that function to print out the statement.

3. Cheering Squad

by CodeChum Admin

The annual Volley Tourney is just around the corner, and our town’s volleyball team will be joining this time around! To show our support, we’re planning on cheering them on in their game this Saturday!

But oh, we don’t have enough time to practice on the chant though, so we’re planning to just flash some words repeatedly on a screen to serve as our visual guide as of the moment. To do that, we need to ask help from a great programmer and you’re the only programmer we know, so could you help us out again this time?

Instructions:

  1. Create two variables: one containing the uppercase character 'G' and the other with uppercase letter 'O'. You can name the variable anything you want as long as it’s a valid name that is accepted in C++.
  2. Print out the values of the variable in alternate order, twice, on separate lines, using the std::cout function.
  3. The output generated by your code must be the same as that of the sample output.

Output Format

Four lines containing a character on each.Output Sample

G
O
G
O

4. Math is Fun

by CodeChum Admin

Hello there!

I’m a math teacher from the school around the neighborhood and I’ve heard from my co-teacher there that you were the one behind all those amazing games that the students in the school are loving so I’ve come to ask for your help as well!

You see, since young people nowadays are so into technology, I think that if I make my math lessons digital and tech-related then they’d be willing to learn about it more, so I want to ask for your help on starting this plan with just simply showing them an addition example, digitally.

I know it’s quite sudden, but can I ask help from you, too?

Instructions:

  1. There are two variables containing integer values that are already prepared for you in the code editor on the side. Create a variable and store the sum of the two given integers.
  2. Print out the statement like that of the output sample using placeholders.

Output Format

A line containing a string.Output Sample

8·+·2·=·10

5. One and One

by CodeChum Admin

Now let’s start with something simple! Make a program that accepts a single character and an integer and print it out afterwards.

Think you can do it?

Instructions:

  1. Input one character and one integer. Make sure that they are typed on different lines.
  2. Print out the inputted character and integer in one line, separated by a space. You may look at the sample output for your reference.

Input Format

The first line contains a character. The second line contains an integer.Input Sample

C
4

Output Format

A line containing a character and an integer separated by a space.Output Sample

C·4

6. Are Integers Created Equally?

by CodeChum Admin

It’s time to find out if something is true or false, let’s test your capabilities!

Instructions:

  1. Input two integers in one line.
  2. Print the two integers in one line, separate them with a space.
  3. Print a string message on a new line, “Equal” if both integers are equal.

Input Format

A line containing two integers separated by a space.Input Sample

5·5

Output Format

The first line contains the two integers input. The second line contains a string which is the result.Output Sample

5·5
Equal

7. Broken Record

by CodeChum Admin

Looping strings works like playing a broken record – it repeats something over and over again. But what’s great about loops is that we can define as to how many times it will repeat something with proper code, and that’s what we’re about to do now using while() loops.

Instructions:

  1. Input a positive integer.
  2. Using while() loop, repeatedly print out the message "CodeChum is awesome" for the same number of times as that of the inputted integer. Each outputted message must be separated in new lines.
  3. Don’t forget to make an increment/decrement variable that will increase/decrease its value per iteration so as to not encounter a forever loop and have errors, okay?

Input Format

A line containing an integer.Input Sample

4

Output Format

Multiple lines containing a string.Output Sample

CodeChum·is·awesome
CodeChum·is·awesome
CodeChum·is·awesome
CodeChum·is·awesome

8. Triple Cubes

by CodeChum Admin

You can also make a list of numbers, ey? Let’s go and have some fun in tweaking the values of each element, but let’s give it some twist to add on some fun to the code.

Let’s have a go at it!

Instructions:

  1. An array containing 5 integer elements is already provided for you in the code editor below.
  2. Print out the cube of the 1st, 3rd, and 5th element of the given array.

Output Format

Multiple lines containing the cubes of the 3 elements of the given array.Output Sample

-8
1
27