C++ Full Course for free ⚡️
By Bro Code
Summary
## Key takeaways - **C++ is a middle-level language**: C++ bridges high-level languages like Python and Java with low-level hardware instructions, offering speed while still resembling human language. [35:39], [01:15:21] - **Essential tools for C++ development**: To begin coding in C++, you need a text editor (like VS Code or Code::Blocks) and a compiler (GCC for Windows/Linux, Clang for Mac) to translate source code into machine instructions. [01:27:27], [01:56:15] - **Understanding C++ data types**: C++ offers various data types: `int` for whole numbers, `double` for decimals, `char` for single characters, `bool` for true/false states, and `string` for text sequences. [13:36:36], [17:04:04] - **The 'const' keyword for read-only variables**: Prefixing a variable with `const` makes it read-only, preventing accidental modification and enhancing data security, a common practice for values like Pi or physical constants. [01:24:24], [02:35:35] - **Namespaces prevent naming conflicts**: Namespaces provide a solution for identically named entities by organizing code, allowing the same names to coexist as long as they reside in different namespaces. [02:44:44], [02:47:48] - **Type aliases simplify complex data types**: Type aliases, created using `typedef` or the `using` keyword, provide shorter, more readable nicknames for lengthy or complex data types, reducing typos and improving code clarity. [01:32:22], [01:33:35]
Topics Covered
- Why C++'s "middle-level" power matters for performance.
- Pass by reference: Efficiency through direct memory access.
- How const parameters secure your code's integrity.
- Dynamic memory: Flexible array sizing for unknown inputs.
- Recursion: Clean code, but at what cost in performance?
Full Transcript
hey guys in this video you're going to
write your first C++ program so sit back
relax and well enjoy the
show hey if you wouldn't mind please
like comment and subscribe one like
equals one prayer for the YouTube
algorithm I'm going to tell you why you
need to learn C++ C++ is a fast language
like really fast it's commonly used in
advanced Graphics applications a few
examples would include a doobe
applications video editing software
anything that's Graphics intensive C++
is considered a middle level language
therefore it's commonly used with
embedded systems and most importantly
it's commonly used with creating video
games I like video games like a lot
compared to other programming languages
you could say that C++ is a middle level
language programming languages tend to
be on a spectrum the higher level of
programming language is the more it
resembles human language
languages that are closer to being lower
level resemble Hardware instructions
higher level languages such as python
Java and CP are very easy to write with
and to understand but they tend to be
slower C++ and C they take a little more
effort to write but they're very fast
they have the benefit of working closely
with machine Hardware while still
somewhat resembling human language just
a fair warning there is a learning curve
with C++ but if you can learn it it's
worth it there's two things you'll need
to get started one is a text editor a
few options include but are not limited
to would be vs code code blocks or even
notepad VSS code and code blocks are
also considered Ides integrated
development environments they are a text
editor as well as a workshop that
contain a lot of useful developer Tools
in this video I'm going to show you how
to download VSS code but feel free to
use any text editor that you're
comfortable with secondly we'll need a
compiler a compiler ER is a piece of
software that will parse source code to
machine instructions and that's really
it if you're using Windows or Linux
you'll probably want to go with GCC if
you're running Mac you'll probably go
with cang okay cang has a really cool
logo it's blue eyes white dragon so
let's get started well all right then
everybody now we are going to download
VSS code that text editor I was talking
about head to this URL code dovisual
studio.com then select the correct
download for your operating system I'm
running Windows I'll select windows then
I will open
this read the agreement yes I actually
did read it that fast I accept the
agreement
next
next next I'll create a desktop icon why
not next and install we might as well
launch it
finish in VSS code there's two
extensions I would recommend go to the
left toolbar under underneath extensions
we will look up
c/c++ and we would like to download this
extension uh let's pretend that this
wasn't already installed so I'm going to
install it then the next extension I
recommend is code
Runner here it is then just click this
blue button to install
it okay let's close out of
this we're going to create a new folder
to hold our C++ projects go to the left
tool bar explore open folder I'll create
a new folder on my
desktop new folder I'll name this
C++ projects that sounds good to me then
select folder within this folder we'll
create a new file I'll name this hello
world. CPP make sure to get that CPP
extension at the end that means it's a
C++ file okay we now have a C++ file to
work with now we just need to download
that compiler that parses source code to
machine
instructions there's a great set of
instructions at this URL code dovisual
studio.com
slocs let's head to C++ there's
different installation instructions
depending on your operating system
you'll be downloading GCC on Linux if
you're running Linux GCC on Windows for
Windows and clling for Mac OS
downloading a compiler for Linux and Mac
is actually really easy I can cover that
in like 30 seconds Windows is a little
more complicated but let's begin with
Linux so all you're going to do is open
up terminal and enter the following
command GCC SLV that will check to see
if it's currently installed if it's not
you enter this command in then you
install the gnu compiler tools by typing
in this Command right here and that's
all you need to do with Linux if you're
on Mac you'll download
clang open Terminal type in this command
if clang isn't installed all you type is
this command and that's it so pretty
easy right if you're using the Windows
operating system there's way more steps
so let's head to step three we'll need
to install
mgww 64 you can click this link to the
installer this is an executable I'll
open this when it's
done click next next next wait for it we
might as well run this then finish now
we will follow the installation
instructions on this
website under step five we will
type
Pacman Das capitals Yu enter
type y then enter to proceed with the
installation type y then enter again to
confirm to proceed now we'll need to
find this program from the start
menu M
cis2 then type this
command pack
man- Su
enter type y then enter to proceed with
the
installation now we'll need to enter
this command
in there's a lot to type
here Pacman
ds-- needed
base
Dash Dev
L min
gw- w64
DX
86 uncore
64- tool chain then
enter then just hit
enter proceed with the installation type
yes type why enter again then give it a
moment then we can close out of this
window we'll have to find the bin folder
of MW W it's likely going to be within
your C drive go to
m64 MW 64 bin then copy this
address we'll need to add that path to
the windows path environment variable to
do so search
settings
settings we'll search edit environment
variables
go to path
edit let's pretend that this wasn't here
I'm going to go to new paste that
address okay okay close out of this
window just to be sure that our compiler
is working and available let's open up
command prompt command
prompt then type in this command G
Plus+ D- version
enter yeah it looks like it's good to go
we have now successfully installed our
compiler all right everybody let's write
our first C++ program at the top of our
C++ file we are going to type
include within angle brackets IO stream
iostream is a header file that contains
functions for basic input put and output
operations by writing include iio stream
we're including that header file then we
have access to a whole bunch of useful
input and output operations now we'll
need a main function the main function
is where the program begins we'll type
int main parenthesis curly braces We
Begin the program by invoking the main
function and read any code within the
main function starting at the top and
working our way down at the end of our
main function we'll want return zero
then add a semicolon if we reach return
zero that means there were no problems
in this program however if one is
returned that means there was a problem
there was an issue so Place return zero
at the end of your main function what
we'll do in this lesson is write some
basic output to write some output you'll
type
STD contrary to what you might believe
in this case it doesn't mean sexually
transmitted diseases it means standard
follow STD with two colons then type c
out c means character Out means output
Al together this means standard
character output we're going to display
some characters as output then follow C
out with two left angle brackets these
characters mean output it's also known
as the left shift operator when used
with numbers what characters would we
like to display as output within
quotation marks let's write something
what's a food you like I like pizza I'll
type that then follow this statement
with a semicolon at the end of
statements we add a semicolon that lets
the compiler know that this statement is
done it's sort of like the period at the
end of a sentence that's when you know
the sentence is complete so I'm going to
save this I'll hold contrl s or you can
go to file save then click this button
to run
it and there's my output I like pizza on
the next line I'll type
STD two colons C out
two left angle brackets for output I'll
write a second
line it's really
good then I'll run this again you can
press this icon to clear your
output uhoh we have a problem I like
pizza it's really good all of this text
is on one line what if you need the next
line of text to be on well the next line
when you need to move your cursor down
to the next line you can follow some
string of text with
left angle brackets for output
STD colon colon e n DL that means end
line and I'll do the same for my second
line I'm going to save clear my output
run this again yeah there we go I like
pizza it's really good each line of text
is on a different line another option
for a new line that's better
performance-wise is to add a new line
character within single quotes type back
sln and let's replace that here as
well so I'm going to save clear my
output run this again I like pizza it's
really good adding a new line character
does the same thing and it's better
performance-wise however the benefit of
using end line is that end line will
flush the output buffer really you can
use either one but I thought that might
be a nice trick to show you now you can
write a comment a comment is ignored by
the compiler
to write a comment you use two forward
slashes this is a comment comments are
used for yourself for notes or for notes
for another developer so if I were to
run this
again this comment is ignored it's not
used as output or anything like that if
you need a multi-line comment you type
slash asterisk wherever you need your
comment to end you'll Place asterisk
forward slash again this
is
a
multi-line
comment and you can see that all of this
is ignored as well so comments are used
as notes for yourself or for other
developers yeah that's a quick
introduction to getting started with C++
I'll post this code in the comment
section down below if you would like a
copy hey if you enjoyed this video
please be sure to smash that like button
leave a random comment down below and
subscribe if you'd like to become a
fellow bro
hey guys I'm going to explain what
variables are a variable you probably
remember from middle school math class a
variable is a representation of some
number or value there are two steps to
creating and using a variable
declaration and assignment we'll begin
with declaration to declare a variable
we need to list the data type of what
we're storing exactly in programming you
can store more than just numbers you can
store characters even whole sentences
Etc let's work with whole numbers to
store a whole number we will type int
for integer then we need a unique
identifier for this variable for now
let's just say x we're used to working
with like X and Y in math class right we
will end the statement with a semicolon
this step is
declaration now to assign a variable you
take the variable's name that unique
identifier then we will set this equal
to some number since we declared this
variable as an INT it will store an
integer maybe like five now this
variable behaves as if it was the value
that it contains it will behave as if it
was the number five then to display a
variable we can use standard output STD
C
out we will display X and let's see what
we
have there's our value five this first
step is declaration the second step is
assignment the nice thing about doing
this in two steps is that you can later
assign your variable a value if you know
what value you would like to give your
variable right away you can do that at
the beginning of your program you could
combine both of those steps int xal 5
and that would do the same thing in
cases where you don't know what value
you would like to give a variable you
could assign it later such as when you
accept user input you don't know what
the user is going to type so let's
create another int y = 6 then let's
display whatever Y is I'll add a new
line let's copy this paste
it okay X is 5 Y is 6 we could even do
something like this let's say int sum =
x + y then we'll display whatever our
sum variable is see out sum the sum of x
+ y is 11 now there's different data
types depending on what you need to
store than a variable exactly the int
data type stores a whole integer let's
think of a few examples of whole
integers what about an
age that's typically a whole number int
age equals 21 let's think of two more
examples what about a year in year
equals
2023 how about days int days equals 7
the int data type can only store a whole
number number with days what if we
assign this a value of 7.5 let me show
you what
happens all right I will display
days all right that decimal portion is
truncated when I display days and we
attempt to assign
7.5 well this variable can't store that
decimal so it's truncated if you need a
number that includes a decimal portion
there 's a different data type for that
and that is a
double this is a number including
decimal a few examples of a double would
be maybe a price there's dollars and
cents
double price equals
$10.99 what about a GPA a grade point
average that includes a decimal double
GPA equals
2.5 uh then maybe a
temperature
double
temperature equals
25.1 I guess this could be an either
Celsius or Fahrenheit then let's display
maybe
price
price yeah and that decimal portion is
not truncated much like like what you
see with whole integers if you need a
number that includes a decimal portion
use a double now we have the Char data
type that stores A Single
Character type Char maybe we're working
with student grades I'll name this
variable
grade equals then to store a single
character you use single quotes this
student has an
a two more examples what about an
initial singular not initials
Char
initial uh what about B so I'm going to
display
initial
initial okay we have our Single
Character of B now check this out what
if I attempt to store more than one
character I'll add C we have a warning
we have an overflow in conversion from
int to char so what's displayed is the
last character just see so chars can
only store A Single Character here's one
more example of a Char data type what if
we're working with currency what type of
currency will we work with
Char
currency
equals maybe a dollar sign if we're
working with a different type of
currency we could change this to a
different symbol yeah that's the Char
data type it stores A Single Character
next on our list is is
Boolean Boolean a variable that's
Boolean has only two states true or
false to create a Boolean variable you
type bull then a variable name so these
are applicable to anything that has two
states what if somebody is a student
they're either a student or not a
student bu student equals true if
they're not enrolled in classes or they
graduated you could set to be false
think of a light switch the light switch
can either be on or off you could say a
light switch is Boolean there's only two
states true or false how about bu power
is something powered on or not power
equals true if it's turned off that
could be false maybe we have a store and
we need to Mark if something is for sale
or not like is it
available bu for sale equals true if an
item in our or isn't for sale like it's
not available we could set this to be
false so that's the idea behind Boolean
values it has two states true or false
the last data type I'll cover is strings
a string is technically an object that
represents a sequence of text think of
it as the Char data type but we can
store more than one character even whole
sentences like a name or an address
strings are provided from the standard
namespace to declare a string we would
type
standard string then a variable name
what about just name like we're storing
a user's name place your text within a
set of double quotes then why don't you
type your first name then we will store
that within this variable name then to
test it let's display
it standard output we will display
name and there is your first name let's
create a couple more examples what about
about a day of the week standard string
day then pick a day I like
Friday what about
food standard string
food I like pizza I'll store this series
of text as a string then maybe an
address standard
string
address equals make up some address 1 2
3 fake Street basically speaking a
string is a type of object that
represents a sequence of text such as a
name a day an address Etc now I'm going
to show you how we can display a
variable along with some text I would
like to display hello then whatever your
name is I will type what is known as a
string literal we're literally printing
a string
hello follow this string of text with a
variable my variable name is good then
let's display
it hello then whatever your first name
is but you do have to pay attention to
spacing after my word hello I'm going to
add a
space there hello bro then let's display
our
age so I'm going to add a new line
character
standard output we will display you
are
age years
old there hello bro you are 21 years old
uh make sure to pay attention to the
spacing as well because it's easy to
mess that up all right so those are
variables we covered a few of the basic
data types but there's more advanced
data types once we gain a little bit
more experience with this that I'll
cover we have integers which store a
whole number doubles which are numbers
that include a decimal portion chars are
single characters booleans are either
true or false then strings represent a
sequence of text an important note with
strings is that you can include numbers
but they're treated differently so yeah
those are variables in C++ your
assignment is to in the comment section
post a integer variable a double a
character Boolean and a string think of
some examples preferably some examples
that I may have not covered already that
would be good practice well yeah and
that's an introduction to variables in
C++ all right welcome back everybody in
this video we're going to discuss the
const keyword the const keyword
specifies that a variable's value is
constant it tells the compiler to
prevent anything from modifying it so
that it's effectively readon here's an
example let's create a program to
calculate the circumference of a circle
we'll first Define the variables that
we'll need we have double Pi Pi =
3.14159 then we have Double Radius pick
some radius I'll pick
10 then double circumference
equals and here's the formula to
calculate the circumference of a circle
it's 2 * pi times
radius then we will display our
circumference standard output we will
display
circumference then I'll add maybe
centimet our circumference
is
62.83 cm
any variable we do not want to be able
to be changed at all we can turn into a
constant let's say that somebody goes
into our program and changes pi to a
different number like
42069 well then this is going to change
the result of our program we may have
not realized that somebody changed the
value of pi to 42069 so any variable you
do not want changed you can prefix this
keyword
const const double Pi now a common
naming convention for constants is to
make all of the letters uppercase so
let's change PI from lowercase to all
uppercase and we'll need to make that
change here as well now let's try and
change pi to 42069 again then see what
happens okay we have an error assignment
of readon variable Pi so by including
constants it adds some data security we
can't normally change any value that's a
constant a couple other examples of
variables that you could turn into
constants could be maybe the speed of
light maybe you have a physics
calculator so
const in light speed the speed of light
in meters per second is 299
792
458 let's think of one more example
perhaps you're working with screen
resolutions we have
const int width of 1920
then const in height of
1080 these may be a few examples uh
variables you do not want to be changed
or altered at all you only want them to
be readon yeah that's a const everybody
it's a keyword that will modify a
variable or some value so that it's
readon and can't be changed you should
use constants as often as possible only
if you know that a variable is not going
to be changed at all your assignment is
to think of a constant and post in the
comment section hey if you're enjoying
the series please be sure to smash that
like button leave a random comment down
below and subscribe if you'd like to
become a fellow
bro hey everyone I have a quick video on
namespaces a namespace provides a
solution for preventing name conflicts
especially in larger projects each
entity needs a unique name a name space
allows for identically named entities as
long as the name spaces are different
now what the heck does that mean
suppose we have variable x x equal 0
each variable needs a unique name I
couldn't create a second variable named
X and give this a different value if I
were to compile and run this program we
would run into an error red Declaration
of int X so each entity needs unique
name but if we use namespaces then two
or more entities can share the same name
to create a namespace let's do so
outside of the main function I will type
namespace then some name for the
namespace let's say first then a set of
parentheses I could create a different
version of X I'll give this a different
value like one well this would run and
compile just fine you can have different
versions of the same variable as long as
they're within a different namespace
just for fun let's create a second
namespace namespace second x = 2 this is
also valid so just to demate a few
things I'm going to display what x is if
I don't explicitly State what namespace
we're using we will use the local
version of an
entity if I display x x would be zero if
I would like the version of X that is
found within the first namespace I would
take that entity in this case X prefix
the namespace let's say first then two
colons the two colons is known as the
scope resolution oper Ator I'm referring
to the version of X that is found within
the first namespace and that version of
X has a value of one if I need the value
of x found within the second namespace I
would precede that entity with the
second namespace followed by the scope
resolution operator so that version of X
is two so entities can have the same
name as long as they're within a
different name space now one line that
you may see is use using namespace then
the name of a namespace let's say first
if we have some entity without a prefix
of the namespace it's assumed that we're
using the entity found within that
particular
namespace so if I was to display X while
we're using namespace
first X would be one and I don't need to
add that prefix but if I need X found
within the second namespace I would
still need to prefix it with second
X is 2 if I changed using namespace to
Second it's implied we're using the
second namespace and I don't need that
prefix two but I still would if I need X
from the first name
space one now there's this evil line
called using namespace STD for standard
now the reason that people include this
line is to save a little bit of typing
if we're using namespace STD we don't
need to include that prefix when we
declare strings or we display output
with C out just for example like this
would still compile and run however the
standard namespace has hundreds of
different entities let me show you
standard there's a high likelihood of a
naming Conflict for example we have an
entity named data one alternative is
that we could say
using standard output that will cut down
on some some of the repetitions or using
standard
string it's a safer alternative to using
namespace
standard in the future I'm not going to
be using namespace standard because I
would like to steer people away from
that but just in case you see that line
you know what it's there for so in
conclusion a namespace provides a
solution for preventing name conflicts
each entity needs a unique name and
namespace allows for identically named
entities as long as the namespaces are
different so those are namespaces hey if
you're enjoying this series let me know
by Smashing that like button leave a
random comment down below and subscribe
if you'd like to become a fellow
bro hey everyone in this topic I'm going
to explain type defs and type aliases
now type def is a reserved keyword used
to create an additional name for another
data type kind of like a nickname it's a
new identifier for an existing type one
of the reasons that people use type def
is that it helps with readability and
reduces typos here's an example in this
example I'll need to include this header
file
include Vector suppose we have this very
long data type and I would like to give
it a nickname an
alias I would type the keyword type def
then list the original data type so
we're used to Strings ins doubles well
here's a really complicated one one and
of course I don't expect anybody to know
this at this level yet
standard
Vector
standard
pair standard string int so this is one
really long data type this could be a
data type for a pair list but I don't
want to have to type all of this so what
I could do is give this data type an
alias using this type Dev keyword after
the original data type I'll come up with
a new name a new identifier let's say
pair list that's a lot easier to write
than all of this for the data type a
common convention when using the type
def keyword the new identifier usually
ends with underscore t for type now
suppose I declare a variable of this
data
type standard Vector standard pair
standard string int let's say the name
is pair list in place of using the
original data type we can use the new
identifier pair listor T so that's one
of the main benefits of using the type
def keyword we can give a new identifier
to an existing data type it helps with
code readability and helps reduce typos
this data type is way beyond our level
of understanding right now let's try
some simple examples I'll turn this line
into a
comment then get rid of that let's
create a type def for standard strings
type def then we list the original data
type standard string in place of using
standard string as the data type I'll
create a new identifier for this data
type as maybe just text textor T if I
need to create a string I could use this
new identifier in place of saying
standard string then maybe first
name I can replace the data type with
the new identifier if I choose to text T
and I'll set my first name equal to
whatever my first name is feel free to
set it to your own first name and this
variable behaves exactly like a string
so let's display it standard
output first
name and then we should have our first
name yeah there we are okay now let's
try this with an
integer type da we list the old data
type int let's create an identifier for
INT as number that's more descriptive
underscore T although it's more to write
technically in place of using the int
data type I could use number T and this
is technically an integer uh let's say
age then make up some
age standard output I will display my
age then I will add a new line
yep we have our first name and our age
now type def has largely been replaced
with the using keyword that's because
the using keyword works better with
templates which is a topic for another
video so in place of using type def I
recommend using the using
keyword so I'm going to turn these lines
into
comments now if we were to use the using
keyword we would type using
then the new data type so let's say text
T equals the old data type standard
string then let's do that with number
using the new identifier number T equals
int and that would work the
same we have our first name and our age
the using keyword is more popular than
typed def nowadays just because it's
more suit for templates and like I said
that's a topic for another video all
right everybody that is the typ def
keyword and type aliases typed def along
with the using keyword they're used to
create an additional name an alias or
nickname for another data type it's a
new identifier for an existing data type
it helps with readability and it reduces
typos however you should really only be
using the typ def and using keywords
when there is a clear benefit so yeah
that is typ defs and type aliases your
assignment is to post a type def in the
comment section down below and well yeah
those are type defs and type aliases in
C++ all right everybody welcome we are
going to discuss arithmetic operators
arithmetic operators return the result
of a specific arithmetic operation such
as addition subtraction multiplication
and division let's say we have 20
students int students equals 20 if a new
student joins our class we would like to
add one student well if we're working
with the variable we could say students
equals whatever students is+ one then we
could display this standard output I
will display students the current number
of students that we have are 21 there is
a shorthand way of writing this too in
place of saying students equals students
+ 1 we could shorten this to students
plus equals 1 that would would do the
same
thing 21 if we need to add two students
this would be students equals students
plus two or students plus equals 2 then
we have 22 students if you need to add
one to a variable you could also use the
increment operator this is another
option and the preferred way if you only
need to add one you would say students
Plus+ we now have 21 students you tend
to to see this in a lot of Loops which
we'll cover later okay now we have
subtraction students equals students -
one there are now 19 students we could
shorten this
to students minus equals
1 there are 19 students if you need to
subtract two we could say either
students equals students minus 2 or
students minus equals 2 that would do
the same thing there there are 18
students another option is the decrement
operator if you need to decrement a
variable by one you would say students
minus
minus this only subtracts one from a
variable there are 19 students so that
subtraction to use multiplication you
use an asterisk I'm going to double the
amount of students that we
have students equals students *
2 there are 40 students or we can
shorten this to students times equals 2
and again there are 40 students for
division you use a forward
slash I'm going to divide our class in
half students equals students divided
two there are 10 students the shorthand
way is students / equals
2 there are 10 students now check this
out we have 20 students what if I divide
students by
three we're working with an in variable
so this variable can't hold any decimal
portion 20 / 3 that is 6 so any decimal
portion is lost it's truncated but if we
change students to be a double well then
that decimal portion is retained 6.66
repeating students if you need the
remainder of any division you can use
the modulus operator let's create a new
variable int remainder equals students
modulus 2 we'll divide our group of 20
students into groups of two then I'll
display the remainder okay 20 divides by
two evenly so there's no remainder but
what if we divide students by three and
get the remainder our class of students
is being divided into groups of three
for maybe like a project but 20 doesn't
divide by three evenly therefore our
remainder is two there will be six group
groups of three students and one group
of two students Now using the modulus
operator is a great way to find out if a
number is even or odd take some value or
variable you would like to check modulus
2 if that number divides by two evenly
where the remainder is zero well it's
even if the remainder is one well then
it's an odd number 21 doesn't divide by
two evenly so that is the modulus
operator it gives you the remainder of
any division these arithmetic operators
have an order of Precedence we resolve
any arithmetic op operations that are
first within parentheses then
multiplication and division then lastly
addition and subtraction perhaps we have
this
formula students
equals
6 - 5 + 4 * 3 / 2 so what do we solve
first in this equation we would check
any parentheses first which there aren't
any of then we resolve any
multiplication and division so let's go
through this so we have some
multiplication here we would resolve 4 *
3 first that is 12 then we have some
division 12 / 2 is 6 then any addition
and
subtraction 6 - 5 is 1 1 + 6 is
seven and let's check to see if that's
right so students should be seven yep
students is seven now you can force
operator precedence by surrounding some
part of your equation with parentheses
I'll surround this part of the equation
with the set of parentheses the new
result is -7 well yeah everybody those
are some basic arithmetic operators they
return the result of a specific
arithmetic operation hey if you would
like a copy of this code I'll post this
in the comment section down below and
pin it to the top and well yeah those
are some basic arithmetic operators in
C++ hey what's going on everybody in
this video I'm going to explain very
basic type conversion type conversion is
the conversion of a value of one data
type to another two ways in which we can
do this are implicit and explicit
implicit is done automatically if done
explicitly we proceed a value with the
new data type within a set of
parentheses you list the new data type
put it before a variable or a value
let's perform an implicit cast suppose
we have variable int X I will assign X
the value
3.14 integers can only hold a whole
number if I were to display X standard
I'll put
X well the value is three we truncated
the decimal portion and implicitly
converted this number into an integer
what if x was of the double data type
double x =
3.14 well then we would retain that
decimal portion what would happen if I
cast 3.14 as an integer then assigned it
to a
variable before the value add a set of
parentheses then the new data type I
will convert 3.14 to an integer then
store it within this double x x now
equals 3 it's a whole integer that is
one example of implicit and explicit
type conversion here's a few other
examples I have character
x equals some number like 100 if I were
to display what x was standard output
put X well we will implicitly cast this
number 100 as a character we'll convert
it using the asky table to whatever its
equivalent is the number 100 converted
to a
character is the letter
D let's try an explicit
cast I will display the number 100
explicitly cast to a
character and that value is the letter d
as output
how is this useful suppose we have an
online exam we have to give the user a
score how many questions did they get
right divided by how many questions were
total let's write something like this
int correct equals maybe 8 the user has
eight questions that are right int
questions equals 10 there are 10 total
questions I need to calculate the score
as a percentage we could say double
score equals
correct divided questions time 100 then
let's display whatever the result is
standard
output
score then I'll add a percent sign to
the
end 8 / 10 is8 right time 100 that
should give us
80% uh we have 0% well that's because
we're using integer division questions
is of the data type when we're dividing
8 by 10 we're truncating that decimal
portion we're getting rid of it then
multiplying whatever Remains by 100 I'm
going to explicitly cast questions as a
double of the double data type and we
should retain that decimal
portion yeah there we go 80% where
you'll use type conversion it really
varies but you should be aware that you
can do it such as when using integer
division so yeah that's type conversion
in C++ hey if you're enjoying this
series let me know by Smashing that like
button leave a random comment down below
and subscribe if you'd like to become a
fellow
bro all right let's get started
everybody in this video I'm going to
show you how we can accept some user
input in C++ we're familiar with C out
followed by the insertion operator which
is two left angle brackets while to
accept some input we would type c in for
character input followed by the
extraction operator which is two right
angle brackets here's a demonstration
let's ask a user for their name I'll
create a string variable standard string
the name will be well name then I'll
create a prompt which will ask the user
what their name is standard output
insertion
operator what's your
name then to accept some user input we
would type standard CN for character
input
extraction operator then where would we
like to store the user input let's store
it within our variable name at the end
of our program let's display what the
user's name is standard
output insertion
operator
hello name okay we're going to have one
problem though if we're using vs code as
our text editor we need to begin using
the terminal tab previously we've been
using output so I can't actually type in
anything to this cuz it's well output if
you're using vs code this is what we'll
need to do if you're not you can skip
the step we're going to go to file
preferences settings look up code
Runner then we are looking for run in
terminal which is right about here check
that close this tab let's stop this from
running and we'll run it again okay here
we go what's your name I'll type in my
first name hit enter
hello bro or whatever your first name
was this time let's ask a user for what
their age is I'll store this within a
variable named age int
age standard
output what's your
age standard
input extraction operator
age standard out output insertion
operator you
are
age years
old and I think we'll need some new line
characters right about here just
one okay this should work let's try
it what's your name I'll type in my
first name hit enter what's your age
I'll make up an age I like to think that
I'm 21 still hit enter hello bro you are
21 years old so that's how to accept
some user input you can use CN for
character input uh but there's just one
problem though if you type in a string
that has spaces well once we hit a space
we stop reading that string this time
let's ask a user to type in their full
name okay type in your first name and
your last
name hit enter what's your full name bro
code what's your age hello bro you are
Zer years old if we need to read a
stream
that could contain spaces there's a
function that we can use to help us with
that that is the get line
function standard get line add a set of
parentheses within the parenthesis we
will type standard C in then comma our
variable name now we should be able to
type in a string including any
spaces what's your full name type in
your own first name and last name hit
enter what's your age I'll type in 21
hello bro code you are 21 years old if
you need to accept a string that
includes any white spaces you're better
off using the getline function and if
you forget I'll post this in the
comments section so you can always take
a look at it if you don't remember okay
there's just one issue with this though
I'm going to move the second question
above the
first let's take a look to see what
happens what's your age 21 what's your
full name hello you are 21 years old
here's the issue if we accept some user
input with C in followed by get line
well in our input buffer there's a new
line character and we don't pick up that
new line character when we reach the get
line function it accepts the new line
character that's still within the buffer
so to prevent that from happening
there's one change that we can make to
the getline function after CN add this
extraction operator standard WS for any
Whit spaces this portion will eliminate
any new line characters or any white
spaces before any user input so let's
try this again what's your age I'll type
in 21 type in your full
name and there we go hello bro code you
are 21 years old so yeah everybody
that's how to accept some user input
basically you can just use CN followed
by the extraction operator but if you
need a string that could include spaces
I recommend using the getline function
so yeah that's how to accept some user
input in C++ plus if you would like a
copy of all this code I'll post this in
the comment section down below and well
yeah that's how to accept some user
input in
C++ hey guys in this video I'm going to
show you eight useful math related
functions in C++ let's begin by creating
three variables double X and I will set
this to be three Double Y that will be
four then double z we will declare this
but not assign it the first useful math
related function is the max function
which will return the greater of two
values or
variables I'll assign the result within
z z
equals standard max parentheses within
the parentheses add two values or
variables I'll compare X and Y then
let's display the result standard output
I would like to display whatever Z is
the greater number between three and
four is well you guessed it four
alternatively there's the Min function Z
equals standard Min let's compare X then
y so the minimum between these two
values would be three so that's Max and
Min now the rest of these functions are
found within the cmath header file at
the top of our file let's include C math
we have the PO function to raise a base
to a given power
Z equal PO for power let's raise 2 the^
of
3 Z would be 8 2 the^ of 4 would be 16
that's the power function then we have
square root Z =
sqrt what's the square otk of 9 well the
square < TK of
9 is three
then we have absolute value Z equals Abs
if you place a negative number within
the absolute value function it will give
you the positive version of that number
how far it is away from zero so -3 the
absolute value of -3 would be 3 that is
the absolute value function next we have
the round function let's change X to
3.14 Z equal round let's round x 3.14
rounded would be three if you need to
round up there's a cealing function Z
equals Seal Seal means cealing let's
round x x rounded
up is four alternatively there's the
floor function which will always round
down let's change X to 3.99 to test it
Z equals
floor x x rounded
down is three so yeah everybody that is
a super quick video on a few useful math
related functions if you head to this
URL C+ plus.com reference cmath there's
a lot more useful math functions that
you may be interested in but we just
covered a few of the basics in the next
topic we're going to create a practice
program to find the hypo new of a right
triangle so yeah those are a few useful
math related functions in
C++ okay everybody this is going to be a
practice project to calculate the
hypotenuse of a right triangle which we
can find with this formula C = theare <
TK of a^2 + b^2 we'll Begin by declaring
our variables double
a double
B Double C
make sure you include cmath as well
because we'll be using the power
function as well as the square root
function at this point we'll accept some
user input for sides A and B standard
output will create a
prompt enter side
a standard
input
a then we'll need side B standard output
put enter side
B standard
input
B we can handle this formula step by
step we could reassign a equal
to power function a to the power of
two b equals power function B to the^ of
two side C equals the Square t of a +
b then at the end we will display
whatever side C is
standard
output side
C
C okay let's try
this enter side a I'll type in three
side B will be four side C is five we
could shorten this code too we could say
the square root of a to the^ of 2 plus b
to the^ of
two then we no longer need these two
lines that's another way of writing it
in less lines of code let's try this
again this time side a will be four side
B will be five side C is 6 .4 so yeah
everybody that's a simple practice
project just to get us used to accepting
user input as well as some math related
functions if you would like a copy of
this program I'll post this in the
comment section down below and well yeah
that's a simple practice project in
C++ all right guys we are on if
statements with an if statement you do
something if a condition you set is true
if not then don't do it it's as simple
as that we'll ask a user what their age
is if their age is greater than or equal
to 18 they'll be allowed into our site
if they're under 18 well we won't let
them in let's declare variable age int
age then we'll create a prompt standard
output enter your
age
standard
input age okay this is how to write an
if statement you type if then a set of
parenthesis then a set of curly braces
if some condition within the parentheses
is true you perform some subset of code
we are going to check if age is greater
than or equal to 18 greater than or
equal to is a comparison operator
there's other comparison operators such
as less than or equals to less than
greater than if you need to compare if
two values are equal you use two equal
signs you don't want to say equals cuz
then you're setting age equal to 18
equals is the assignment operator so
let's check to see if age is greater
than or equal to 18 then we'll print a
message standard
output welcome to the
site okay let's try
this enter your age let's say that I'm
12 well it doesn't do anything since
this condition EV evaluated to be false
we skip over this body of code if it
were true then we execute it this time
my age is 21 I hit enter welcome to the
site if you would rather do something
else if a condition is false you can use
an else statement an else statement you
will place at the end there is no
condition else we will print standard
output you are not old enough to enter
okay let's try this
again enter your age I'll say that I'm
12 you are not old enough to enter
that's an if statement if some condition
is true you do something if not you can
do something else or nothing at all
there are more conditions you can check
by using an else if statement we can
check another condition by adding else
if if this condition is false check this
else if condition uh let's check to see
if age is is less than
zero that means somebody hasn't been
born
yet you haven't been born
yet okay now check this
out let's say that my age is
-10 and I hit enter you haven't been
born yet since this condition was false
we skip the section of code then we
check the else if statement since this
condition was true we execute this body
of code then skip over the else
statement let's add one more Els if
statement else
if age is greater than or equal to
100
standard
output you are too old to enter this
site okay enter your age I am 120 years
old I hit enter welcome to the site we
check these conditions one by one
starting from the top we stated that our
age was 120 years old even though we
were expecting to execute this body of
code we instead executed this body of
code within the if statement that's
because our age was technically still
greater than or equal to 18 so the order
of your if and else if statements does
matter it makes a difference if we need
to execute this body of code if
somebody's age is greater than or equal
to 100 well then we should probably move
that to the top then turn it into an if
statement else if age is greater than or
equal to 18 we will display this message
let's try this one more time enter your
age I am 120 years old I hit enter you
are too old to enter this site so yeah
that's an if statement you do something
if a condition is true if not then you
don't do it if you would rather do
something else you can use an else
statement if there's other conditions
you would like to check before reaching
the else statement you can use an else
if statement and there's really no limit
to these if you would like a copy of
this code I'll post this in the comment
section down below and well yeah those
are if statements in
C++ all right everybody today we're
going to discuss switches a switch is an
alternative to using many else if
statements it Compares One value against
many matching cases here's an example of
what you don't want to do I have this
program we have variable month month is
of the integer data type the user will
type in a number 1 through 12 to
represent the month if month is equal to
1 it is January else if month is equal
to two it is February else if month is
three four five so on and so forth this
is what you don't want to do because
it's inefficient it's how the game
yandere simulator was created if you
know what that is a better solution
would be to use a switch this is how to
right one I'm going to delete all of
this we will type switch parenthesis
curly braces what value would we like to
examine against matching cases let's
examine our month to write a case we
would type case then the value let's
check to see if month is equal to one so
case one colon on the next line what we
want to do if month is equal to one
let's display a message stand
output it is
January at the end of this case add
break to break out of the switch so that
is case one let's work on case two so
case two it is February I think the rest
is self-explanatory I'll speed up the
footage
we have our 12 cases 1 through 12 each
case corresponding with a month of the
year let's run this enter the month
let's say that the month is Four for
April it is April one more time time the
month is 12th it is December so a switch
is an alternative to using many else if
statements it's more efficient and
easier to read if there are no matching
cases we can execute a default case type
default then what would we like to do
standard
output let's say please enter in only
numbers 1 through 12
enter the month uh let's type
42 please enter in only numbers 1- 12 so
the default case is kind of like the
else statement if there are no matching
cases we execute whatever is within the
default case let's try one more example
this time we'll have a user enter in a
character a letter grade will display a
custom message depending on what grade
they have
Char
grid standard
output what letter
grade
standard
input
grade then we'll create a switch switch
parenthesis curly braces we're examining
our letter grade against matching cases
the first case will be the character a
what will we display if somebody
receives an
a standard
output you did
great then
break case
b standard
output you did
good then break
case
C
standard
output you did
okay
break case
D standard
output you did
not do good
break case
f standard
output you
failed break then let's add a default
case please only enter in a letter
grade A through
F let's try it what letter grade I
received an a you did
great what letter grid F you failed then
let's test our default case what letter
grid
pizza please only enter in a letter
grade A through F so yeah that's a
switch everybody it's an alternative to
using many else if statements it's more
efficient and easier to read your
assignment is to create a switch and
post it in the comment section and well
yeah those are switches in
C++ hey guys in this video we're going
to create a simple calculator program
now that we know how switches work this
will be a very simple program let's
begin by declaring our variables at the
top we'll need a character for an
operator we'll name this op the operator
will be either addition subtraction
multiplication or
division double num one double num two
double
result this next part isn't necessary
but I'm just going to add one line of
text when we begin the program I'll add
a bunch of asterisks let's say
calculator then I'll add a new line to
the
end wherever my program ends I will
create another line of
asterisks and I can get rid of that new
line character
our code for our program will be within
these two lines of output let's ask the
user what operand they would like
standard
output enter
either addition subtraction
multiplication or
division
standard
input we'll store the response within
the variable
op standard output
enter number
one standard
input num
one let's copy these two lines paste
them change one here and here now we
need a
switch switch parentheses curly braces
we're examining our operator against
matching cases the first case will be
addition make sure the operand is within
single quotes cuz it's a character if
the user wants to add two numbers we'll
take result equals num one plus num 2
display the result standard output will
display the word
result followed by the variable
result then I'll add a new line to the
end then break then we need a case force
subtraction case subtraction num one
minus num
two
multiplication case
multiplication num
one times num two then
division case division num one / num two
what if somebody doesn't type been a
valid operator let's add a default case
default standard
output that wasn't a valid
response then break I'll add a new line
too okay we are good to go let's save
run
this
calculator let's add two numbers enter
number one
1.23 enter number two
3.14 the result is
4.37 let's run this
again we will subtract two
numbers
1.23 - 3.14 is -
1.91 let's multiply two
numbers
1.23 *
3.14 that's 3 3.86
22 now we will divide two numbers
1.23 /
3.14 that is
0.39
172 let's type in an operator that's not
valid how about a w enter number one
1.23
3.14 that wasn't a valid response
actually I think it would be better if
we said that wasn't a valid operator
all right everybody that is a simple
calculator program in C++ using a switch
if you would like a copy of this code
I'll post this in the comment section
down below if you're enjoying this
series please let me know by Smashing
that like button leave a random comment
down below and subscribe if you'd like
to become a fellow
bro okay guys we are talking about the
tary operator which is represented by a
question mark followed by a colon It's a
replacement to using an if else
statement you write a condition then add
a question mark kind of like you're
asking a question is something true if
that condition is true we can do some
code if it's false we do some other code
here's an example we have a grade my
grade is 75 if grade is greater than or
equal to 60 I'll output you pass else
will output you fail my grade is
75 therefore I pass another way of
writing this is to use the tary op
operator first we write a condition so
let's get rid of this if
statement after our condition We'll add
a question mark now parentheses are
optional then we write some
expression standard output you pass we
do this if our condition is true colon
what will we do if that condition is
false well let's use whatever is within
our else
statement and this would work the same
if my GR is
75 you
pass if it's
50 you fail let's come up with a few
other
examples let's check to see if a number
is even or
odd int number equals what about nine we
write a condition we'll check if number
modulus 2 remember modulus gives you the
remainder of any division does number
divide by two evenly so this returns a
one or a zero if number modulus 2 is
equal to
1 question mark then let's
display
odd if it's false we'll display standard
output
even okay odd let's change number to
8 now it's even you don't necessarily
need equals 1 or equals 0 the number one
does correspond to true and zero
corresponds to false so you could write
it like this too 8 divides by two evenly
that's even if it's
nine that is odd okay last
example let's examine a Boolean variable
bull how about hungry is somebody hungry
I'll set this to be
true let's write our
condition
hungry equals true question mark now if
you're examining to see if a Boolean
variable is true you don't necessarily
need equals true you can just say that
Boolean variable hungry question mark
like you're asking a question so if
hungry is true we will do this standard
output use are
hungry colon what will we do if it's
false standard
output you are
full hungry is set to
true you are hungry if it were
false you are full if we're displaying
output there's a couple different ways
in which we could write this it's up to
you how you want to handle it so another
way of writing the same code code would
be
standard
output then within a set of parentheses
then we could use our chary
operator hungry question
mark you are
hungry
else you are
full this would work as well let's just
check that hungry is set to false you
are full let's set it to true
you are hungry so yeah that's the tary
operator everybody it's a question mark
followed by a colon you write a
condition as if you're asking a question
if that condition is true you do some
expression if not you do some other
expression it's a replacement to an if
else statement your assignment is to
post a use of the trinary operator in
the comment section and well yeah that's
the tary operator in C++
hey guys in this video I'm going to
discuss the and or as well as not
logical operators we'll begin with and
the and logical operator will check to
see if two conditions are true here's an
example we'll ask a user what the
temperature is int temp short for
temperature standard output this will be
a prompt enter the
temperature standard input put temp with
the and logical operator we check to see
if two or more conditions are true let's
see if our temperature Falls within a
certain range if condition then a set of
curly braces we'll check to see if our
temperature is above zero if temp is
above
zero and temp is less than let's say 30
in order for us to execute this if
statement both of the conditions must be
true this condition and this condition
must be true if one of them is false we
skip over this if statement so if our
temperature Falls within that
range the
temperature
is
good
else standard
output the temperature
is
bad okay let's try
it enter the temperature uh let's say
it's 25° this will be in
Celsius the temperature is good let's
try it again uh what about
-100°
CSI uh the temperature is bad yeah no
kidding one more time uh positive 100° C
the temperature is bad so with the and
logical operator we check to see if two
or more conditions are true there's
another way of writing the same program
too we can use the or logical operator
which is represented by two vertical
bars it checks to see if at least one of
two conditions are true if temp is less
than or equal to
zero or temp is greater than or equal to
30 the temperature is bad else the temp
temperature is good in order for us to
execute this if statement only one
condition has to be true if both of them
are false we don't do anything what's
the temperature the temperature is 25
that's within that range the temperature
is good one more time enter the
temperature it is1 100° C the
temperature is bad all right so that's
the and as well as the or logical
operator there's one more the not
logical operator which is an exclamation
point it reverses The Logical state of
its operand meaning if a condition is
true it becomes false if it's originally
false it becomes true let's create
another variable this will be a Boolean
sunny sunny can be true or
false I'll write another if
statement if Sunny is equal to
true now if you're examining to see if a
Boolean variable is true you don't
necessarily need to say equals true you
could just type the name of the Boolean
variable if
Sunny if Sunny is true we'll display a
message standard output it is sunny
outside else standard
output it is cloudy outside
okay one more
time enter the temperature it's 20°
C I should probably add some new line
characters there enter the temperature
it's 25° C the temperature is good it is
sunny outside if we use the not logical
operator we can preed a condition with
an exclamation point we're checking to
see if it's not
Sunny that means we would want to change
our output if is cloudy outside else it
is sunny outside let's change Sunny to
be false enter the temperature it is 50°
C the temperature is bad it is cloudy
outside so yeah everybody those are
logical operators and or not your
assignment is to use either the and or
or otherwise not logical operator then
post it in the comment section down
below whatever you wrote so yeah those
are logical operators in C+
Plus+ okay guys in this video we're
going to create a temperature conversion
program to convert from Fahrenheit to
Celsius or Celsius to Fahrenheit at the
top of our program let's declare our
variables double temp temp is short for
temperature then Char
unit will the user select Celsius or
Fahrenheit now with my programs I like
to add a title at the beginning standard
output
temperature
conversion it's totally not necessary
but it's something that I like to do
then I'll add another line of output at
the end of my program to show the user
that the program is over I'll just add a
bunch of asterisks like I said totally
not necessary but it's something I just
like to do I will display a couple lines
of
output f equals
fenit I can never spell Fahrenheit right
I think that's okay I'll add a new
line standard
output C
equals
Celsius add a new
line standard
output what unit would you like to
convert to
standard input
unit the user will hopefully type in F
or C depending on what they want to
convert to let's check to see if the
user types in F first if unit is equal
to the character F that's a capital f
but you know maybe the user types in
lowercase St I'll add an or conditional
operator or you
is equal to a lowercase f that's also a
valid response if the user would like to
convert a temperature to Fahrenheit
these are the steps we can
do standard
output enter the
temperature
in
celsius standard input
temp to store the temperature to convert
our temperature from Celsius to
Fahrenheit we can assign temp equal to
now here's the formula
1.8 * R temp plus
32 then we will display the temperature
standard
output
temperature is
temp
degrees
Fahrenheit then I'll add a new
line if the user would like to convert
to Celsius I'll add an else if
statement else if unit is equal
to the character Capital C or unit is
equal to the character lowercase C
we can copy these two lines of code and
reuse them we'll just repurpose them
enter the temperature in
Fahrenheit here is the formula to
convert from Fahrenheit to
Celsius temp
equals our current temperature -
32 /
1.8 then let's display our temperature
I'll copy this line of code paste it Che
change Fahrenheit to
Celsius now what if the user doesn't
type in a valid
response else standard
output please enter in only C or
F add a new
line and that should be everything let's
try
this temperature conversion program what
unit would you like to convert to I
would like to convert to to
Fahrenheit enter the temperature in
celsius so what's 0° C converted to
Fahrenheit that is 32° Fahrenheit let's
go again let's convert to
Celsius enter the temperature in
fahrenheit what's 100° in
Celsius
37.7 de Celsius let's type in a response
that's not valid uh I would like to
convert to Pizza please enter in only C
or F all right everybody that is a
program to convert from Fahrenheit to
Celsius or vice versa I thought we could
use some practice using conditional
operators as well as if statements if
you would like a copy of this code I'll
post this in the comment section down
below and well yeah that's a temperature
conversion program in
C++ hey what's going on everybody so in
this video I'm going to explain some
useful string method methods that you
might be interested in let's begin by
creating a variable named name standard
string name we'll accept some user input
we'll need a prompt standard
output enter your
name a user's name may contain spaces
we're better off using the getline
function
standard
getline standard CN
name the first useful method is the
length method type your string name
follow it with
DOT length parentheses the length method
will give you the length of a string
let's write this within an if
statement if name. length method is
greater than 12 we'll print a message
such as your name can't be over 12
characters
long standard
output your
name can't be over 12
characters else we'll print a different
message standard
output
welcome the user's name enter your name
type in your full name
welcome whatever your name is okay now
what if our name is over 12
characters type in your full
name then just add a bunch of
characters your name can't be over 12
characters that is the built-in length
method of strings you type a string
follow it with DOT length parentheses
wherever you invoke this method in that
spot you will return the length of that
string in characters the empty method
will will return if a string is empty or
not type your string
name. empty parentheses this returns a
Boolean value if name is
empty we'll display a
message you didn't enter your
name
else hello whatever your name
is okay I'm just going to hit enter you
didn't enter your name but if I do enter
my name it works normally hello whatever
your name is that is the empty method of
strings you'll check to see if a string
is empty or not a useful case of this is
to check to see if somebody enters in
some user input another is clear name.
CLE then let's display our name
standard
output
hello
name enter your name type in your first
name and last
name hello and we don't have a name
anymore because that name has been
cleared so that is the clear method we
can append a string to another string
after my name I will use append
parentheses within the parenthesis we
can add a string to the end of another
string I'll add
gmail.com standard
output your username is
now
name andent to your
name your username is your name with
gmail.com appended to it that is the
append method we can return a character
at a given position within a string
standard
output type your string name do at
parentheses so the first character in a
string has an index of zero I'll display
whatever that character is Ander your
name so the first character in my string
is a capital B the character at index
one well that would be R we can insert a
character at a given position type your
string
follow it with
insert there will be two arguments will
list within the parentheses and index so
the beginning of our string would have
an index of zero comma then what would
we like to insert I'll insert the at
sign at the beginning of my
name then let's display our
name okay so we we now have the at sign
inserted at the beginning of our string
or you could pick a different position
the index of one would be the second
character technically so yeah pick a
position then you can insert a string
now we can find a certain character I
would like to find if there's any spaces
within my name name.
find then place a character I'll look
for any white spaces this method will
give me the position of the first space
type in your first name and last name
the index of the first White space
within my name has an index of three the
first character is always zero 0 1 2
three okay then lastly erase
name. erase we can erase a portion of a
string we'll need a beginning index and
an ending index I'll eliminate the first
three characters then we will display
our name enter your
name okay and that's what's left in my
name I deleted the first three
characters the first number is the
beginning index the second is the ending
index it's not inclusive though so yeah
those are a few helpful string Methods
if you would like to know more head to
the string class on the C+ plus.com
website and there's a fairly extensive
list hey if you're enjoying the series
let me know by Smashing that like button
leave a random comment down below and
subscribe if you'd like to become a
fellow
bro hey hey everybody in this video I'm
going to explain while Loops a while
loop is much like an if statement except
we can repeat some code potentially an
infinite amount of times here's an
example of where a while loop would be
useful let's say that we'll have a user
entering their name standard string name
at first I'll use an if statement if
name I'll check to see if the name is
empty did the user actually type in
something if name is empty we'll create
a
prompt standard
output enter your
name
standard
getline standard
input name once we exit the if statement
we'll display a message involving the
user's name standard
output hello
name enter your name I'm just going to
hit enter and not entering anything
hello and I don't have a name what if we
need to force the user to do something
in order to continue with the rest of
the program well we could change this if
statement to a while
loop if this condition remains true we
will execute this code a potentially
infinite amount of times once we reach
the end of this code block we check the
condition again if it's still true we
repeat the code again enter your name
I'm going to hit enter enter your name
no enter your name no enter your name no
so I can't actually continue with the
rest of my program until I type in
something I'll type in my full name hit
enter hello whatever your name is
basically speaking a while loop is kind
of like an if statement except it can
repeat some code infinitely as long as
this condition remains true we check
this condition once when we enter the
while loop then anytime we finish the
while loop we check the condition again
if the condition is false we exit then
continue on with the rest of the program
you do want some way to exit the while
loop let's write a condition that we
won't be able to change it all while one
is equal to one there's no way we can
escape this while loop so this is what's
known as an infinite Loop I'll display a
message
help I'm stuck in an
infinite
Loop then when I run this yeah we're
stuck in an infinite Loop and we can't
actually move on or do anything so yeah
that's basically a while loop everybody
while some condition that you set
remains true you will continue to
execute some code a great use of a while
loop is that you can force a user to do
something in order to continue with the
rest of the code your assignment is to
use a while loop then post it in the
comment section down below and well you
yeah those are while Loops in
C++ all right everybody do while Loops a
do while loop it does some block of code
first and then you repeat that block of
code if a condition is true here's an
example let's write a program that will
ask a user to enter in a positive number
first we'll use a while loop that'll
demonstrate how a do while loop would
actually be better for the situation we
have an integer number int number
I'll write a while loop while number is
less than zero we will prompt the user
to enter in a positive
number enter a positive
number okay standard
input number outside of the while loop
at the end of our program let's display
the number standard
output the
number
is number so this isn't going to work
normally here's why let's run this the
number is zero so this is what's going
on we've declared our number but have
not assigned a value quite yet when we
reach the while loop we check the
condition if the condition is true we
execute this block of code since we've
declared an integer variable but have
not assigned it a value it's defaulting
to just zero 0 is not less than zero so
so this condition is false that means we
skip the while loop and continue on
another way in which we could write this
but it's not the best solution is that
we could copy what's within this block
of code then run it once if number is
still less than zero we would then
execute this block of code repeatedly
let's try this
again okay enter a positive number 1 2 3
the number is 1 2 3 let's type in a
negative number negative 1 enter a
positive number negative 1 enter a
positive number 1 so I can't actually
continue until I enter in a positive
number you know this does work but
there's a much better way of writing
this because you know we're repeating at
least two lines of code when we really
don't need to we need to run this block
of code once and then repeat it if this
condition is true well you know what
would be great for that a Doh Loop let's
eliminate these two lines of code to
create a do while loop we will move this
condition to the
end while then our condition
preceding the left curly brace right do
do this code once and then check the
condition make sure you have a semicolon
at the end let's try it
again enter a positive number I'm just
going to type in a negative number
negative 1 nope 1 nope how about a
positive number 1 2 3 the number is 1 2
3 so that's a do while loop you do some
block of code first then you repeat it
again if the condition is true it's an
optional way to repeat some code one
good use of a do while loop that comes
to mind maybe we're playing a game we
would like to run the game once at the
end of the game a user can choose if
they would like to play again based on
the user's input if they would like to
play again we can run the game one more
time repeatedly so that's a do while
loop everybody I'll post this code in
the comment section down below and well
yeah that's a do while loop in
C++ all right guys in this video I'm
going to explain for Loops a for Loop is
a loop that will execute a block of code
a specified amount of times to create a
for Loop we type for parentheses curly
braces within the for Loop there are up
to three statements that we can add the
first is that we can create an index a
sort of
counter int index I'll set the equal to
be we'll start at one then finish the
statement with a semicolon now what a
lot of people do instead of saying index
they'll just shorten this to I the
second statement is a stopping condition
let's count up to three I'll continue
this as long as I is less than or equal
to three then semicolon to finish that
statement the third statement is that we
can increment or decrement our counter
our index I'll increment my index by one
by saying
i++ okay let's repeat something Three
Times Standard
output how about happy New Year Happy
New Year
here this code should be repeated three
times happy New Year happy New Year
Happy New Year I should probably add a
new line now let's try this five times
we'll begin I at one we'll continue this
as long as I is less than or equal to
5 okay 1 2 3 4 5 that's it this time
let's count up to 10 then display happy
New Year once we exit out of the for
Loop I'll move this line to outside of
the for
Loop I'll set I to be 1 we'll continue
this as long as I is less than or equal
to 10 during each iteration of the for
loop I will display whatever I is
standard output I then I'll add a new
line
okay here we go
go we're starting at one then we're
counting up to 10 then we escape the for
Loop once we escape the for Loop then we
print happy New Year when you increment
or decrement your counter you can skip
iterations let's increase I by two after
each iteration I plus equals 2 now we're
counting up by
twos 1 357 9 Happy New Year we can even
set our index to be a different number
let's begin at Z we're still counting up
by twos 0 2 4 6 8 Happy New Year we
could even increment I by
three
0369 happy New Year or we could
decrement and go backwards
iusus this time we will begin at 10 then
continue as long as I is less than or
equal to zero so this would be a
countdown 10 9 8 7 6 5 4 3 2 1 0 happy
New Year okay let's decrement I by two
after each iteration IUS =
2 108
6420 happy New Year so yeah everybody
that's a for Loop there's a lot of
overlap where you could use either a
while loop or a for Loop for Loops tend
to be better in situations where you
only need to repeat code a certain
amount of times your assignment is to
post a use of the for Loop in the
comment section down below and well yeah
those are for Loops in C++
hey everybody so in this video I'm going
to explain the break and the continue
keywords the break keyword will break
out of a loop another place where you
see this is a switch within a switch
statement continue will skip the current
iteration here's an example let's create
a for Loop that will count up to the
number 20 I'll set I equal to B1 I will
continue this as long as I is less than
or equal to 20 then increment I by One
standard out out put I'll display
whatever I is then I'll add a new line
new
line then let's take a look so we have
the numbers 1 through 20 I would like to
skip the number 13 because 13 is
considered an unlucky number I know it's
a weird example what I'll do is use an
if statement within my for Loop if I is
equal to 13 first we'll break then see
what happens if we break where I equal
13
then we have the numbers 1 through 12
once we hit 13 we break out of the loop
we do not finish the rest of the
iterations if we replace break with
continue this is instead what
happens we have the numbers 1 through 20
but the number 13 isn't there so using
the continue keyword we skip the current
iteration so yeah that's the break and
the continue keywords these keywords are
available if you need them but where
you'll use them it really depends but
just so you know they exist and that is
the break and the continue keywords in
C++ all right guys we are on nested
Loops a nested Loop is just a loop
that's inside of another loop it doesn't
matter what kind of loop you're working
with it can be a while loop or a four
Loop or whatever here's an example we'll
create a loop to count the numbers 1
through 10 we'll count to 10 three times
so let's create a basic Loop for now in
I I'll set this equal to be 1 the
condition will be I is less than or
equal to 10 then I will increment I by
1 during each iteration I will display
whatever I is then I'll add a
space
there this Loop will count up to
10 just like that so now I would like to
count up to 10 three times Well I can
stick this Loop in another loop so let's
create the outer
loop for in I I'll set this equal to be
one I'll continue this as long as I is
less than or equal to 3 then increment I
by
1 so I'm going to take this Loop and
stick it within the curly braces of the
outer for Loop however you don't want
these Loops to have the same index a
common naming convention for the inner
loop is to use J as the counting index j
j j j okay let's take a
look okay now we count up to 10 three
times but what I think I'm going to do
is that every time we exit the for Loop
the inner for Loop I'll just print a new
line character
standard
output new
line yeah that's much better so yeah
nested Loop is just a loop inside of
another loop just as a practice project
let's create a program that will print a
rectangle made out of symbols we'll let
a user specify how many rows and columns
we'll use our Nesta Loop that we created
previously so we have int rows int
columns then char
symbol we're going to ask for some user
input we'll need some prompts standard
output how many
rows standard
input
rows let's copy this paste it change
rows to
columns then
enter a symbol to
use standard
input
symbol we'll continue printing rows as
long as I is less than or equal to rows
whatever we typed in we don't want any
more rows than what the user wants the
inner loop is going to be in charge of
the columns J is less than or equal to
columns in place of printing J let's
print our symbol whatever the user
picked and we do not need to separate
these with any spaces all right let's
try
this how many rows what about three
rows then six columns enter a symbol to
use what about the at sign and there's
our rectangle there's three
rows and six
columns let's try it one last
time how about four rows and five
columns I'll use a dollar sign okay we
have four rows 1 2 3 4 five columns 1 2
3 4 5 so yeah everybody that's a nested
loop it's a loop that's inside of
another loop when you'll use these it
really depends on the situation I
thought this would be a fun practice
project if you would like a copy of this
code I'll post this in the comment
section down below and well yeah those
are nested Loops in C++
hey this is bro from the future before
you begin this topic to work with random
numbers you may need to include this
header file C time hey everybody in this
video I'm going to show you how we can
generate some random numbers just so you
know these are pseudo random numbers
they're not truly random but they're
close maybe if you need to roll a
six-sided dice for a game well then this
would work perfect to generate some
random numbers we'll need to initialize
the random number generator by typing s
Rand add a set of parentheses semicolon
within the S Rand function we'll need a
seed what programmers typically do is
that they'll use the current calendar
time as a seed within the parenthesis
type time parentheses again then pass in
null I'll store the first random number
within a variable int num equals to
generate a random number we invoke the
Rand function then I'll display this
let's take a look to see what we have
standard output
num okay the random number that we have
is
3,231 using the Rand function this will
generate a random number between 0 and
32,767 but we don't necessarily need a
number that large I just need to roll a
six-sided dice well what we're going to
do is follow this with modulus than the
range of numbers we would like if I'm
rolling a six-sided dice I'll type
modulus 6 modulus gives you the
remainder of any division so take
whatever number We Roll divide it by six
take the remainder and that's our number
but there's one issue with this we have
five 2 and zero technically the range of
numbers is currently 0 through 5 if we
need 1 through six what we can do is add
one plus 1 this should give us a random
number between 1 and and
six there it is six so I tend to play a
lot of Dungeons and Dragons there's
polyhedral dice one die that we commonly
roll is a 20-sided dice so if I would
need a random number between 1 and 20 I
would say Rand function modulus 20 my
random number is one wow that's
surprisingly
low then I have a 14 maybe you need a
random number between 1 and 100 Rand
function modu
100 my random number between 1 and 100
is 67 now I need to roll three six-sided
dice I'm going to create three
variables let's name this num one Rand
function modulus 6 + one then let's copy
this paste it twice we have num one num
two num three let's display num one I'll
add a new line
then do this two more times for Num two
and num three so our three dice that
we're rolling are 5
22 then again 3 1 4 yeah everybody
that's how to generate some pseudo
random numbers they're not truly random
but they're close if you have a simple
game you're working on this would work
perfect if you would like a copy of this
code I'll post this in the comment
section down below and well yeah that's
how to generate some some random numbers
in
C++ hey everybody in this topic we're
going to create a random event generator
using random numbers and a switch this
might be useful maybe if you're writing
a game you need some random event to
occur like random monsters show up or
the weather changes anything like that
we'll be working with random numbers you
may need to include this header file
include C time cuz we need access to the
time function to work with random
numbers will need to generate a seed s
Rand function pass in time pass in
zero this function will use the current
time as a seed to Generate random
numbers we'll create a local variable to
store our random number int Rand num
equals use the Rand
function
modulus then what's the range of numbers
you would like I would like the numbers
1 through five
but this will give us 0 through four so
I'm going to add one to the
end my integer random num will be a
random number between 1 and five I'm
going to create a switch to examine this
random number against many matching
cases so we have case
one through
five if the random number is one what
would you like to do exactly so in this
program I think we're going to give away
prizes like it's a random prize
generator depending on the random number
we'll give a participant a random
prize standard output you win how about
a bumper sticker a bumper
sticker that will be the lowest tier
prize then we should probably add a
break to break out of the
switch okay let's think of some others
and I should probably break after
these prize two will be a
t-shirt prize three how about a free
lunch prize
four maybe a gift
card case
five concert tickets that sounds good so
when I run this program we'll generate a
random number between 1 and 5 depending
on what that number is we'll execute the
code found within one of these
cases let's see what I won I won a free
lunch if I try this again there's a good
chance it'll be a different prize this
time I won a bumper
sticker I want a bumper sticker again
come on I want those concert tickets
I'll take a a gift card that's not bad
now if you don't add these break
statements you'll just fall through the
switch you want a gift card you want
concert
tickets so if you only want somebody to
win one prize you'll want to exit out of
the switch by including this break
statement so yeah everybody I thought
that might be an interesting program you
can generate some random event maybe
it's for a game or something I thought
maybe a random prize giveaway would kind
of be interesting this program is more
or less for practice your assignment is
to write a switch with some random
events then post it in the comment
section down below and well yeah that's
a random event generator using
C++ all right welcome back everybody in
this video we're going to create a
simple number guessing game Let's
declare our variables int num our number
will be randomly generated int guess
this variable will hold the current
player gu int tries how many tries is it
going to take for the user to guess the
correct number we'll be using the srand
function to generate some random
numbers pass in time pass in null we
will assign our variable num a random
number between 1 and 100 Rand
function modulus
100 then add
one this function will give us a random
number between 1 in 100 start with a num
just for some decorations I'm going to
create a title for this
game number guessing
game then add a new
line I'll place all of this code within
a do while loop
do
while our guess does not equal num we
will have the user type in another guess
we'll create a prompt standard
output enter a guess
between 1 through
100 standard
input guess once the user types in guess
we will increment our tries variable by
one to keep track of the score
now we'll have to examine the guess
versus the
number
if guess is greater than
num let's
display too
high I'll add a new
line else
if gas is less than num
then we'll
display to
low
else if the guess is not above the
number and the guess is not below the
number the guess must be equal to the
number standard
output
correct we'll display the number of
tries number of tries
we'll display our tries
variable I'll add a new
line and I'll just add a line of text
for decoration at the bottom once we
exit the
game that should be everything let's run
this number guessing game I'll guess
something right in the middle 50 too low
okay so the number is between 50 and 100
I'll guess right in the middle of that
range
75 too high something between 50 and 75
perhaps
62 that's still too high
56 too high 53 to
low
54
55 all right the correct guess was 55 it
took me seven tries I don't really think
that's too good but it works okay
everybody that is a simple number
guessing game involving the use of do
while loops and generating random
numbers if you would like a copy of this
code I'll post this in the comment
section down below if you're enjoying
the series please let me know by
Smashing that like button leave a random
comment down below and subscribe if
you'd like to become a fellow
bro well well well everybody we have a
pretty important lesson today today
we're going to talk about functions a
function is a block of reusable code if
you ever think that you're going to use
some section of code more than once you
might as well stick it within a function
here's an example I'll create a function
to sing Happy Birthday currently our
program is within the main function to
begin the program we call the main
function before the main function we can
create a new function for the time being
we're going to type
void then a unique function name the
function name should be descriptive of
what it does if I'm going to sing Happy
Birthday let's name this function the
happy birthday function then add a set
of parenthesis then a set of curly
braces you can see that this is almost
identical to our main function except
with the main function we have a return
type and return zero what would we like
to do when we invoke this function let's
sing some of the lyrics to Happy
Birthday standard
output
happy birthday to you add a new line
I'll repeat this a couple times
happy birthday dear you happy birthday
to you to invoke this function all we
have to do is within the main function
type the function name followed by a set
of parentheses this will call or
otherwise known as invoke the function I
like to think of the parentheses as a
pair of telephones that are talking to
each other to use a function you have to
call the function call it up on the
phone so when I run this code we have
the lyrics to Happy Birthday this
function is reusable I can call this
function as many times as I want I'll
call this function two additional times
just to separate these lyrics I'm going
to add an additional new line
character okay we now should have three
verses of happy birthday 1 2 3 that's
because I called the function well three
times a function is just a block of
reusable code now what a lot of people
do is that they'll declare and Define
their functions after after the main
function because it's more readable to
many people but there's one issue with
this happy birthday was not declared in
this
scope our programs are read from the top
down since we're invoking the happy
birthday function before we even know
what it is well the compiler doesn't
recognize it a solution to this is that
before the main function you can declare
functions but Define them later let's
declare happy birthday before the main
function then make sure you add a void
or a return type so void happy birthday
we can now use this function even though
it's after the main
function a lot of people like to Define
their functions after the main function
it's another way in which you can write
it just be sure to at least declare them
before the main function now check this
out what if we have a
variable standard string name assign
this whatever your name
is I'm going to use this name that's
declared in the main function and use it
within the happy birthday
function let's replace you with the
user's name happy birthday to name I'll
add a new
line then I'll copy
this paste
it and let's change this line as well
all right now when I run this here's the
issue name was not declared in the scope
think of each function as a house the
main function is your house functions
outside of the main function would be
your neighbors their house functions
can't see what's going on inside of
other functions you can't see what's
going on inside of your neighbor's house
you're only familiar with what's going
on inside of your own house in order for
the happy birthday function to use the
main function's name variable it needs
to be made aware of it to do that when
you invoke a neighboring function you
can pass that variable or some other
value as an argument So within the
parentheses when you invoke that
function place your values or variables
I would like to make my happy birthday
function aware of this name variable
within the main function when you send
some data over to a function that data
is also known as an argument however the
receiving function needs a matching set
of what are called parameters if this
function is going to receive this data
this name you need a matching parameter
to set up a parameter you first list the
data type we will receive a
standard string then we can list a
parameter name let's say name now this
happy birthday function can use this
name variable within the main function
if you have a function declaration at
the top of your program you'll have to
add that parameter there as well so
happy birthday standard
string and we can run this happy
birthday to whatever your name is
functions aren't aware of what's going
on inside of other functions but you can
make them aware of any local variables
or values by passing them as an argument
but you'll need a matching set of
parameters the name or otherwise unique
identifier of your parameter doesn't
necessarily need to have the same name
so to say you can name it something else
instead of naming our parameter name
let's say birthday boy or birthday
girl happy birthday to birthday
boy and that should work the same so you
can rename parameters but let's revert
that back now let's pass an age int age
equals make up some age I would like to
send my age over to the Happy Birthday
function so I will pass that as an
additional argument separate each
argument with a comma we'll send our
name as well as age now we need a
matching set of parameters right now the
happy birthday function is only equipped
to receive a name so we list the data
type int age and if you have a function
declaration change that there as
well then I'll add one more
line you are age
years
old then this should work okay happy
birthday to whatever your name is you
are whatever your age is years old so
that's a function everybody it's a block
of reusable code if you think you're
going to perform some code more than
once you can stick it within a function
whenever you need it you just simply
call it if you need to make your
function aware of any variables you can
send them as arguments to that function
but you'll need a matching set of
parameters in the function definition
and the Declaration so yeah those are
functions everybody your assignment is
to create a unique function and post it
in the comment section and well yeah
those are functions in
C++ all right everybody we are on the
return keyword the return keyword will
return a value back to the spot where
you called the encompassing function the
return keyword is commonly found at the
end of a function much like the main
function when we invoke a function we
can return some value back here's an
example I'll create a function that will
calculate the area of a square but we'll
need to pass in a length the length of
one side this will be double length
assign some value 5.0 is good then we'll
need to declare and Define a function at
the top of my program I'll add a
function declaration for the time being
we'll write void but that will change
soon void I'll name this function Square
we will square a length list any
parameters we will accept a double value
which we will name length then I'll need
a function definition I'll add that
after the main function void
Square I'm going to create a temporary
variable named result it will be of the
double data type we will take length
time length to calculate the
area then I will use that return keyword
return what are we returning we're
returning our result if we're returning
a value we need to change this keyword
void to match the DAT type of what we're
returning we're returning a double so I
will change void to double and then make
sure you change that within the function
declaration as well double square you
could do this in one line of code you
don't necessarily need to we could
simply just return length time length
that is also valid that's probably how I
would write it we now have this function
that will calculate the area of a square
once we pass in a length I'm going to
create a new variable called area it
will be of the double data type and I
will set this equal to then let's invoke
the square
function pass in our length variable as
an argument at this point of the program
area should be assigned a value let's
display it standard
output area I'll add my area
variable then add cm squared then new
line the area of our square is 25 cm
squar and I could change this to a
different number like six the area is
now 36 cm squared let's create another
function this function will find the
volume of a cube if we know the length
of a side we'll return a value of the
double data type but I will name this
Cube we will still accept the length of
the double data type
let's copy this paste it change Square
to
cube return length time length time
length double volume equals we'll invoke
our Cube function pass in our
length then I will display whatever the
volume
is volume
my volume variable cm
cubed if the side of a square is 6 cm
the area would be 36 if it was a cube
the volume would be 216 CM if you need
to return a value back to the spot in
which you invoked a function be sure to
list the data type of what you're
returning let's try another example
involving strings I'll create a function
that will add a user's first name their
last name and create a new string called
full name let's declare our variables
standard
string
first name equals add your first
name standard string last name
equals add your last name then I'll
create a function to concatenate two
strings together we're returning a
string I will list the data type as
standard string
I'll name this function concat
strings we will have two arguments two
standard strings standard string I'll
name the first string string
one standard string string I misspelled
string string two so we have our
function declaration now we just need to
Define it I'm going to
return string one plus I'll add a space
between the first name and the last
name plus string two I'll create a third
variable standard string full name
equals I will invoke my concat strings
function then I need to pass in two
strings as arguments I'll pass in my
first
name and my last name then let's display
the full name stand
output
hello the users's full
name Hello Bro Code or whatever your
first and last name is so yeah everybody
that is the return keyword wherever you
invoke a function you can return a value
back to that spot in which you invoked
that function if you're returning a
value just be sure that you change the
return type of that function to match
the data type of the value being
returned in this example I returned a
string a standard string so the return
type of this function would be a
standard string so that's the return
keyword everybody your assignment is in
the comment section to post a function
that returns some value so yeah that is
the return keyword in
C++ hey guys in this topic I'm going to
explain overloaded functions in C++ and
actually with many other programming
languages you can have different
versions of the same function here's
what I mean I have a function to bake a
pizza because well I like pizza Bake
Pizza this function will have no
parameters all I'm going to do within
this function is display the words here
is your
pizza then I'll add a new
line uh then I should probably add a
declaration at the
top void bake pizza then to invoke this
function I would type the function
name here is your pizza this time I
would like to bake a pizza that has
toppings right now we just have a plain
pizza with no toppings and that's kind
of lame I'm going to create an
additional version of this baked pizza
method but it's going to have different
parameters void bake
pizza we will accept a string stand
standard string I'll name this string
topping one we'll accept one topping as
an
argument standard output here is your
I'll add my topping here topping
one pizza then be sure to add your
function declaration
too bake pizza then this time we are
accepting a string it is valid for
functions to share the same name but you
need a different set of parameters a
function's name plus its parameters is
known as a function signature I can bake
a pizza that has no toppings here is
your pizza or I could pass in a topping
like
pepperoni here is your pepperoni pizza
let's create an additional function that
accepts two
toppings so we have topping one topping
two here is your top toing
one
and Topping
two
pizza then add your function
declaration topping one topping two now
I can bake a pizza that has two toppings
I would like pepperoni and
mushrooms here is your pepperoni and
mushroom pizza so yeah everybody those
are overloaded functions functions can
share the same name but you need a
different set of parameters a function's
name plus its parameters is known as a
function's signature and each function
signature needs to be unique kind of
like an ID so yeah those are overloaded
functions if you would like a copy of
this code I'll post this in the comment
section down below and well yeah those
are overloaded functions in C++
okay everybody we got to discuss
variable scope I'll explain local
variables and Global variables local
variables are declared inside of a
function or block of curly braces such
as within the main function or inside of
another function Global variables are
declared outside of all functions you
tend to see them at the top of your
program there's some major differences
between the two let's begin with local
variables suppose I have some number int
my num my num equals 1 if I need to
display my num I can use standard output
my num and of course this will display
my num which is one now what if I have a
function to display my num void print
num let's move this line of code to our
print num
function I'll need to add a function
declaration to the top of my
program then we will invoke this
function print num
okay this isn't going to work and here's
why my num was not declared in this
scope functions can't see inside of
other functions my function print num
has no idea what this my num variable is
my num is a local variable to the main
function that's why we pass arguments to
functions we'll make the function aware
of this value but you'll need a matching
set of parameters int my
num then add that to the function
declaration in
my
num and this would work that displays
the number one but let's get rid of
these
parameters it is legal to reuse the same
variable name as long as it's within a
different scope within the print num
function I'll also have a my num
variable that has the same name but I'll
give this a different
value when printing my num it prints two
we have two versions of the same
variable and this is fine because
they're within different scopes now a
global variable is declared outside of
all functions you see these at the top
of your program I will declare int my
num equals 3 I'm going to delete these
two local
variables if I was to invoke the print
num function and print my num well then
that number is
three This Global variable is also
available within the main function so I
will print my num here as well within
the main function
so we have three and three it's best to
avoid Global variables if you can
because it pollutes the global namespace
also variables declared within a
function are much more secure because
like I said functions can't see inside
of other functions if we had both local
and Global
variables my num within the main
function will be one within the print
num function it will be two if I was to
display my num for both of these I'm
going to add a new line to each of
new
line and new
line a function will use any local
variables first before resorting to any
Global variables that's why our print
num function prints 2 and the main
function prints one if you'd rather use
the global version you can use the scope
resolution operator so precede your
variable name with two colons that is
the scope resolution operator I'll do
that here as well in place of using the
local version of myum we will use the
global
version and we will print three we're
using the global version of my num
instead of the local version so yeah
that's variable scope local variables
are declared inside of a function or
anytime you see a set of curly braces a
variable declared inside a set of curly
braces is hidden to the outside world a
global variable is declared outside of
all functions and is accessible to all
functions within the program like I said
you should try and avoid using Global
variables if you can because it pollutes
the global namespace and these variables
are less secure so yeah that's variable
scope hey if you're enjoying this series
let me know by Smashing that like button
leave a random comment down below and
subscribe if you'd like to become a
fellow
bro hey guys in this topic we're going
to create a banking program for practice
we'll be able to deposit money withdraw
money and and show a balance this is
more or less just for practice let's
begin by creating our
functions void show
balance there will be one parameter
double balance whatever our bank account
balance is will show
it the return type is double
deposit no
parameters double withdraw and there
will be one parameter double
balance let's fill in a few things
within the main
function double balance and I will go
ahead and set this to zero as well as
int choice I will set that to zero as
well we'll use a switch to determine if
the user wants to show their balance
make a deposit a withdrawal or exit
let's display some output some
prompts standard output enter your
choice and I'm just going to add some
text decorations because I think that'll
be cool maybe a bunch of as
risks and one
more okay we have option one
one show
balance two will be deposit money
three is withdraw
money four will be
exit then we'll accept some user input
standard input
choice now we're going to create a
switch we're examining the user's choice
switch we're examining our choice
against many matching cases we have case
one case
two
3
4 then a default
case Okay case one the user wants to
show their balance will'll invoke the
show balance function but we need to
pass in our balance
balance and then we are going to
break case two the user wants to deposit
money so we're going to take our
balance equals
balance plus our deposit
function so deposit will return a double
right here so we're going to add that to
our balance once we verify it actually
we can shorten this too balance plus
equals whatever value is returned with
the deposit
function then we are going to
break case three withdraw
money balance minus
equals the withdraw function pass in our
balance we're withdrawing money from our
balance once we verify
it then we're going to
break we'll exit with case 4 I'll
display some output standard
output thanks for
visiting then I'm going to
break K default case standard
output
invalid
Choice okay now we're going to place all
of this code within a do while
loop do all of this while some condition
is true so let's take all of this code
cut
it put it within that do while loop let
me just format this a little
bit the condition will be while Choice
does not equal four four is what we used
to exit we'll need to add some function
definitions but I'm going to fill these
in later
we'll need to return something so let's
return zero for the time being for two
of these functions at least return zero
okay let's run and compile this just to
test our do while
loop okay enter your choice uh one show
balance that doesn't show our balance
yet but it will deposit money withdraw
now we should be able to exit by
pressing
four thanks for visiting okay so we know
that the do while loop is working
let's fill in our functions let's begin
with show
balance now with the show balance
function we're receiving our balance as
an
argument so I'm going to display
standard
output
your balance is dollar sign or some
other currency if you
choose I'll display our balance then add
a new line
so let's say we have
$123 in our
account I'm going to show my
balance $123 even but I would like to
display cents I'll need two decimal
places after the
decimal so there's one thing we can
include we'll include this header file
include IO man IP there's a function in
here to set some precision for floating
Point
numbers I'm going to make this change
after the dollar
sign standard set
Precision pass in two for two decimal
places then
add standard
fixed this will display our balance up
to two decimal places after the decimal
point so let's try that again
okay show balance
$123
and0 if I were to change this to
123.0 one we should display two decimal
places yep $123
And1 okay that is the show balance
function let's work on the deposit
function okay now we're within the
deposit function I'm going to create a
local variable named amount set this
equal to
zero we'll ask the user how much they
would like to deposit standard
output enter amount to be
deposited standard
input our
amount so I'm going to set balance back
to
zero then let's test
it show balance one your balance is $0
and0 I would like to make a deposit uh
$420
69 okay now I would like to show my
balance after we make a
deposit so within case two after making
a deposit let's show our balance pass in
the balance variable H let's do so after
a withdrawal
too okay let's try that
again show balance $0 0 make a deposit
$420
69 your balance is $0 cents so what
we're going to do is return our amount
at the end of this function return
amount
$420
69 all right we have our
balance the user is able to enter in
negative money enter amount to be
deposited 1,000 your balance is now
$1,000 we need to prevent somebody from
making a negative
deposit so before we return our amount
let's use an if
statement if amount is greater than zero
then we will return the
amount
else standard
output that's
not a valid
amount then let's return zero okay let's
try that
again deposit money negative
$1,000 that's not a valid amount your
balance is
0 I'm just going to add a new line like
right here then let's make a legitimate
deposit deposit money I will deposit
$1,000 And1 your balance is $11,000 And1
okay that is the deposit function that
is
complete then we have the withdraw
function we'll create a local variable
named amount of the double data type
we'll create a prompt standard
output enter amount to be
withdrawn standard
input
amount and at the end of this program we
will return
amount okay let's test it okay I need to
deposit some money first I will deposit
$1,000 and 1
C then let's withdraw money I will
withdraw $100 and 1ent my new balance is
$900 but we can overdraw our account
still so I'm going to withdraw a million
doll and 1
cent our balance shouldn't be negative
so let's prevent our user from
overdrafting their account within our
withdraw function let's add an if
statement if amount is greater than our
balance will
display
insufficient
funds then we will return
zero okay I'm going to withdraw $1
million and one
cent insufficient funds your balance is
zero okay now what if the user would
like to deposit negative money withdraw
money negative
1,000 your balance is
$1,000 we'll need to make sure that the
amount is a legitimate amount I'll add
an L if statement if
amount is less than
zero stand standard
output that's not a valid
amount now else we will return the
amount to be
withdrawn then within the lse if
statement we'll need to return zero
there okay let's withdraw money enter
amount to be withdrawn
$1,000 that's not a valid amount that's
good let's withdraw
again I would like to withdraw
$100 in sufficient funds my balance is
zero let's deposit some money
$99.99 our balance is $99 99 let's
withdraw again let's try and withdraw
$100 nope we can't let's withdraw again
$999.99 your balance is zero that's good
then let's exit
press for to exit thanks for visiting
okay so these functions are
done there's just one more thing we
should
add if I type in some characters like
the word Pizza well this will break our
program we'll want to clear the input
buffer so after our choice let's add
these two
lines
standard input. clear
function so I haven't talked about this
function this function will reset any
airor Flags when the standard input
fails to interpret the input then follow
this with f
flush this is a function pass in
standard input this will clear the input
buffer basically speaking once we hit
enter we have a new line character
within our input buffer so we just need
to flush that and get rid of it that
should prevent our program from going
crazy so let's type in some characters
invalid Choice cool then I would like to
exit all right everybody that is a
banking program for some practice if you
would like a copy of this code I'll post
this in the comment section down below
and well yeah that's a banking practice
program in
C++ all right everybody in this video
we're going to create a game of rock
paper scissors let's create our function
declarations first Char get user
choice Char in this case would be the
return type we'll be returning a
character Char get
computer
Choice void there is no return type show
Choice there will be one parameter Char
Choice then the last function is void
choose winner there will be two
parameters Char player that's us Char
computer the computer's choice will be
determined randomly using a random
number generator let's define these
functions let's copy all of these after
the main function I will paste them then
add a set of curly braces after
each currently if I were to run this
program we do have some warning because
with these two functions get user choice
and get computer choice we're not
returning anything even though we stated
that we're returning a character just
for the time being I'm going to return
zero just so that those warnings go away
but we'll correct these momentarily so
we shouldn't have those warnings within
the main function we will declare two
characters one for player Char player
that's us Char computer that's the
opponent we will take our player then
assign this a value of whatever is
returned from the get user Choice
function then we need to fill in this
function within the get user Choice
function I will create a local variable
of player as well I'll create a message
to begin our game standard
output rock
paper
scissors game I'll add a new
line uh this part isn't necessary but
I'm just going to add a bunch of
asterisks
afterward just because I think it would
look cool underneath our title let's
list our choices standard
output the character
R for
rock new
line let's copy this
P for
paper s
for
scissors standard input
player I'm just going to test that this
works standard
output
Player rock paper scissors game R for
rock P for paper s for scissors I'll
pick r that would give us the character
R okay so we know that that
works I'm going to place some of this
code within a do while loop because the
user might not type in RP or
S so
do while
I'm going to stick my code within the do
while
loop I'm just going to add one more line
of
output choose one of the
following all right we'll continue this
while loop as long as our player does
not equal the character r
and
player does not equal the character
p and player does not equal the
character s then at the end of this
function we will return
player we can't escape this while loop
until we pick either r p or S that's how
this condition works Let's test
it rock paper SC game choose one of the
following R for rock P for paper s for
scissors uh I will pick W for
womo choose one of the following r p or
S uh I like the letter X nope can't pick
that uh let's go with s for scissors
okay s is a valid Choice okay that is
the get user Choice function that is
complete so I'm going to close out of
this function
after we assign our player variable
let's display the user's Choice standard
output your choice colon
space then we will invoke the show
Choice function show Choice then there
is one parameter we have to pass in a
choice as an argument we will pass in
our player that's a character within the
show Choice function I'm going to create
a switch
switch we're examining some value
against matching cases we'll examine our
choice our choice argument that we
receive if our choice matches the case r
what would we like to do I'm going to
display some output standard
output just rock then I'll add a new
line make sure to break
then
case P for
paper
standard
output paper I'll add a new
line then
break case s for
scissors standard
output scissors new line
then
break let's close out of this function
then test
it okay I'll type R for rock your choice
Rock P for paper your choice
paper s for scissors your choice
scissors okay the show Choice function
is done now we need to get the computer
Choice computer
equals get computer
Choice then we'll need to fill in this
function get computer choice right
here we'll need to generate a random
seed s
Rand pass in the time function then type
zero or null you may need to include
this header file at the top of your
program just in case this doesn't work
include C
time we'll generate a random number
between 1 and three and num equals Grand
function modulus 3 + 1 we'll examine
this number against matching
cases switch we're examining our num
the first case will be the number one if
our random number is one let's return
the character
R since we're returning a value we don't
necessarily need to add that break
statement we're already breaking when we
return so we can Emmit
this case
2 return the
character P for
paper case three
return s for scissors okay we can close
out of the get computer Choice function
that's all done back within the main
function let's display the computer's
Choice standard
output computer's
Choice we'll invoke the show Choice
function but pass in our
computer let's run it to test it I'll
pick R for rock your choice Rock the
computer's choice is paper let's try it
like two more
times okay we chose paper the computer
chose
Rock let's pick s for scissors your
choice scissors the the computer's
choice is also scissors okay so the
computer is picking a random Choice
that's good now we'll have to decide who
won at the end of our program we will
invoke the choose winner function pass
in our player as well as the
computer then within the choose winner
function let's create another
switch we will examine our player
against matching
cases if our player chooses Rock the
character R I think the best way to do
this would be to use if statements
within each
case if the player chooses Rock and if
the
computer chooses R for rock that means
there's a
tie I'll display that standard
output it's a
tie then I'll add a new
line else
if the
computer chooses paper that means we
lose standard
output you
[Music]
lose else well there's only one option
left Scissors because if the computer
didn't choose rock or paper that means
they pick scissors rock beats scissors
so let's display that the user
one you
win oh then be sure to to add a break at
the end to break out of the
switch this is the case if the player
chooses Rock Let's copy all of this
code paste it and let's move this over
now if the user chooses paper we have
some different results paper BS Rock
will change this line of output to
be you win if the user chooses paper and
the computer chooses paper that means
means it's a
tie it's a
tie if we choose paper and the computer
chooses scissors that means we lose you
lose one more
case if the player picks scissors and
the computer picks rock you
lose scissors beads
paper you win else
scissors ties with
scissors it's a tie and that is
everything so let's close this function
and run this
program okay I'll pick R for rock we
picked Rock the computer picked scissors
you
win P for
paper the computer also picked paper
it's a tie
I'll pick
scissors I picked scissors the computer
picked rock you lose well all right then
everybody that is a game of rock paper
scissors if you would like a copy of
this code I'll post this in the comment
section down below and well yeah that's
a game of rock paper scissors in
C++ we have a big topic today I need to
discuss arrays an array is a data
structure that can hold multiple values
values are accessed by an index number
think of an array as kind of like a
variable that holds multiple values it's
a little more complicated than that but
that's a good way of thinking about them
perhaps we have the name of a car this
will be a standard string I will name
this car assign this a value of whatever
car that you like one car that I like is
a
Corvette then I will display whatever
our car is
standard
output
car so of course this car is a Corvette
we can transform this variable into an
array by making the following changes
after the variable name add a set of
square
brackets then enclose your values with a
set of curly
braces there we now have an array my
variable car is now an array now this
variable can hold multiple values
multiple cars kind of like it's a
parking garage separate each value with
a comma this time I'll add a
Mustang then a Camry now take a look at
this I will display
car now what the heck is this so this is
a memory address of where our array is
located like 123 Fake Street if I need
one of these elements one of these
values that's found within the array in
order to access it I have to do so by an
index number
after the array name I will add a set of
square brackets then an index number the
first element in an array has an index
of zero because computers always start
with zero and we have our Corvette it's
kind of like a parking spot number
that's why I went with this example of
cars if I need the next element within
my array I would access element number
one then I should probably add a new
line just to separate these new line
we have our Corvette and our Mustang
then we have our third element which
would have an index of two so we have
our three elements our Corvette our
Mustang and our Camry you can reassign
values too I'm going to change the first
element within this array take the array
name select an index number I'll set
this equal to a Camaro a Chevy Camaro
now at parking spot number zero we have
our Camaro then our Mustang than our
Camry I'm going to rename car as cars
just so people know that it's plural
although it's not necessary one thing
with the Rays is that they can only
contain values of the same data type
like I'll try and stick a number within
here number
one so our compiler doesn't like it that
there's a number in here with all these
strings so arrays should all be of the
same data type now if you don't know
what you want to place within an array
you can simply declare an array then
assign values later I'm going to declare
an array of cars and then later assign
some
values cars at index one will have our
Mustang cars at index
2 will be our
Camry see we still have an error though
array size missing in cars you can
declare an array then assign values
later we need to set a size to this
array it's a static data structure if
I'm only going to place three cars
within this array I'll set the size to
be three So within the square brackets
you can set an array size and this would
work the same you can declare an array
be sure to set the size and then assign
values later let's try one last example
I'm going to create an array of prices
these will be of the double data type
prices add a set of square brackets I'll
go ahead and assign these values right
away so I don't need to declare a size
explicitly make up some prices $5
$7.50
$9.99 then
$15 I'll display these prices standard
output prices I'll list an index number
of what element I'm trying to access the
first would be zero then I'll add a new
line
let's copy this line of code and paste
it a couple more times we have prices at
index zero that is the first element
then one 2 and
three and here are the prices so yeah
that's an array think of it as a
variable that can hold multiple values
it's a little more complicated than that
it's a type of data structure but that's
a good way of thinking about them to
change a variable into an array after
the variable name add a set of square
brackets place your values within a set
of curly braces that's if you're
assigning values right away or otherwise
you can set a size and then assign
values later that's another option so
yeah those are arrays your assignment is
to post an array in the comment section
down below and well yeah those are
arrays in
C++ you guys ready all right let's talk
about the size of operator the size of
operator determines the size in bytes of
a variable data type class objects Etc
whatever you would like to find the size
of you stick within the parentheses of
the size of operator here's an example
let's create a
double double GPA our GPA will be a
solid 2.5 to determine the size in bytes
of my variable or a data type I will
just place within the set of parentheses
I'll display this standard output
size of operator I would like to return
the size of my GPA variable then I'll
just add a
string byes new
line let's take a look the size of my
GPA variable is 8 bytes that's the
maximum size allocated to my double
variable if I was to replace GPA with a
data type such as double well this would
be the same 8 bytes this will be helpful
in the future when we begin working with
the
so let's try a couple other variables
I'll create a string standard string
name assign some
name then I will find the size of the
string size of
name the size of a string is 32 bytes
because a string really just holds an
address to where some text is located
the address of where the string of text
is located is 32 bytes even if I were to
change the size of the string bro code
is is awesome well this size is still
going to be the same 32 bytes because a
string is a reference data type let's
try a couple other examples how about a
character Char
grade my grade will be an F I will find
the size of this character
grade the size of a character is one
bite let's try a Boolean Boolean student
is somebody a student true or or false
I'll Place student within the size of
operator a Boolean variable also takes
one bite of memory this time let's find
the size of an array in byes I'll create
an array of
characters Char grades this will be an
array I'll set this equal to some
grades a
b
c d then F I'll place my array within
the size of
operator the size of this array grades
is 5 bytes remember that characters take
up one bite of memory an array of five
characters would be well five bytes we
can use the size of operator to
calculate how many elements are within
an array if we have the total size of
our array we could divide this by the
size of one
element size of grades at index of zero
or otherwise we can find the data
type we'll divide the size of my array
grades divided by the size of a
character so I should have these many
elements five elements within my array
of grades if I were to add one more
grade like an e even though that's not a
typical grade well then the total
elements within that array would be six
elements that's a useful trick to
calculate the size of an array how many
elements are within that array one more
this will be a bonus question I'll
create an array of
strings I'll name this
students we'll enter in some student
names such as
SpongeBob
Patrick then
Squidward to calculate how many strings
are within this array how many students
we have we can find the size of my array
students divided by the size of a
string I have three elements within this
array of students then I could add one
more and this equation should calculate
that I'll add
Sandy size of students divided by the
size of a string would give me four
elements so yeah that's the size of
operator everybody it will return the
size in bytes of a a variable data type
class objects all sorts of things it
will be really helpful when working with
arrays because we can determine the size
of an array but we'll get some practice
with that in the future and well yeah
that's the size of operator in
C++ all right guys in this video I'm
going to show you how we can iterate
over the elements of an array suppose we
have an array of students these will be
strings standard
string I'll name this array
students set the equal to some student
names pick a
few
SpongeBob
Patrick then
Squidward suppose I would like to
display all these students normally to
do that I would type standard output my
array followed by an index number so the
first student would be SpongeBob which
has an index of zero and my first
student is SpongeBob if I need to
display all of the elements of this
array I would have to one by one access
each
element then I'll just add a new
line we have SpongeBob Patrick and
Squidward if I need to display all of
the elements of an array a better
approach would be to use a for
Loop I'm going to type for parentheses
curly braces we'll need an index in I
I'll set this equal to is Zer because
the first element in our array has an
index of zero I'll continue this as long
as I is less than the length of our
array currently it's
three then increment I by
One during each iteration I would like
to display each element standard
output students now instead of an index
number like 0 1 2 whatever I'm going to
use my counter variable I students at
index of I during the first iteration I
will be zero then 1 then two once we
reach three we'll stop I'll add a new
line this for Loop will print the
elements of my
array SpongeBob Patrick Squidward
there's one issue with this though what
if we add another student such as
Sandy well this for Loop will stop once
I reach is three if we make any
adjustments to this array we would have
to go into our code and make some
changes such as setting this four Loop
so that we discontinue when I reaches
four this would work but it's not the
best solution for our stopping condition
in place of just setting I to be less
than some number let's calculate how
many elements are within this array to
do that we can use the size of
operator I'll type size of my array this
will give me the total size in byes of
my array to calculate the number of
elements I can divide size of students
by the size of the data type string or
even an element this will Loop through
all of the elements of this array
SpongeBob Patrick Squidward Sandy if we
change the number of elements well then
there's no need to touch this for Loop
it will calculate the size automatically
see now we just have SpongeBob and
Patrick let's create one last example
I'll create an array of
grades Char
grades we have an
A
B
C D then
F if I need to iterate over this array
of characters I would find the size of
my array grades divided by the size of a
character the character data type during
each iteration I will display grades at
index of I our
counter and this will display all of the
elements of this array so yeah that's
how to iterate over an array using a for
Loop in the next topic I will explain
the for each Loop which has different
syntax and well yeah that's how to
iterate over an array using a for Loop
in
C++ all right guys the for each Loop the
for each Loop is a loop that that eases
the traversal over an iterable data set
an array is an example of an iterable
data set suppose we're using a standard
for Loop and I have this array of
strings named students we have SpongeBob
Patrick and Squidward using a standard
for loop I would need three statements
an index a condition then we could
increment or decrement our
Index this does work but there is
another way of writing this using a for
each Loop there's less syntax than a
typical four Loop but it's less flexible
using a for Loop we can go forwards
backwards or even skip iterations of
something we're iterating over using a 4
each Loop we start at the beginning and
go to the end there's less flexibility
so let's change this to a 4 each
Loop first We'll add the data type of
what we're iterating over we're
iterating over
strings then we'll need a name for the
current element that we're on we have an
array of students let's name the current
element student colon then our iterable
data set which would be our
array string student colon students
during each iteration let's display
whatever the current element is which I
named
student then I'll add a new
line and there we go we have our three
students then you could change the
amount of students if you would like
let's add
Sandy now we have SpongeBob Patrick
Squidward Sandy let's try a different
example let's work with grades this time
these will be of the int data type int
grades equals make up some
grades
65 72 81 93 good enough the data type of
what we're iterating over is not a
string this time it is an INT integers
let's name each element simply grade
colon the name of my iterable data set
which would be my array grades for every
grade in grades let's display each
grade and here are the grades 65 72 81
93 so that's a 4 each loop it's a loop
that eases the traversal over an
iterable data set there's less syntax
invol D in a 4 each Loop but it's less
flexible if you just need to display the
elements of an array a 4 each Loop would
work perfect so yeah that's a 4 each
Loop everybody your assignment is to
post a 4 each Loop in the comment
section down below and well yeah that's
the 4 each Loop in
C++ all right everybody so in this video
I'm going to show you how we can pass an
array to a function suppose we have an
array of prices these will be of the
double data type double prices straight
brackets equals just make up some prices
$49.99
$155
$75
$9.99 good enough we'll create a
function to find the sum of these prices
and print a total let's say double total
equals then I'll invoke a get total
function which we still need to declare
and Define so let's do that now we'll
return a double double get
total let's list the parameters we need
to accept an array of doubles
double prices then add a set of square
brackets for the parameter now when we
pass an array to a function you only
need to pass the array name you don't
need a set of square brackets then we'll
need a function declaration let's do
that before the main
function then at the end of my program I
will display the
total standard
output pick a currency uh let's pick a
dollar
sign then I will display the total
within the get total function I'm going
to declare a separate local instance of
a total
variable remember that variables can
have the same name as long as they're
within a different function so we have
double total I'm going to iterate over
my array using a for
Loop normally what we would do is say in
I equals 0 I would continue this as long
as I is less than then at this point we
would calculate the size of the array
but technically this isn't going to work
and I'll demonstrate why we have the
size of our array prices divided by the
size of either the data type or one of
the elements typically I like to use one
of the elements prices at index zero
then I will increment our counter by one
during each iteration within our for
Loop let's assign total equal to Total
plus prices at index of I or we could
shorten this to Total plus equals prices
at index of I at the end of our program
we will return whatever the total is now
this isn't going to work the way it's
written now here's why when we pass an
array to a function it KS into what's
known as a pointer which we haven't
discussed yet but we will in future
topics within this function we're not
working with an array anymore we're
working with a pointer that points to
the address of where the array begins
this function has no idea how big this
array is anymore we can't calculate how
many elements are within this array what
we could do is that when we invoke this
function we can pass in the array as
well as the size of the array since this
function no longer knows how big the
array is we can explicitly let theun
function know what the size is so let's
calculate what the size is int size
equals we can just copy all this
code paste
it now when we invoke this function I'm
going to pass the size as a second
argument then we'll need a matching set
of
parameters in
size be sure to add that with your
function declaration too if you have
one I would like to continue this for
loop as long as I is less than size now
this should work let's verify that yep
and our total is
$150 3 in conclusion when you pass an
array to a function you only have to
pass the array name you don't need a set
of square brackets when you do so
however when a function receives an
array it decays into a pointer and the
function no longer knows what the size
of the array is so we could pass that as
an additional argument to let the
function know what the size is which we
could then use to you know iterate over
the array so that's how to pass an array
to a function your assignment is to post
a function that accepts an array as an
argument in the comment section down
below and well yeah that's how to pass
an array to a function in
C++ hey welcome back so in this video
I'm going to show you how we can search
an array for an element let's create an
array of numbers something simple int
numbers this will be an array then
assign some numbers I'll just assign the
numbers 1 through 10 because I'm basic
like
that there 1 through 10 we'll probably
need this later I'm going to calculate
the size of the array int size equals
size of my array numbers divided by the
size of one of the elements I'll just
pick the first element
we'll need to keep track of an index
like what index did we find something
that we're searching for INT index I'll
declare this variable but we don't need
to assign it as well as int my num my
num will be the number that we're
looking
for let's accept some user input we'll
create a prompt standard
output enter element to search for
I'll add a new line cuz I
can
standard
input my
num I'm going to create a function that
will search an array for us let's define
that function outside of the main
function this function will return an
integer that will be our index the
return type is in I'll name this
function search
array there's a couple par parameters
we'll have three parameters an array of
integers integer
array the size of the array int size
then some element that we're searching
for INT element then we should probably
add a function declaration at the
top that's good this function will
return an integer the index of the
element that we're searching for we will
take our index variable set this equal
to then I'm going to invoke the search
array function that we just declared but
we need three matching Arguments for the
three parameters that we have set up an
array a size and an element we'll pass
in our array
numbers the size of the array that we
already
calculated and the element that we're
searching for we're searching for my
num within the search array function we
will iterate from the beginning of the
array to the end and see if there's any
matches we can do that with the for
Loop we'll begin at zero in I equals z
that's our
index I will continue this as long as I
is less than the size of the array that
we're passing in as an argument then
increment our index by
one this would be technically a linear
search we'll start at the beginning and
check every value until we reach the end
so let's check using an if statement
within the for Loop if our array we did
name this array numbers but remember
that you can rename parameters numbers
is technically our array if our array
that we
receive at index of I that's our counter
is equal to the element that we're
searching
for we will return whatever the index is
I if we search through this entire array
and don't find that element that we're
searching for will
return1 in
programming1 serves as a sentinel value
if you see NE 1 that typically means
that something wasn't found well return
either I
or1 then assign it to this index
variable within the main function using
an if statement we'll check to see what
that value
is if our index does not equal -1 that
means the element that we're searching
for is somewhere within our
array let's display the index standard
output my
num is at
index whatever the index variable
is
else standard
output my num
is not in the
array okay let's see if this actually
works enter element to search for let's
search for one one is at index zero
remember that computers always start
with zero enter an element to search for
let's search for 10 10 is at index 9
enter an element to search for
42069 42069
is not in the
array for additional practice let's
search through an array of strings such
as food we'll create an array of
strings I'll rename numbers as Foods
then think of some food that you
like
pizza
hamburger hot
dog in size equals the size of foods
divided by one of the elements of foods
let's rename my num as my food that's
the food that we're searching
for and that will be of the string data
type in place of CN when working with
strings let's use getline because the
user input may contain spaces
standard get
line standard
input my food
within the search array function that we
created we will pass our array Foods the
size can stay the same then pass in my
food that's what we're searching for
within the if else statements replace my
num with my
food then we'll need to change the data
types of this function we're accepting
an array of
strings replace int with string do that
with your element as
well then we need to change the function
declaration at the top of our
program okay we can now search through
an array of
strings enter element to search for
let's search for pizza pizza is at index
zero hamburger hamburger is at index
one hot
dog hot dog is at index 2 then let's
search for something that's not within
this
array what about sushi
Sushi is not in the array yeah everybody
that is how to search through an array
this would technically be a linear
search you begin at the first element of
an array check to see if the values are
equal if they're not equal you move to
the next element until you reach the end
and that's basically it if you would
like a copy of this code I'll post this
in the comment section down below and
well yeah that's how to search through
an array in
C++ hey everybody in this topic I'm
going to to show you how we can sort an
array first I'll explain the logic
behind it then we'll write a C++ program
to actually handle it we'll use a
standard bubble sort it's an easy
sorting algorithm to write although
there are more efficient sorting
algorithms we're still learning so let's
stick with a bubble sort so with a
bubble sort we begin at index zero the
beginning of our array we'll examine the
element directly to the right if the
element on the left is larger than the
element on the right we need to swap
these two elements I will take this
element move it within some temp storage
like a temporary variable take the
element on the right move it to the left
take whatever is within temp place it
within that opening again we take our
value examine the element to the right
if it's larger we swap
them then we would just repeat this
until we reach the end
so that would be one element we would
repeat this process with the rest of the
elements now for the next iteration one
is not greater than 9 so we leave it
alone then we check the next element 9
is greater than two we would swap these
two
values I'll speed up the footage
for
that is a quick demonstration of a
bubble sort so let's actually write this
in code
now okay let's create an array this will
be an array of
integers make up some numbers make sure
they're not in
order let's let's calculate the size of
the array and size
equals size of our array divided by the
size of one of the
elements at the end of our program we
will iterate over our array I'll use a
for each Loop in element in Array I will
display using standard output every
element then I think I'll separate each
with the space
okay and here's our array obviously
unsorted so let's change that I'll
create a sort function void
sort there will be two parameters an
integer
array int size let's add a function
declaration at the top of our
program before we print our array let's
invoke the sort function that we just
created pass in our array as well as the
size there we go okay so let's head to
our sort function what we'll need to do
is iterate over our array once for every
element that's within the array we'll
need the help of a temporary variable to
swap some values then we'll need nested
Loops for in I equals z we'll continue
this as long as I is less than the size
of our array minus one the reason that
the condition is size minus one is
because we don't need to compare the
last element to anything the larger
values will naturally gravitate towards
the end of the array increment I by one
then we'll need a nested for
Loop let's use index J because I is
already
taken now our condition is going to be
size - i - one once we place the larger
elements all the way to the right they
should already be in order we don't need
to sort any elements that are already
sorted then what we have to do is use an
if state statement to check to see if
the current element that we're on array
at index of J is greater than the
element on the right array at index of
J + 1 if the element on the left is
larger than the element on the right we
just have to swap those two values we'll
take temp which we declared up here
equals array at index of J array array
at index of J equals array at index of J
+ 1 then lastly array at index of J + 1
equals whatever is within Temp and that
should be it let's run
this yeah and our array is now sorted in
ascending order so if you need
descending order within this if
statement use less
than and now this array is in descending
order well okay then everybody that's
one way in which you can sort an array
we used what's known as a bubble sort
it's easy to write but it's not as
efficient as some other algorithms that
are out there this is a good one for
beginners if you would like a copy of
this code I'll post this in the comment
section down below and well yeah that's
how to sort an array using
C++ hey everybody in this topic I'm
going to explain the fill function The
Fill function fills a range of elements
with with a specified value there's
three arguments a beginning address of a
data structure an ending address then
some value suppose we have an array of
strings standard string I'll name this
array
Foods I'll give this a maximum size of
10 elements then I'll go ahead and fill
this array with the same food I'll fill
all 10 elements with the word
pizza so that's one 2 3 4 5 6 7 8 9 10
so these all have the same value now
this really isn't practical although it
does work just to demonstrate I'll
display the elements with the for each
loop we're displaying strings for every
food element in my array Foods I would
like to
display each food element then I'll add
a new line so we have 10 elements all
filled with pizza you know this does
work but it's not practical to
initialize all of these elements
manually what if we had an array of 100
elements I would have to type the word
Pizza 100 times there's a few Solutions
one of which would be the fill function
which would make this process a lot
easier I'm going to declare this array
but not fill it in quite yet we have an
array of 100 elements to store strings
I'm going to fill all 100 elements with
pizza so we type fill parentheses now we
need the beginning address of a data
structure well that's simply the array
name then an ending address so that
would be the second argument we would
type the array name plus the size of the
array so plus 100 in this case then some
value I'll fill this array with the word
Pizza 100
times there we
go all 100 elements have been filled
with pizza now if you do change the size
of this array let's say we have 150
elements you would have to go and change
that within the fill method too what I
would do in place of adding some number
to my array I will add a size variable
foods will be index of size and then we
can set some size actually better yet
let's make this a constant constant int
size then I'll set this to be
100 Foods plus size so again all 100
elements are filled with pizza now
here's a few exercises if I'm filling
the first half of this array with pizza
we have our beginning address then I
need to find the halfway point Foods
plus size / two I'll just go ahead and
put that within some parentheses for
clarity then if I were to run this the
first half of this array contains
pizza and the second half contains
nothing it's empty to fill the second
half of this array with hamburgers I
would invoke The Fill function
again we will begin where we left
off Foods plus size / two the ending
address would be Foods plus size we will
fill the second half of this array with
hamburgers there we are the first half
is all Pizza the second half is all
hamburgers here's a challenge round
we'll fill the first third of our array
with pizza the second third will be
hamburgers and the last third will be
hot dogs
but 100 doesn't divide by three evenly
just to make this simple I'll set our
array to be 99 elements we're filling
the first third of our array with pizza
size divided 3 hamburgers will begin at
Foods plus size ID 3 and end at size / 3
* 2 then we'll invoke The Fill function
one more time we'll continue where we
left
off and we will end at Foods plus size
and fill this with hot
dogs here we
go so we have pizza hamburgers then hot
dogs so yeah that is the fill function
we can fill a range of elements with a
specified value it's great if you have a
lot of elements to work with and you
don't manually want to type all the
values if you would like a copy of this
code I'll post this in the comment
section down below and well yeah that's
the The Fill function in
C++ hey welcome back everybody in this
video I'm going to explain one of a few
ways in which we can accept user input
and place it within an array there's no
one- siiz fits-all way to do it I'll
show you one way that's good for
beginners let's begin by creating an
array I'll create an array of strings
named
Foods we're not going to be assigning
values to this array quite yet that's
where the user input will come in if
we're not assigning values right away
when we initialize this array we'll have
to specify a size for the time being
let's say five something small now
arrays they're static data structures
while our program is running we can't
change the size of this array the max
size is stuck at five and that might be
a problem if we would like to enter in
more than five items we'll discuss
dynamic memory in a future video then
I'm going to calculate the size of this
array in size equals size of my array
Foods divide by the size of one of the
elements Foods at index of
zero let's create a for Loop to iterate
over the elements of this
array for in I equals 0 we'll continue
this as long as I is less than the size
of our array then increment I by One
let's create a
prompt standard
output enter a food would you like then
I'll display the number to show the user
what number we're
on I then I'm just going to add a colon
at the
end if we're working with strings we
should probably use the getline function
just because what the user enters may
contain spaces get line standard
input we'll place our input within our
array
Foods at the index of I whatever we're
currently on our counter at the end of
our program let's display a
message you like the following
food I'll use a for each Loop to iterate
over the elements of this array we list
the data
type a name for the current
element food in foods
let's display standard
output whatever the food is I'll add a
new
line and that should be good now take a
look at this enter a food you like we're
on number zero I'm going to add plus one
to I when we display our prompt the user
is not going to be sure why there's a
number zero but we know that's the
beginning index of an array so I'm just
going to change that here enter a food
you like we're on number one
pizza hamburger
hot dog
Ramen
Sushi and these are the five elements
you like the following food pizza
hamburger hot dog Ramen Sushi okay
that's pretty good so far suppose the
user only wants to enter in three
elements not all five we should add some
way to escape out of this for Loop based
on some user input I'm going to add this
line enter a food you like
or Q to quit
now check this out if the user types in
Q we would like to
exit if Foods at index of I is equal to
the string Q then I would like to break
out of this for Loop the user is done
entering an input but there's a problem
with
this enter a food you like or CU to quit
number one pizza
hamburger hot dog now I'm going to press
Q to
quit we don't have any more prompts to
enter in food we went to the results you
like the following food pizza hamburger
hot dog Q I'd rather not put the letter
Q in my Foods array I'm going to create
a temporary variable just to hold some
user input this will be of the string
data type standard string I'll name this
temp meaning temporary it's a a
temporary variable in place of directly
putting my user input into my Foods
array I'll place it temporarily within
my variable temp I'm going to check if
temp is equal to
Q else will take Foods at index of I set
the SQL to Temp that way we're not
directly assigning our user input to our
array until we check what it is if the
user types in Q to quit we don't want to
put that within our Foods array so let's
try this again it should be better enter
a food you like or C to
quit Pizza hamburger hot dog Q to
quit Okay Pizza hamburger hot dog well
the letter Q isn't here but when we
display what's within the array we have
these empty spaces we did not assign a
value to these if one of our elements is
empty I don't want to display it so we
can make this following change in place
of for each Loop let's use a standard
for Loop in I equals
0 now here's the condition we're used to
saying I is less than size right I'd
like to propose a change we'll write a
different condition I will check if the
current element is empty Foods at index
of I dot empty function then we'll add
the not logical operator we'll continue
our for loop as long as theur current
element is not empty then we'll add the
statement increment I by one we'll
display our array Foods at index of I
this for Loop shouldn't display any
elements that are
empty
Pizza
hamburger hot dog Q to quit yeah and we
only have three elements Pizza hamburger
hot dog one disadvantage of arrays is
that they have a limited size they're
static once we declare a size we can't
change it we're limmited to only storing
five foods you could declare a larger
size but you may be wasting memory if a
user doesn't want to type in all 10 so
in future topics we'll need to discuss
both dynamic memory and vectors which
should be coming up sometime in the
future so yeah that is one way out of
many ways to enter in user input into an
array if you would like a copy of this
code I'll post this in the comment
section down below and well yeah that's
how to enter user input into an array
using
C++ hey everybody in this topic I'm
going to explain multi-dimensional
arrays more specifically 2D arrays it's
an array made up of separate arrays
they're useful because they can
represent a grid or Matrix of data with
rows and columns here's an example I'll
create a two-dimensional array of cars
car names the data type will be string I
will name this array cars with arrays
they have one set of square brackets but
if you're creating a two-dimensional
array you need two sets of square
brackets the first set of square
brackets is for the number of rows let's
say three in this example the second set
of square brackets corresponds to the
number of columns if we have three rows
and four columns 3 * 4 is 12 so that
would give us 12 elements if you're
initializing your 2D array right away
you don't necessarily need to set a row
size but you do need a column size I'll
just set the amount of columns to be
three just something small okay so let's
fill in the first array this first row
will be cars manufactured by Ford I'll
add a
Mustang then a Ford
Escape then maybe a Ford
F150 okay this is our first array I'm
going to create a second array after the
first array I'll add comma what I like
to do I like to organize my 2D array
kind of like it's a grid so now we have
a second array this next array will be
cars manufactured by
Chevrolet I'll pick a
Corvette then an
equinox and a
Silverado let's add one last
array these will be cars manufactured by
Dodge
Challenger
Durango Ram
1500 all right now to finish this
two-dimensional array we will enclose
all of these inner arrays with another
set of curly braces then add a semicolon
to the end that is our two-dimensional
array you can see that there's rows and
columns in this example each row
corresponds to a
manufacturer so it's kind of like a grid
a matrix then if you were to access one
of these elements you need two indices
just to demonstrate let's display all of
them standard output
cars I need to select the row number
then the column number row zero column
zero let's see what C that
is I'm just going to add a space between
these
elements okay row zero column zero
that's my Mustang row 0 column 0 that's
Mustang let's print the next element
that would be row0 column
one that is my Ford Escape row zero
column 1 I'm just going to zoom out
there then we have row zero column
2 that's the Ford F-150 I'm going to
display a new line character now we are
on Row one so let's copy these
paste
them Row one column zero Row one column
1 Row one column
two so this next row is our cars
manufactured by Chevrolet we have our
Corvette our Equinox then our
Silverado then we will display row
two row two column zero row two column 1
row row two column
2 and these are the cars manufactured by
Dodge we have our Challenger Durango Ram
1500 so yeah you can see that a
two-dimensional array is kind of like a
grid made up of rows and columns now if
we need to iterate over a
two-dimensional array and display the
elements here's one way in which we can
do that we can use nested Loops but just
to make it easy I'm going to calculate
the amount of rows and columns that we
have let's begin with the rows if rows
equals size of my array
cars divided by the size of one of the
elements cars at index Zer is
good then to calculate the amount of
columns that we have we could do
something like this int columns equals
the size of cars at index of zero
divided by the size of one of the
elements so remember there's two indices
this time 0 Z is good in this example we
should have three rows as well as three
columns now let's create a for Loop to
iterate over the
rows in I equals z i will continue this
as long as I is less than the number of
rows that we have then increment I by
one I'm going to
display cars at index of I just for the
time being then for now I'm just going
to add a new line between
each so if I was to display cars at
index
I that should give us three memory
addresses one address for every inner
array this memory address is for the
first array then the second
array then the third
array what I need to do now to get the
elements within each array is to create
an inner loop
let's use an in four Loop to iterate
over each element within each
array int J because I is already taken
set this equal to zero we will continue
this for loop as long as J is less then
the number of columns that we have
increment J by
one now I'm going to
display cars and there's two
indices I
then
J I'm going to display a space between
each of
these okay now we have one long line of
text so once we escape the inner for
loop I would just like to print a new
line I'll add standard
output new line
character okay and here's our
two-dimensional array the first row are
for cars Manu factured by Ford then
Chevrolet then Dodge that's how to
iterate over a two-dimensional array you
have the outer loop that's in charge of
the rows the inner loop which is in
charge of the columns so that's a
two-dimensional array everybody it's
just an array where each element is its
own separate array you have two indices
the first for the rows the second for
the columns to access one of the
elements you have to specify the row
then the column that element is found so
those are two-dimensional arrays your
assignment is to post a two-dimensional
array in the comment section down below
and well yeah those are two dimensional
arrays in
C++ hey everybody in this video we're
going to create a quiz game using C++
let's begin by creating an array of
questions these will be of the string
data type I will name this array
questions and then let's think of some
questions really add any questions that
you want here's a few that come to mind
for
me what year was
C++
created okay that is the first question
I'll add an additional
string question
two who invented
C++ third
question what is
the
predecessor of
C++ and I couldn't think of a fourth
question so I'm going to ask is the
earth flat good enough with each
question there will be four
corresponding options I think a
two-dimensional array would be perfect
for this this will be a two-dimensional
array of strings named
options we'll need to set the number of
columns four columns is
good this first array will be for the
options for the first
question a will be
1969
B
1975 C 1985 1985 is the correct
answer d
1989 now we have our next array who
invented
C++ gido van
rossom he's the creator of python so
that's not the correct
answer
bearn
stro strip I'm sorry if I mispronounce
your name dude hopefully you're not
watching right now B is the correct
answer in this
case C
John
karmac
D Mark
Zuckerberg we're on question
three what is the predecessor of
C++ the correct answer is C that would
be option A
C+ C minus
minus or
b++ okay last
question is the earth
flat
yes no
sometimes what's
Earth all right then I just need to
surround all of these arrays with
another set of curly
braces and there is our two-dimensional
array named options to hold all of the
options for our questions we'll need to
create an answer key next this will be
an array of characters
answer key array
equals here are the correct
answers
C
B
A then
B
1985 bejn
strup C the language see that is and no
the Earth is not flat I looked it up on
Wikipedia just now let's calculate the
size of our questions how many questions
do we have
in size equals the size of our array
questions divided by the size of one of
the elements questions at
index0 we'll create a character to hold
our
guess int score to hold the
score now we'll need to iterate over our
questions for let me move down
here in I equals z we'll continue this
as long as I is less than the size of
our array the size of questions this
would effectively be the amount of
questions that we have then I'm going to
increment I by one we will iterate once
through all of the questions we
have standard
output let's access the string that's
within question questions at index
I I'll add a new
line just for some text decoration I'm
going to add a bunch of asterisks before
and after the
question so let's get rid of
this I think that'll look pretty
cool there we go then we'll need to
iterate over our 2D array
we'll use an in four Loop for that we'll
need a different index I is already
taken let's pick J in J equals z we'll
continue this as long as J is less than
now we'll need to calculate how many
elements are within each
array so we can do that with size
of our options array at index of I
divided by the size
of options and there's two indices
here I then zero then we will increment
J by
one we will display our options standard
output options there's two indices I
then J I'll add a new
line so if I were to run this this
should display all of the questions and
all of the
options yeah here we are what year was
C++ created who invented
C++ what is the predecessor of C++ is
the earth flat after all of the options
are laid out we will accept some user
input standard
input we will place the user's input
within guess then just in case the user
types in something that's lowercase like
a lowercase C we're looking for Capital
C so let's take the user's guess then
make it uppercase guess equals two upper
pass in
guess so that will capitalize the
character the user enters
in then let's check to see if the user's
guess is equal to the answer we'll need
to access the answer
key at index of I that's the current
numbered question if those two values
are the same we will display correct
I'll add a new
line then increment the user score score
Plus+ else the user's guess is not
correct standard
output
wrong then we will display the correct
answer standard
output answer colon space
we'll access the answer key at index of
I then I'll add a new
line okay let's drive this so far what
year was C++
created C who invented C++ that would be
B what is the predecessor of
C++ that is C the language C but it's
option A
is the earth flat what's Earth
D okay wrong answer B okay so we know
that we can cycle through the
questions outside of the for Loop we
will calculate the player score so right
here I'll display the word results
standard
output
results I'll add a new line actually now
that I think of it I'm going to steal
some of these text
decorations let's make it look
pretty something like this would look
cool but not
necessary standard
output
correct
guesses then we will display the current
score add a new line
standard
output number of
questions that is simply the size of our
array add a new
line then we will calculate a percentage
what percent of the questions did they
get
right
score score divided by size
times 100 then we'll add
percent so at first this isn't going to
work because we're using integer
division but I'll explain that
momentarily about type casting uh so
let's run this
once let's say A B C D correct guesses
one number of questions four uh our
score was 0% even though we got one
ready all right we'll need to add a cast
to the diviser let's cast size as a
double to hold that decimal
portion then this should
work A B C D correct guesses one number
of questions four our score was 25% now
let's go for 100 remember that the
correct answers are CB a b 1985 bejn
strp the language C but that's option A
is the earth flat no B correct guesses
four number of questions four score 100%
well yeah everybody that is a quiz game
you can make in C++ you can impress your
friends or have your friends take the
quiz you know you can change your
questions around if you want if you
would like a copy of this code I'll post
this in the comment section down below
and that is a quiz game written using
C++
hey everybody Welcome to the exciting
world of memory addresses a memory
address is a location in memory where
data is stored in C++ a memory address
can be accessed with an Amper sand known
as the address of operator suppose we
have some varibles I'll create a
string the variable name will be well
name assign this a string of text I'll
create int age set equal to some
value then a Boolean Boolean student
I'll set that to be true a variable is a
container for some data but these
variables need to exist somewhere well
they exist in your computer's memory at
a given address we can find that address
with the address of operator I'll
display that standard output I would
like to display the address of name then
I'll just add a new
line here's the address of my name
variable in my computer's memory it's a
bunch of weird letters and numbers well
this is a hexadecimal address every time
we run this program that number is
likely to
change let's display the addresses of
agent
student address of age address of
student here are the memory addresses
again all in heximal so these are kind
of like street address es hey for fun
let's decode these to decimal you can
easily find tools online to convert
heximal to
decimal let's see what these numbers
are here are the heximal memory
addresses but converted to decimal
they're like house numbers different
data types take up more or less room
than other data types if we look at the
distance between my name variable and
age well that has a gap of four memory
addresses but the gap between my age and
student variables is only one because
well booleans only take up one bite of
memory that's one of the reasons we use
data types we need to know how much
memory we need to allocate to fit a
certain value if we're working with a
Boolean variable well we only need one
bite of memory that's why the distance
between the memory address of age and
student is only 1 40 - 39 is 1 integers
take up four bytes of memory 44 4 - 40
is 4 4 bytes so that's an introduction
to memory addresses it's going to be
helpful in the next topic when we
discuss pointers if you would like a
copy of this code I'll post this in the
comment section down below and that is
an introduction to memory addresses in
C++ all right everybody so I'm going to
explain the differences between pass by
value and pass by reference in this
example we'll swap two variables suppose
we have two imaginary cups
I'll name the first cup x x will contain
Kool-Aid then we have cup Y which
contains water I need to swap these two
values we'll need the help of a
temporary
variable string temp to swap two
variables we would assign temp = to
x x =
y y = temp let's display these variables
standard
output
X the variable
X I'll add a new
line let's copy this paste
it y the variable y this should
work X now contains water y contains
Kool-Aid now check this out what if we
create a function to swap two variables
for us
the return type will be void I'll name
this function swap there will be two
parameters string
X string y let's copy this section of
code delete it then paste it within the
swap function then you'll need a
function declaration at the top of your
program then we will invoke this
function swap pass our arguments X and
Y let's see what
happens okay what the heck X still
contains Kool-Aid y still contains water
these values weren't switched within my
variables X and Y even though we invoked
this function so why didn't it work well
that's because normally when we pass a
variable to a function we're passing by
value when we invoke this function we're
creating copies of the original values
what we have now are two copies of the
variable X X and Y and all we're doing
is switching the two copies and not the
original values so that's pass by value
we're creating copies of the arguments
if I need to change the original values
of these variables I could instead pass
by reference a reference as in a memory
address an address in your computer's
memory where a value is located I will
prefix the address of operator which is
an ampersand to these parameter names
then add that to your function
declaration as well now let's see what
happens yeah those two variables were
switched X contains water y contains
Kool-Aid when we passed by value we
created copies of X and Y with the
parameters when we use the address of
operator we're passing memory addresses
to where the original X and Y variables
are located and then swapping the values
just to reinforce this idea let's revert
to passing by value I'm going to display
the address of X and Y then within our
SW op function let's get rid of this
code then I will also display the
addresses of X and
Y see we have four different addresses
our original X variable has a different
memory address than the one that's
within the function same thing goes with
Y these two addresses are different we
have two x variables and two y variables
originally within that swap function we
were switching the values of the X and Y
copies if we instead pass by reference
let's use that address of operator
again well now X and Y are referring to
the same place they have the same memory
addresses that's why the swap function
worked when we passed by reference in
place of pass by value so that's the
main difference between pass by value
and pass by reference you should use
pass by reference as often as possible
unless you have a reason to pass by
value if you would like a copy of this
code I'll post this in the comment
section down below and well yeah that's
the main difference between pass by
value and pass by reference in
C++ hey everyone in this topic I'm going
to explain const parameters a const
parameter is a parameter that is
modified with a const keyword that makes
it effectively readon there's a couple
reasons why you might want to declare a
const parameter your code is more secure
within a function and it conveys the
intent to other programmers it's
especially useful for references and
pointers here's an example of const
parameter an action I have standard
string name assign your first
name then in age whatever your age
is then suppose I have a function to
print my info void print info and there
will be two
parameters standard string name int age
be sure to add a function declaration if
you're missing
it then if I need to call this function
I would invoke the function name pass in
my arguments name
age then we can print our info standard
output
name standard output
age this of course does what you expect
it prints our name and our age to make
this function more secure we can instead
use con parameters that means that we
can't change the values that we receive
name and age in this case just as a test
let's set name equal to an empty space
and age equals z I don't want this to be
able to happen at all now when I run
this we don't have a name and we don't
have an age to make these parameters
readon we can precede the parameters
with that const keyword const string
name const int age and you would
probably want to add that to your
function declaration as
well just to display
intent there we have an error assignment
of readon parameter age and name is
somewhere up here but I don't feel like
reading all that when we pass our string
and our integer as arguments what we're
doing is effectively making a copy of
name and age technically we're not
modifying the original variables in this
case using the const keyword when we
pass a variable by value isn't really
that big of a deal but it at least
conveys intent if we were working with
reference data
types now we'll pass by reference well
now it's a bigger deal we don't want
anybody modifying the original name and
age variables all right everybody those
are const parameters they are parameters
Modified by the con keyword that
effectively make them read only within a
function your code is more secure and it
conveys intent it tells other
programmers hey don't mess with these
values they're useful with references so
that no nobody can change the value
found at that reference then in the case
of pointers nobody can change the
address of where a pointer is pointing
to so yeah those are const parameters in
C++ hey everybody in this topic we're
going to create a program to validate if
a credit card number is valid or not to
do so we'll need to utilize The Loon
algorithm which I've broken into these
steps if you need some test credit card
numbers you can always Google them I
found a bunch on this website let's just
take this one for example
and to make this more readable I'll
divide this number into groups of
four step one we double every second
digit from right to left if the double
number is two digits split them I'm only
concerned with every second digit from
right to left so we can eliminate some
of these that we won't be
using then we're going to double these
numbers so two doubled is four
9 doubled is 18 since we have the number
18 that's two digits we need to split
them we'll split 18 to one and
8 then six doubled is 12 we'll split
that step two we need to add all of
these numbers together to create a
sum the sum is 29 step three add all odd
number digits from right to left with
the original number so now we're only
concerned with the odd
numbers then we just add these numbers
together no need to double
them the sum is 21 step four we sum the
results of steps two and steps three 29
9 + 21 that equals 50 step five if step
four is divisible by 10 that number is
valid we could say our result modulus 10
if that number is divisible by zero that
number is valid 50 is divisible by 10 so
that number is valid we'll create a
program that will do all of this for
us let's create our functions we'll need
three int get digit
the parameter will be a constant integer
that I will name
number int we'll need to sum the odd
digits the parameter is const standard
string card
number let's copy this paste it sum even
digits the parameter is the same
let's copy these functions and add some
declarations we do need to return
something otherwise we'll get a warning
for the time being I'm just going to
return zero as a
placeholder okay let's begin with the
main function we'll need a credit card
number that will be a string standard
string card
number then int result and I will set
that equal to zero right away okay we'll
prompt the user to enter in their credit
card number standard
output enter a credit card
number standard
input card
number result equals will invoke the sum
even digits
function pass in our card number
plus some odd digits pass in our card
number we'll need to fill in these
functions let's begin with some even
digits we can get rid of this I'll
create a local variable named sum to
keep track of the sum what we'll need to
do is iterate over our card number in
reverse order we can treat a string as
an array of characters and we can
iterate over that so we'll need a for
Loop and we will iterate over this card
number in reverse order starting from
the end we'll need an index in I equals
then we'll need to find the size of our
card number there's a built-in function
for that card number do size now arrays
they always start with zero so we're
going to subtract one however if we're
summing the even digits beginning from
the right we'll need the second to last
digit so that would actually be -2 the
very last digit would be minus1 our
index I will begin from the second to
last position I would like to continue
this for loop as long as I is less than
or equal to
zero then we will decrement I by 2 i - =
2 because we need every even digit so we
will take sum plus equals then invoke
the get digit
function get digit within the get digit
function as an argument we're going to
pass in card number at index of
itimes 2 however there's one more thing
that we'll need to do with card number
at index of I we will subtract the
character Zero and here's why we're
currently working with a string of
characters you can also treat a string
as an array of characters each character
according to the aski table has an
Associated integer value a decimal value
if I'm passing one of these characters
as an argument to my get digit function
we'll treat that character as if it was
its decimal equivalent according to the
asky table the character Zero has a
decimal value of 48 the character 1 is
49 2 is 50 then all the way up to 9
which has a decimal value of 57 so if
I'm passing in the character at index of
I what we'll end up working with is the
decimal representation of that character
if we subtract the character Zero or its
equivalent 48 that would give us a range
of numbers 0 through 9 for example the
decimal equivalent of the character 9 is
57 57 minus 48 would be 9 you could
subtract either 48 or the character Zero
that would give us numbers 0 through 9
according to the asky table then we're
multiplying that number by two
then at the end we will return whatever
the sum is let's fill in this get digit
function within the get digit function
the digit that we're working with was
doubled whatever number we passed in it
may take two digits for example like 9 *
2 is 18 we need to split those two
numbers to get 1 and8 so I'm going to
return number modulus
10
plus number
ID 10 modulus 10 that will split the two
numbers for example let's say our number
that we're passing in as an argument is
18 9 * 2 18 modulus 10 would give us
8 18 / 10 that would give us 1 since
we're using integer Division 1 modulus
10 is
1 8 + 1 is 9
then we're just returning that number
nine okay that is the get digit function
then we need to sum the odd digits and
really we could just copy all this then
paste
it but there's a couple changes to make
in I equals card number. size function
minus one we need to begin at the end
and then sum plus equals card number
minus
0 when summing the odd digits there's no
need to double the odd digits that's
only with the even digits and that is
all the functions let's close out of
these so we'll have a result the sum of
the even digits plus the sum of the odd
digits if result is divisible by 10 that
number is
valid
if
result modulus
10 is equal to
zero then that number is valid standard
output card
number is
valid
else card number is not
valid okay let's try this I'm going to
enter in that original number that we
worked with that Discover card
okay enter a credit card number I'm
going to paste this hit
enter that number is valid let's try
that
again so I'm going to enter in the same
card number except I'll add one to the
end that number is not valid hey if you
have your own credit cards feel free to
try them too and see if it works all
right everybody that is a credit card
validation program most for practice if
you would like a copy of this code I'll
post this in the comment section down
below please be sure that you do not
enter in your own credit card into the
comment section and well yeah that is a
credit card validation program using
C++ all right everybody we finally made
it to pointers a pointer is just a
variable that stores a memory address of
another variable that's it the reason
that we use pointers is because well
sometimes it's just easier to work with
an address here's an example I have a
stack of maybe 20 pizzas that I'm going
to give out for free to my neighborhood
instead of going around house to house
carrying the free pizza and handing it
out it's a lot easier to go door too and
tell people where the pizza is located
hey there's free pizza at my house at
this address come and get some and
that's one of the uses of pointers
sometimes it's easier to just work with
an address I'll tell people where the
free pizza is rather than carry it
around with me so when working with
pointers need to use the address of
operator which is an ampersand as well
as the D reference operator which is an
asterisk let's begin with the name I'll
create a pointer Twi a name standard
string name assign your first
name then we'll create a pointer to name
where is my name located in my
computer's memory to create a pointer it
should be of the same data type as the
variable it's pointing
to I'm creating a pointer to a string
this pointer will be a of the string
data type then type asterisk that D
reference operator then a common naming
convention for pointers is you type P
then the variable name but I'm going to
make the first letter uppercase I will
set this pointer equal to the address of
that name
variable and there we go we have a
pointer so if I was to display this
pointer standard
output P name
my pointer contains this value it
contains a memory address as its value
to access the value at this address you
would use the dfference
operator I'm accessing the value of that
address that's stored within this
pointer which contains my first name by
using this D reference operator I'm
accessing the value that's at this given
address which contains my first name
let's create a couple other pointers
let's create a variable age int age
equals make up some
age I'll create a pointer to age the
data type of the pointer should be the
same as the variable int D reference
operator P age equals the address of
age then let's
display whatever value is is located at
the address that's stored within my
pointer of
pH so we have my first name and then an
age I think I'm just going to add a new
line real
quick going back to that analogy with
the free pizzas I'll create an
array an array of
strings I'll name this array free
pizzas I'll give this a size of five
we have pizza
1 Pizza 2 Pizza 3 Pizza
4 then Pizza
5 like I said in my example it's a lot
easier instead of carrying around five
free pizzas house to house giving away
Pizza I can just tell people where the
pizza is located I'll give them an
address I'll create a pointer to this
array we'll use the same data type we're
storing
strings D reference operator P free
pizzas now I'm going to attempt to set
this to the address of free
pizzas now we're going to run into a
problem my array is already an address
so I don't need to use the address of
Operator Let Me demonstrate
I will display see out free
pizzas when accessing my array free
pizzas it's already a memory address if
I display the value contained within my
pointer to my free
pizzas it's going to be a memory address
then if I was to use the dfference
operator
that would give me the first element
within that array Pizza one so those are
Pointers it's a variable that stores a
memory address of another variable
sometimes it's easier to work with an
address instead of carrying five free
pizzas with me and going house to house
giving it away I'll just tell people
where the free pizza is so those are
Pointers your assignment is to post a
pointer in the comment section down
below and well yeah that's an
introduction to pointers in C++
hey what's up everybody so let's talk
about null pointers but first we'll need
to know what a null value is a null
value is a special value that means that
something has no value when a pointer is
holding a null value that means that
pointer is not pointing to anything
that's what we would call a null pointer
there is a keyword that represents that
null PTR PTR meaning pointer it's a
keyword that represents a null pointer
literal one of the reasons that we use
null pointer is that they're helpful
when determining if an address was
successfully assigned to a pointer if we
create a pointer but don't assign it a
value we don't know where it's pointing
to it would be good practice that that
pointer doesn't Point anywhere so let's
create a null pointer I'll create a
pointer of the int data type we use the
D reference operator pointer if I'm not
going to assign this pointer and address
right away it would be good practice to
assign this pointer null PTR null
pointer
later on in your program if you need to
assign an address let's say int x = 1 23
I would just take my pointer set this
equal
to the address of my variable if you
dfference a null pointer it can lead to
undefined Behavior or if you dreference
a pointer that's not assigned a value
well that can lead to undefined Behavior
too what some programmers do is that
they'll check to see if their pointer is
a pointer before continuing kind of like
a system of checks and balances we
assigned our pointer the address of X I
would like to check to see if my pointer
contains a valid address before
dereferencing it so we could say
pointer equals null pointer was my
pointer assigned an address or is it
still a null
pointer if my pointer is still a null
pointer that means we did not
successfully assign an address to my
pointer there may be situations such as
when working with dynamic memory where
you attempt to assign an address to your
pointer and it fails this would be a
good way to check to see if that failed
or not if your pointer Still Remains a n
pointer so let's say address was not
assigned
else standard
output address was assigned
so let's run this currently our pointer
is pointing to the address of
X address was assigned now if for some
reason we did not assign an address I'll
turn this line into a comment to
represent that well our pointer is still
going to be a null
pointer address was not assigned if your
pointer is still a null pointer it's not
safe to dereference that pointer if I
need access to the value that's at that
pointer it would be safe to do so within
this else
statement standard
output the reference
operator
pointer so my pointer contains the
number 1 123 if I were to dreference
this null pointer that would lead to
undefined Behavior I have no idea what's
going to
happen don't try this at home
kids what the
a null pointer is a keyword that
represents a null pointer literal when
declaring a pointer it's good practice
that our pointer is pointing to a valid
address or this null pointer keyword
because otherwise we don't know where
it's pointing originally they're helpful
when determining if an address was
successfully assigned to a pointer when
using pointers be careful that your code
isn't dereferencing a null pointer or
pointing to any free memory that we're
not using cuz that can lead to undefined
Behavior
so yeah everybody those are n pointers
in
C++ hey guys in this topic we're going
to create a game of tic taac toe we'll
be working with random numbers you may
or may not need to include this header
file
include C time we'll add some function
declarations then some definitions void
draw board there will be one parameter a
pointer tun array named spaces spaces
will be a one-dimensional array that
will keep track of all the markers like
what spots are taken what spots are
occupied Player
move the parameters will be a pointer to
spaces and Char
player computer
move a pointer to
spaces char
computer check
winner a pointer to spaces Char player
and Char
computer then
lastly check tie and all we need is a
pointer to our array spaces oh uh check
winner and check tie will both return a
Boolean
value okay let's add some fun
declarations so after the main function
let's paste
these we do need to return some value
for check winner and check TI because
there is a return type just for now as a
placeholder I'm going to return
zero but we'll change that later let's
head to the main function and declare
everything that we'll need a character
array named space
spes the size will be nine nine
spaces we'll have nine elements each
contains an empty
space one two three four five six seven
eight nine
good Char player pick a character that
you'd like to be you could do X or
something something
else Char
computer pick a character for the
computer let's begin with
o Boolean running I'll set this equal to
True when we begin our game we will
immediately invoke the draw board
function then pass in our array so
remember when we pass an array to a
function it decays into a pointer so we
don't need to create a pointer for this
array within the drawboard function we
will display a
grid so let's write something like this
standard output I'll add five spaces 1
two 3 4 five then a vertical bar five
spaces again 1 2 3 4 5 vertical bar 1 2
3 4 five then a new
line okay let's copy this
line right in the middle I'm going to
add one of the elements of our array
spaces so right about
there spaces at index
zero I'm going to copy this section of
code right in the middle between the two
vertical bars I'll paste what we copied
spaces at index
one then again right in the middle
paste what you have spaces at index
2 this time we'll create a horizontal
bar let's copy this we'll replace the
spaces with
underscores so right about
there okay let's see what we
have okay yeah something like this we'll
have a player or the computer right in
the
center so let's copy this line on top
paste it underneath copy this line that
displays elements of our
array paste it underneath but change the
element to numbers 3
4 five and we'll copy this
line paste it
underneath let's double check to see
what we
have okay we're getting somewhere let's
copy this line
paste
it copy one of these lines where we
display the elements of the
array paste it
underneath so we are missing elements
six 7
8 let's copy one of these empty
lines paste it
underneath then before and after we
display this grid I'll just display a
new line standard
output new
line and let's do that
after okay let's see what we
have yeah not too bad there's our grid
of nine
spaces okay that is the draw board
function we can close out of this we're
done with that when we invoke the draw a
board function we will pass in our array
which decays to a pointer and then
prints our board let's add a while loop
after the draw board function while our
condition is running running is set to
True
initially when we exit out of the game
we'll set running to be false the first
thing that we'll do is invoke the player
move function Player move but we need to
pass in our array spaces as well as a
player player then let's fill in the
player move
function okay player move move I'll
create a local variable named number the
user will enter in a number between 1
and 9 depending on what space they'd
like to occupy with their marker I'll
create a do while loop do while the
condition will be not number is greater
than
zero or not number is less than 8 the
user can only enter in a number between
0 and 8 those numbers correspond to the
elements of our array elements with
indices 0 through 8 within the do while
loop we'll ask for some user input
standard
output enter a
spot to place a
marker 1 through n whatever the user
types in we'll just subtract one because
the user doesn't know that arrays start
with zero supposedly
standard
input
number so the user will enter in a
number between 1 and N then we will
decrement the number by one because the
array starts with
zero if spaces at index of number
whatever the user types in is equal to
an empty space if that space isn't
occupied We'll add that marker to that
spot
spaces at index of number
equals the players marker then we like
to break out of this while loop so after
the player moves let's draw the board
again to reflect any
changes okay enter a spot to place a
marker how about one yeah and there's
our marker let's try it
again how about nine yep and we are in
the last spot the bottom right Corner
let's enter in a number that's outside
of this range like 100 enter a spot to
place a marker
uh1 okay so we're limited to the numbers
1 through n even if I were to type zero
we still can't uh so let's try something
in the middle that would be 1 two 3 four
five yeah and there's our marker I'm
just going to add a colon then a space
okay and that is the player move
function we can close out of this
function
let's work on the computer move function
next within the while loop let's invoke
that function pass in our spaces array
as well as whatever character the
computer is then we will draw the board
again right after just to update it
within the computer move function we'll
create a local variable named
number we'll need a seed to generate a
random number s
Rand within the parenthesis invoke the
time function pass in zero or
null and we should be able to generate
some random
numbers so I'm going to create a while
loop while the condition will be true I
would like to generate a random number
between 0 through 8 we'll take number
set this equal to Rand function modulus
9 number will be random between 0 and 8
technically if we pick a spot number
that is occupied already we'll need to
reroll a random
number if
spaces at index of number is equal to an
empty space we'll take spaces at index
of number set this equal to the
computer's
marker then break out of this while loop
Let's test this
function after we pick a spot the
computer will pick a spot too yep so the
computer picked a spot right in the
middle let's right one more time I'll
pick the spot in the middle again so
that would be five and our computer
picked spot number two cool let's close
out of the computer move
function after the player moves then we
draw the board again we will check a
winner I'll use an if statement within
the condition of the if statement we
will invoke the check winner function
the check winner function returns a
Boolean value so that's why we're
placing it within the if statement but
we need to pass in a couple ARG
are spaces the player and the
computer if there's a winner if this
evaluates to be true we will set running
equal to false and we will break let's
add this if statement to after the
computer moves
too okay let's fill in the check winner
function so write down
here we'll need to check all of the
different win conditions there's several
normally I would use a switch but it's
going to get very complicated especially
for beginners I think just to make this
easier we'll use a bunch of if and else
if
statements within the first condition of
the if statement we'll check to see if
the first row all has matching
characters so we can do that by saying
spaces at index of
zero is equal to spaces at index of
one and
spaces at index of one is equal to
spaces at index of two if all three
characters in the first row are the same
that means that somebody won I'm going
to use the tary operator here we have to
determine who won the player or the
computer let's check to see if the first
index spaces at index zero is equal to
the player's marker tary operator like
we're asking a question if the player
occup
the first row then we'll print standard
output
you
win otherwise standard
output you
lose and I'm just going to add a new
line here and
here okay there's one more thing we have
to do with this condition and I'll
explain that so let's run
this oh I'll pick spot number
nine you lose the reason that we lost is
that we're checking to see if the first
row all has the same characters they're
technically all empty spaces so our
program thinks that somebody won because
all of these characters match there are
three empty spaces I'm going to amend
this if statement we'll want to ensure
that none of the spaces are empty and
really we only need to check the first
space I'll make this amendment spaces at
index of zero
does not equal an empty
space and all these other conditions if
you'd like to keep this more organized
you can always surround some of these
conditions with
parentheses I think it's more legible
that
way let's try that again just to be sure
that it's working I'll pick something in
the
middle okay yeah so the computer doesn't
win automatically if there's three empty
spaces in the first row okay so that is
the first win condition let's copy this
condition I'll add else if now we'll
check the second row if spaces at index
3 is not equal to an empty space and
spaces at index 3 is equal to spaces at
index 4 and spaces at index 4 is equal
to spaces at index 5 then does spaces at
index 3 equal to player okay so that is
row two let's copy and paste that else
if statement then we'll need to check
the last row SPAC is at index 6 6 is 6
equal to 7 and is 7 equal to 8 so these
conditions will check all of the rows
then we'll need columns let's copy one
of these L if statements paste it so we
have 0
0 is 0 equal to 3 and is
three equal to 6
okay now time for the second
column spaces at index
one one right here as
well is 1 equal to 4 and is 4 equal to
7 copy this again paste
it then we have the third
column 2 2
is 2 equal to
5 and is 5 equal to
8 okay now the
diagonals spaces at zero
0 is 0 equal to
4 and is four equal to
8 then the last diagonal
spaces at index 2
2 is 2 equal to
4 and is four equal to
6 if there's no win
conditions we'll have an else statement
we will return false then all we have to
do at the end of this function is to
return true somebody won okay so let's
test
this I'll try and win with the first row
one two three you win this time I'm
going to try and
lose
one
2
4 7 whoops Seven's taken uh eight there
we go you lose we can close out of the
check winner function we know that it's
working then we just need to check to
see if there's a tie if there's no more
spaces available within the the main
function after our if statements we'll
add else
if we'll invoke the check tie
function pass in our spaces check Tai
returns a Boolean value if it's
true we will set running to be false
then
break then add that after the computer
move section too so right
here then let's fill in this function
within the check tie function we'll
iterate over the elements of our array
spaces we'll use a for Loop for in I
equals z we'll continue this as long as
I is less than 9 because there's a total
size of nine
spaces increment I by
One if spaces at index of I is equal to
an empty space that means we can
continue return false there's still
empty spaces if we iterate over our
array and there's no empty spaces well
then we'll display standard
output it's a
tie I'll add a new
line then we will return true and we can
get rid of
that okay so let's close out of this
check tie
function then after we exit our game
outside of this while loop let's display
a message standard
output thanks for
playing all right and that's everything
let's run this I'm going to try and get
a tie this
time
one
2
6
7 8 it's a tie thanks for playing all
right everybody that is a game of
tic-tac-toe for beginners if you would
like a copy of this code I'll post this
in the comments section down below and
well yeah that's a game of tic-tac-toe
using
C++ hey everybody we finally made it to
dynamic memory dynamic memory is memory
that is allocated after the program is
already compiled and running to allocate
dynamic memory we use this new keyword
it's an operator it allows us to
allocate memory in the Heap rather than
the stack it's useful when we don't know
how much memory we'll need it makes our
programs more flexible especially when
accepting user input because we have no
idea what the user is going to type in
here's an example we'll start with a
basic integer variable but we'll
allocate memory in the Heap rather than
the stack by using that new keyword I'll
create a pointer
int D reference operator P num now it's
good practice when when you declare a
pointer but don't assign it right away
to give it a value of null meaning no
value to allocate memory in the Heap
rather than the stack I'll take my
pointer set this equal to use the new
operator then a data type I'll use up
enough space in the Heap for one integer
the new operator will return an address
we're storing that address within P num
because it's a pointer it's pointing to
a memory location where we're going to
store an integer later on in your
program whenever you would like to store
a value we can use the dfference
operator our pointer then assign some
value like 21 I don't know just for fun
I'm going to display the address that's
stored within the
pointer
address P num then I'll add a new
line as well as the
value value the reference operator P num
our pointer is storing this address and
at this address in the Heap that address
contains this value 21 now it's very
good practice if not expected whenever
you use the new operator you'll also
want to use the delete operator when
you're no longer using that memory space
So at the end of this program or earlier
if you choose we will delete our pointer
delete P num we're freeing up the memory
at this address if you don't you may
cause a memory leak and it's best to
avoid that whenever you use the new
operator you probably should be using
the delete operator some place within
your program here's another example
we're going to dynamically create an
array let's create an array of grades
Char then we'll need a pointer the
reference operator P
grades set this equal to null if we're
not going to assign this pointer right
away then to dynamically create an array
we will we'll take our pointer set the
equal to new the data type Char if this
is an array we add a set of straight
brackets within the straight brackets we
will list a size if I have five grades
to enter in I would type in five but if
we already know the size of the array
before we even run the program we might
as well do that normally like create a
normal array there's no point to
allocating memory dynamically we would
want to do that when we don't know what
the size is going to be so I propose we
ask for some user input let's say in
size we'll create a prompt standard
output how many grades to enter
in standard input size will dynamically
allocate enough memory in the Heap
depending on how many grades the user
has to enter in I'll just create a for
Loop so that we will ask the user to
enter in some grades in I equal 0 I will
continue this as long as I is less than
size increment I by
1 standard
output enter grade
number I + one because I will be zero to
begin
with and I'm just going to add colon
space
afterwards standard
input P Cades that's our pointer now we
we can either add plus I or use those
straight brackets at index of I either
way let's display all of the
grades in I equals z i is less than size
i++ standard
output P grades at index of I I'll
separate each with the space and
remember if we no longer need this array
we should delete it to prevent a memory
leak if we have to delete an array we'll
add a set of straight brackets after
delete then our
pointer PG
grades and let's try
it how many grades to enter in so we
don't know what the user is going to
type let's say six grades enter grade
one a b c d f a and here are the grades
so that's why dynamic memory is useful
it's memory that is allocated after the
program is already compiled and running
we use the new operator to allocate
memory in the Heap rather than the stack
it's useful when we don't know how much
memory we will need it makes our
programs more flexible especially when
accepting user input so that is an
introduction to dynamic memory we'll
have more practice with this in the
future so don't worry if you would like
a copy of the code that we worked on
I'll post that in the comments section
down below and well yeah that's an
introduction to dynamic memory in
C++ hey guys I got to explain recursion
recursion is a programming technique
where a function invokes itself from
within we break a complex concept into
repeatable single steps many problems we
can approach iteratively or recursively
some of the advantages of recursion
include less codite and typically it's
cleaner it's also useful for sorting and
searching algorithms however some of the
disadvantages of recursion is that it
uses more memory and slower there's a
trade-off it's up to you if you'd rather
use an iterative approach or a recursive
approach here's an example we'll break a
complex concept maybe such as walking
into repeatable single steps to
accomplish the task of walking we would
take a single step and then just repeat
that a bunch of times we'll do this
first iteratively then
recursively so let's create a function
to walk V
walk there will be one parameter a
number of steps let's define this walk
function we'll use an iterative approach
first to do that we can use a for Loop
we'll set in I equals z we'll continue
this as long as I is less than our steps
then increment I by One I will
display just you take a
step then I'll add a new
line so we will invoke this function
pass in how many steps we would like to
walk I would like to walk 100
steps and here we go we printed you take
a step 100 times this is an iterative
approach if we were to take a recursive
approach we would invoke this function
from within itself so I'm going to turn
this for Loop into an if statement
we'll need a base case when do we stop
if
steps is greater than zero we will
display you take a step then I'm going
to invoke the walk function from within
itself then I will pass in steps minus
one this would be a recursive approach
we're invoking the walk function from
within itself you'll end up in a
function within a function within a
function within a function so on and so
forth so when I run
this this would do the same thing but
we've done so recursively the advantages
with recursion is that the code tends to
be easier to write I find this if
statement a lot easier to understand
than that for Loop although they're both
pretty simple however with recursion it
uses more memory and it takes more
processing time in the case with our
walk function I would probably stick
with an iterative approach there's
really not much benefit in this case but
in the case of let's say a searching
algorithm or navigating a tree data
structure recursion would really help us
with that so let's say we don't have a
base case that's when we stop what if I
just call the walk function
forever well we end up in an infinite
Loop and we would encounter what's
called a stack overflow when you invoke
a function you add what's called a frame
to the stack when your stack is
overloaded you'll encounter a stack
Overflow so that's one problem with
recursion
so let's try a different example we'll
create a factorial function if you don't
remember factorial is a mathematics
concept where you take a number and you
multiply that number times the previous
number minus one times the previous
number minus one times the previous
number minus one until you reach one you
multiply all these numbers and you're
given a result I'm going to demonstrate
a function to do that both iteratively
then recursively let's begin with an
iterative approach we will return it
integer this function will be named
factorial we'll pass in an integer named
num I'll immediately display the output
standard output factorial then pass in
some number maybe
10 let's define this
function if I was to take an iterative
approach I would write something like
this in result this will be a local
variable I'll set this equal to one I'll
create a for
Loop in I equal
1 we'll continue this as long as I is
less than or equal to our number
increment I by One I will take our
result equals result times whatever I
currently is at the end of this program
we will return result factorial 10 that
would be 3,6
28,800 if I was taking a recursive
approach I would write something like
this we would need a base case when do
we
stop if num is greater than
one we will
return num times invoke factorial again
our number minus
one else we will simply return one this
would do the same thing but recursively
factorial 10 is
3,628
1800 those were two different approaches
to the same problem when we did this
recursively we have a function call
inside of a function call inside of a
function call inside of a function call
you get the idea personally I find a
recursive approach to be a lot easier to
read and understand although remember it
uses more memory and a slower when you
start to learn about sorting algorithms
that's when recursion is really going to
help you quite a lot it will simplify
the steps so that's recursion everybody
it's a programming technique where a
function invokes itself from within we
break a complex concept into repeatable
single steps whenever you see a function
invoking itself from within you'll know
that that's recursion hey if you would
like a copy of this code I'll post this
in the comment section down below and
well yeah that's recursion in
C++ hey everyone let's discuss function
template
a function template describes what a
function looks like they can be used to
generate as many overloaded functions as
needed each using different data types
how is this useful suppose we have a Max
function that will accept and return an
integer int Max the parameters will be
int X int
y will return I'll use the tary operator
here is X greater than
y if so return X if not return y this
function is compatible with integers as
arguments let's display standard output
Max then pass in two integers like one
and
two so this would return the number two
but what if I would like to use this
function with doubles such as
1.1 and 2.1
while we're truncating that decimal
portion we're returning two not 2.1 if I
want this function to be compatible with
doubles normally I would have to create
an overloaded function that accepts
doubles and returns a double replace int
with
double and I guess this would work
technically the value returned is 2.1
what about characters how about the
character
one and the character 2 technically we
could use the max version that accepts
integers because there's an Associated
asky value with each of these characters
but I would like an overloaded function
that accepts and returns characters Char
Char
Char so this would return the character
to this is a lot of work creating three
overloaded functions that each do the
same thing the only difference is that
they accept and return different data
types what if we could write one
function that will accept any data type
well that's what function templates are
to create a function template take your
function replace any data type with t
we're returning an integer let's instead
return T the data type of X will be T
same thing with Y using t as a common
naming convention I like to think of it
as thing like we're not sure what the
data type is we're returning a thing
that's just how I think of it however
our compiler doesn't know what T is
exactly we'll need to add a template
parameter declaration before this
function template definition we'll add a
declaration of what T is so type
template angle
brackets type name t and that's it this
function template will work with many
data types
characters
doubles
integers you name it so yeah just
replace the data type with t then be
sure to add a template parameter
declaration now here's a scenario what
if you need to mix and match the data
types I'll find what the max is between
the integer 1 and the double
2.1 well we have a problem no matching
function for call 2 max int double with
this function template it's only set up
to receive arguments of the same data
type now we're passing in two different
data types what we could do within our
template parameter declaration is add
another template name I'm going to add
type name U because U comes after T in
the alphabet then if you needed more you
could add V WX so on and so forth I'll
change one of these T's to a u this
function template is set up to receive
up to two different data types as
arguments but there's one more change we
need to
make so we don't have that error anymore
but the decimal portion of of our double
is truncated it's returning two that's
because we're still returning T and T we
set to be an integer in this case do we
set the return type to be t or U
actually better yet we can set this to
Auto using the auto keyword the compiler
will deduce what the return type should
be this should return
2.1 all right everybody that is a
function template it describes what a
function looks like they can be used to
generate as many overloaded functions as
needed each using different data types I
like to think of it like a cookie cutter
we're determining what the shape is but
the arguments the dough that we use for
our cookies can be different but the
cookies will end up having the same
shape one of the main benefits of using
function templates is that we only have
to write a function once and then it's
compatible with different data types so
you don't need multiple versions of the
same function we'll generate functions
using this template as needed so yeah
those are function templates everybody
your assignment if you choose to do so
is to write a function template in the
comment section down below and well yeah
those are function templates in
C++ well okay then everybody we got to
talk about structs a struct is a
structure that groups related variables
under one name think of an array an
array can store multiple values of the
same data type well a struct can store
multiple values of different data types
we we can store strings along with ins
doubles booleans Etc to create a struct
let's do so outside of the main function
type struct then we need an identifier
this is kind of like the data type
suppose we're going to group related
variables for
students I'll name this identifier
student within the structure of student
variables that we declare are known as
members I think each student should have
a name member this will be of the string
data type string name I'll declare this
but not yet assign it as well as a GPA
that could be of the double data
type then a Boolean variable if they're
currently enrolled or not
enrolled then be sure to end your struct
with a semicolon our struct student is
kind of like its own data type we can
use this data type to declare variables
I'll create a student variable of this
data type and that variable will have
these three different members a name a
GPA and a Boolean variable for being
enrolled much like with creating a
variable we type the data type student
and then some name some identifier let's
name the first student student one
student one will have its own name GPA
and enrolled status if I would like to
assign the name member of student one I
would type the name of the student
student one followed by dot members can
be accessed with a DOT also known as the
class member access operator I'll assign
the name member and set this equal to
SpongeBob I'll assign student 1's GPA
student 1. GPA I'll give SpongeBob a
solid 3.2 then I could set his enrolled
status student one.
enrolled I'll set this to be true then
we could access these members I'll
display them standard
output student 1. name
I'll add a new
line let's do the same thing with GPA
and enrolled student 1. GPA student 1.
enrolled this is what this looks like we
have a student variable the name member
is SpongeBob SpongeBob has a GPA of 3.2
when accessing Boolean variables one
corresponds with true zero corresponds
with false enrolled a set to true so
that would return one let's reuse the
struct to create a second
student I'll just copy what we have here
then paste
it we'll give the second student a
different identifier such as student
two student two will have a name member
of
Patrick a GPA of
2.1 and he will be enrolled that's set
to True let's display student 2's
members student 2.n name student 2. GPA
then student 2.
enrolled these first members correspond
with student one SpongeBob 3.2 one for
True the second set is for student 2
Patrick has a GPA of 2.1 and Patrick is
currently enrolled okay one last example
let's create student
three let's copy what we have paste
it student student 3 student 3. name
student 3. GPA student 3. en rolled
student 3's name will be
Squidward Squidward has a GPA of 1.5
let's set enrolled to be false then
display student 3's
members student 3. name student 3. GPA
student 3.
enrolled and here are student 3's
members Squidward 1.5 and zero that
means false now with members you can set
a default value all set enrolled to be
true then we don't need to explicitly
state
that underneath SpongeBob Patrick and
Squidward their enrolled member is all
set to one with members you can set a
default value so yeah those are strs
it's a structure that groups related
variables under one name strs can
contain many different data types
variables in a struct are known as
members and members can be accessed with
a DOT the class member AIS operator so
those are strs your assignment is to
post a struct in the comment section
down below and well yeah those are strs
in
C++ hey everybody in this topic I'm
going to show you how we can pass a
struct to a function in C++ suppose we
have a struct the identifier of the
struct will be
cars then we'll create some members
related to cars how about a model
standard string model a year in year
then a color standard string
color then let's go ahead and create two
car structs how about car car
one car car
2 then we'll assign the
members car one. model pick a model of a
card that you
like then a year
and a
color let's do the same thing with Car
2 car 2. model car 2. year car 2.c color
let's pick some different
data that'll work suppose we have a
function to display the members of a
car void
how about print car we're printing the
members we'll need some
parameters the data type of what we're
passing in are car structs so we'll list
that as the data type then some nickname
for the argument that we receive how
about just car then I will display the
members standard output
car. model should probably add a new
line
too then do the same thing with year and
color car doe car. color Let's test this
by printing car one print car 1 we will
pass the name of a struct as an
argument uh then I think we're just
missing a function declaration so if
you're missing that be sure to add that
there now let's run
this okay here's our car Mustang 2023
and the color is red now with structs
they're passed by value rather than
passed by reference if we pass a struct
as an argument what we're doing is
creating a copy of the original struct
to demonstrate that let's display the
address of car1 before and within the
function standard
output address of operator car one I'll
add a new
line then let's do that within the
function
too the parameter name is car not car
one there so let's try
that so these addresses are different
when we pass the struct to a function
the function will create a copy of it
it's pass by value we're displaying the
members of the copy rather than the
original if you need to work with the
original struct you can use the address
of operator we're passing a reference to
the original car struct then be sure to
change that within the function
declaration as well so let's take a look
at the addresses now
yeah these addresses are the
same car 2 is feeling pretty lonely so
let's print Car 2 as well print car pass
in Car 2 as an argument to this
function so we should have car one and
Car 2 this time let's change one of the
members within a
function let's create a function to
paint car painted a different color
paint car there will be two
arguments an address to a
car as well as a color which will be of
the string data
type be sure to add a function
declaration if you're missing
it then within this function we will
take our car. color equals the new color
that we
receive now before we print our cars
let's paint them a different
color paint car we have two arguments
this time a car struct and a new color
let's paint our Mustang
silver then let's paint car2 maybe
gold then let's display
this okay our Mustang is now silver and
our Corvette is now gold so if we didn't
use the address of operator When
painting our car let me show you what
happens our cars are still the original
colors red and blue what we did within
this function is that we created a copy
of our car struct and changed the color
of the copies rather than the originals
so if you need to make any changes to
the original you would want to use the
address of operator so that's how to
pass structs to functions you can pass
by value which can be expensive or you
can pass by reference your assignment if
you choose to do so is to post a
function that accepts a struct as an
argument and that's how to pass structs
to functions in
C++ hey everybody we got to talk about
enums enums also means enumerations it's
a userdefined data type that consists of
paired named integer constants they're
great if you have a set of potential
options here's an example suppose we
have a day of the week standard string
today then pick a day I'll pick Sunday
normally you can't use strings within
switches but we can use enums which are
kind of similar let me explain so I'm
going to create a switch we will examine
today normally we can't do this because
it's a string we'll examine today
against many matching cases case Sunday
and I'll speed up the footage
okay here's my switch depending on what
day of the week it is we'll display a
custom message it is either Sunday
through Saturday one of these days so
normally we can't use strings within
switches this is what happens when we
attempt
that error switch quantity not an
integer something similar that we can
use are enums they're paired named
integer constants we have a name and an
Associated value they're interchangeable
at the top of my program I will declare
Eno
then a name for the set of enumerations
let's say day for day of the week we
have Sunday
Monday
Tuesday and you know the
rest you can associate a value with each
of these names Sunday equals z Monday
equals 1 then we'll just continue on
with with the rest of
these I'm going to group these together
like
that okay we have our enum setup this
identifier is kind of like the new data
type we're not working with strings
anymore we're working with days these
are a set of potential options each
option is a pair of a name and some
Associated value you can really pick any
value I went with the numbers 0 through
6 to represent the day of the week I'm
going to set today to Sunday this name
we can now use this within a switch
there's an Associated integer value but
we'll change the cases from strings to
that enum data
type and this would
work it is Sunday within the cases you
could use the associated values as well
I'm going to change today to be
Friday case Zero is Sunday Monday is 1 2
3 4 5
6 it is Friday so that also works but I
don't think it's as readable another
cool thing with enums is that enom
variables take only one value of the set
if I try and make up some value like P
Pizza day well we can't do
that pizza day was not declared in the
scope here's a few other enum examples
you could create a set of enums for
flavors vanilla chocolate strawberry
mint an important note is that if you're
working with enums and you don't assign
an integer value to each of these names
you'll implicitly assign zero to the
first name then one 2 three kind of like
what I did up here but we explicitly
assigned those values we have six colors
or maybe planets I have a set of enums
of the nine planets in our solar system
the associated integer is the size of
each planet in kilometers so yeah those
are enums they're a userdefined data
type that consists of paired named
integer constants they're great if you
have a set of potential options your
assignment is to post a set of enums in
the comment section down below and well
yeah those are enums in C++
hey everybody so we have finally made it
to object-oriented programming an object
think of it as a collection of
attributes and methods attributes are
characteristics of an object methods are
functions that an object can perform
objects can be used to mimic real world
items so look around you right now next
to me I have a phone a book and a dog
think of attributes as characteristics
what kinds of characteristics would a
phone have maybe a version number a
charge a service provider objects can
also contain methods what kinds of
actions can a phone perform they can
make calls receive calls play games now
with a book some of the attributes of a
book could be maybe an author number of
pages let's see what kinds of methods
can a book perform really not much you
can open a book and you can close it so
those are just a few okay last lastly
how about a dog object some of the
attributes of a dog could be a name an
age maybe a breed of dog then what kinds
of actions can dogs perform they can eat
they can bark they can sleep maybe play
fetch so I think you get the idea an
object is a collection of attributes and
methods Now to create an object we can
use a Class A class acts as a blueprint
to create objects let's create a class
to create human objects
I will type class human curly braces I'm
going to add a public access modifier
we'll learn about access modifiers
pretty soon I would like these
attributes and methods to be publicly
accessible let's start with the
attributes of humans what kinds of
characteristics can humans have how
about a
name this will be of the string data
type I'll declare this attribute but not
yet assign it
maybe an occupation like a job standard
string
occupation then maybe an age int age our
class human has these attributes humans
have a name an occupation and an age
that's good enough for this example now
let's cover methods a method is a
function that belongs to a class it's
something that an object can do an
action it can perform what sorts of
actions should our humans be able to
perform how about an e
method void
e I'll just display a message standard
output uh let's say this person is
eating humans can drink void
drink standard
output this person is
drinking okay one last example how about
sleep human sleep right void
sleep standard
output this person is
sleeping good enough oh then make sure
we add a semicolon to the end of the
class perfect okay so we now have a
human class we can use this class as a
blueprint to create human objects each
human object will have a name an
occupation and an age they can also eat
drink or sleep they have their own
functions which we call methods so to
create a human object we will type the
name of the
class
human then a unique
identifier how about human one that's
creative so human one is an object human
one has a name an occupation and an age
but we have not assigned these
attributes let's say human one's name
human one member AIS modifier which is a
DOT name equals
Rick then human
ones
occupation equals
scientist human ones age equals
70 let's verify that this worked by
printing out these
attributes standard
output human one.
name I'll add a new
line then let's repeat this for
occupation and age human one. occupation
human
1.age human one's name is Rick his
occupation is a scientist his age is 70
years
old so this part is kind of similar to
strs however objects can also perform
actions they have methods Rick can eat
drink and
sleep so to invoke those methods I would
type the name of my object human one and
let's have human one
eat so human one. eat add a set of
parentheses to invoke this
method okay this person is eating let's
also test drink and
sleep human one.
drink human one.
sleep okay this person is eating this
person is drinking this person is
sleeping and that is our human human one
for more practice let's create a second
human human human
2 I'm going to copy these lines
let's change human one to human
2 human 2's name will be Morty
occupation will be student age what
about 15 I'm going to display the
attributes of human 2 this time then
I'll have human 2 invoke its methods eat
drink then
sleep okay human 2's name is Morty their
occupation is a student Morty is 15
years old then Mor Mor can perform these
actions eat drink and sleep now you can
assign some default attributes so let's
say that all humans we create will be
named Rick it's kind of like we're
cloning
him his occupation will be
scientist age will be
70 I'm not going to assign these
attributes what I did is that I added
some default
attributes so we have human one and
human 2
I'll display the attributes of human one
first then human 2 human
1name occupation
age then we have human 2's attributes as
well so remember I am not assigning
these attributes within the main
function we have two humans they're both
named Rick they're both scientists and
they're both age 70 okay now here's one
last example to really get the hang of
objects let's create a different class
this time how about cars Class
Car let's add a public access modifier
then what kinds of attributes would cars
have perhaps a
make standard string
make a model standard string
model a year that would be an INT then
maybe a color standard string
color you can add some default
attributes but I'll just leave those
empty for now you can add some methods
what kinds of actions can cars take I
guess you can accelerate void
accelerate standard output uh what can
we
print you step on the
gas then maybe break void
break standard output
you step on the
brakes then be sure to add a semicolon
to the end of your class because I
always forget to do that okay we now
have a car class it acts as a blueprint
to create car objects to create an
object we would type the name of the
Class Car in this example then a unique
identifier for the object let's say car
one then we can assign some of the
attributes of this car object car 1.
make maybe
Ford car
one.
model equals Mustang I like
Mustangs car 1. year equals
2023 then a color car 1. color maybe
silver okay then just to test these
let's print these
attributes standard output car one. make
I'll add a new
line let's copy this line paste it three
times then we'll display the model year
then
color okay our car object is a Ford
Mustang the year is 2023 the color is
silver not only does our car have
attributes but it has methods actions it
can perform as well our car can
accelerate and it can break Let's test
that car
1.
accelerate car 1.
break okay you step on the gas you step
on the brakes then if I need a second
car object I can type car car 2 then I
can assign the attributes and I have
access to its methods so yeah that's an
object everybody it's a collection of
attributes and methods attributes are
characteristics of an object methods are
functions that an object can perform so
yeah those are objects everybody in the
next video we're going to cover
Constructors your assignment is to post
a class in the comment section down
below so yeah that's an introduction to
object-oriented programming in
C++ hey everybody welcome back so in
today's video we're going to discuss
Construction S A Constructor is a
special method within a class that is
automatically called when an object is
instantiated it's useful for assigning
values to attributes as arguments before
when we were assigning attributes to an
object we would say for example car
1. make equals Ford well with a
Constructor we can do that automatically
here's an example this time let's create
a student class
class
student I'll add a public access
modifier what attributes Should students
have how about a name standard string
name int age double GPA sounds good to
me then if I need to create a student
object I would type the name of the
class student a unique identifier for
this specific object let's say student
one
then to assign some of the attributes
right away I could use a Constructor we
do have a Constructor that is
automatically called behind the scenes
but we could explicitly set one up the
Constructor has the same name as the
class in this case student add a set of
parentheses add a set of curly braces
think of this as a function we can set
up parameters when we instantiate a
student object we will automatically
call this function the instructor then
pass arguments let's set up some
parameters we have standard string
name int AG double
GPA then when I instantiate a student
object I will add a set of parentheses
after the object name then pass in my
arguments let me just zoom in real quick
okay in order to instantiate a student
object we need to pass in a name an age
and a GPA so for the first student
student one's name will be SpongeBob his
age will be I don't know how old
SpongeBob is let's say he's 25
SpongeBob's GPA will be a solid
3.2 when we instantiate our student
object we will pass these values as
arguments to the Constructor now to
assign these attributes with these
parameters we first need to select these
attributes in this example I gave them
the same same name just to remove
ambiguity if I'm referring to these
attributes I will type this then an
arrow name equals the name of the
parameter
name this name equals my name
parameter this Arrow age equals my age
parameter this Arrow GPA equals my GPA
so now let's test this I will display
student 1's name age and
GPA standard
output student
one. name add a new
line then we have
age then
GPA okay we got SpongeBob he's 25 years
old his GPA is 3.2 so you can see that
we don't need to necessarily add these
values to these attributes manually you
can do that automatically with a
Constructor so another way in which you
may see this Constructor set up is with
the parameter names being different from
the attribute names perhaps instead of
name age and GPA let's say X Y then Z if
the attribute names are different from
the parameter names you don't need the
this
keyword you could say name equals x age
equals y GPA equals z and this would
work
too if you prefer this way of doing
things you can do that uh just my own
personal preference I like to use the
this keyword and then keep my parameters
the same but that's just me you do you
let's create a couple more students and
it's kind of nice because we can reuse
this Constructor let's create student 2
student student
2 student two will be Patrick I don't
know how old Patrick is let's say
Patrick is
40 uh Patrick's GPA will be
1.5 okay to test this let's display
student 2's name age and
GPA okay we got Patrick he's 40 years
old GPA is 1.5 one last student student
student 3 student 3 will be Sandy Sandy
is uh how about 21 years old and sy's
GPA is a perfect
4.0 okay now we'll display student 3's
name age
GPA okay we got Sandy her age is 21 GPA
is 4 well 4.0 let's do one last example
just to reinforce our understanding of
Constructors let's create an entirely
new class let's go back to our car class
I'm going to get rid of all this so we
need a class class
car set of curly braces add a semicolon
to the end I will add a public access
modifier in the last topic we decided
that cars had four attributes a make
standard string
make a model standard string
model in
year standard string color
now we'll create a Constructor for our
car objects it has the same name as the
class name car set of parenthesis set of
curly braces we can set up some
parameters we have make model year and
color I think I'm just going to copy
this to save time you can rename these
if you
want but I like to keep them the
same then I will assign this Arrow make
equals
make this Arrow model equals
model
this Arrow year equals
year this Arrow color equals color when
we create a car object we'll need to
pass in these
arguments I will create car car one add
a set of parenthesis pass in my
arguments a make model year and color
I'll create a
Chevy
Corvette the year will be
2022 the color is
blue I'm going to display the attributes
standard output car 1. make I'll add a
new line then I will display the model
year then color
color
model year
color car one is a Chevy Corvette the
year is 2022 the color is blue let's
create a second car car car
2 Car 2 will be a
Ford
Mustang the year will be 2023 the color
will be read I will display c2's
attributes we have a Ford Mustang the
year is 2023 the color is red so yeah
that's a Constructor everybody a
Constructor is a special method that is
automatically called when an object is
instantiated it's useful for assigning
values to attributes as arguments when
you create an object from the class add
a set of parentheses then add your
arguments within the construct you can
assign those arguments to the attributes
of that class in the next topic we'll
cover overloaded Constructors if you're
looking for some additional practice in
the comment section down below post a
class that contains a Constructor and
well yeah those are Constructors in
C++ overloaded Constructors are when we
have multiple Constructors with the same
name but different parameters they allow
for a varying number of arguments ments
when instantiating an object here's an
example we'll create Pizza objects from
a pizza class let's type Class Pizza add
a set of curly braces a semicolon to the
end will make our members publicly
accessible so pizzas they can have a
variable number of toppings right you
can have no toppings one topping two
toppings three toppings suppose we have
just one topping to begin with topping
one and that will be of the string data
type standard string topping
one then I will create a pizza
Constructor it has the same name as the
class name Pizza parentheses curly
braces we'll set up some
parameters standard string topping one
in order to construct a pizza we have to
pass in one topping so let's do that we
have pizza pizza one and I will pass in
one argument for a topping I feel like
pepperoni then we'll just need to assign
this argument to this
attribute this Arrow topping one equals
topping one the name of this parameter
then to test this let's display topping
one standard
output Pizza one do topping
one okay we have pizza 1 that contains
pepperoni now what if if you would like
a pizza that has two toppings suppose we
have pizza 2 Pizza Pizza 2 this time I'm
going to attempt to pass in two
arguments how about
mushrooms and
peppers well when I run this
program we're going to have an error
error no matching function for call to
Pizza with two
arguments we can create an additional
Constructor that accepts different
arguments let's copy what we have and
paste it this Constructor will take two
string arguments topping one and Topping
two so we have two toppings this time
and I should probably create another
attribute for a second topping standard
string topping
two this topping two equals topping
two so now with pizza 2 let's display
topping one as well as topping
two now Pizza 2 contains mushrooms and
peppers what if you would like a pizza
with no toppings like a plain cheese
pizza well we could set that up pizza
pizza
3 I'm going to attempt to add a set of
parentheses after Pizza 3 but pass in no
arguments but we have a warning our
compiler is saying we should get rid of
the
parentheses if we're passing in no
arguments we don't need that set of
parentheses but we still have an error
here no matching function call for pizza
with no
arguments if we're creating an object
and passing in no arguments we'll need a
matching Constructor so at the top I'll
create a a pizza Constructor with no
arguments and that should make that
error go
away so this should run and compile just
fine then yep no errors so yeah those
are overloaded Constructors you can have
multiple Constructors with the same name
as long as the parameters are different
we have three Constructors with the same
name we can create a pizza with no
toppings one topping or two toppings
overloaded Constructors allow for
multiple objects with a varying number
of attributes if you're looking for some
additional exercises post a class with
overloaded Constructors in the comment
section down below and well yeah those
are overloaded Constructors in
C++ hey everyone let's talk about
Getters and Setters Getters and Setters
are used within this concept of
abstraction where we hide any
unnecessary data from outside of a class
Getters are functions that make a
private attribute readable Setters are
functions that make a private attribute
writable here's an example I'm going to
create a stove object class
stove then I will instantiate a stove
object stove stove in previous topics
when we created attributes we would use
the public access specifier then write
any attributes in this example let's say
int
temperature I'll go ahead and set this
to zero right away since this attribute
temperature is public it's accessible
from outside of the class that means
that people can change it for example I
will take my stove object set the
temperature attribute to a really high
setting that doesn't exist like a
million this is
fine then I can display the temperature
standard
output the
temperature
setting
is stove.
temperature the temperature setting is 1
million I don't want people to mess with
my temperature attribute what I could do
instead is set these attributes to be
private we're following that rule of
abstraction we're hiding any un
necessary data from a user that they
don't need we no longer have access to
this temperature attribute from outside
of the class you can see we have some
red
underlines temperature is private within
this context this is a hidden attribute
from the outside world if I need access
to the value found within this
temperature I can write a getter it's a
function that will make an attribute
readable I'll add a public access
specifier then write a getter we're
returning an
integer I'll write get then the
attribute name
temperature all I'm going to do is
return our
temperature I can no longer update or
change the temperature it's readable but
not writable so I'm going to turn this
line into a
comment in place of accessing this
attribute directly I'm going to invoke
the get temperature
method stove. getet temperature add a
set of
parentheses now the current temperature
setting is set to zero adding a getter
will make an attribute readable if you
need a private attribute to also be
writable you can add a Setter void set
temperature this Arrow temperature
equals our temperature that we pass in
then we just need a parameter int
temperature in order for a user to
change the temperature they would need
to invoke the set temperature
method then they can pass in a new
temperature using this Setter they can
still set the temperature to whatever
they want like a million in the previous
example the temperature setting is set
to 1 million within a Setter we can add
some additional logic or checks before
we do set the temperature let's check to
see what the temperature
is if the temperature the user passes in
is less than
zero we will set this temperature to be
zero else
if the
temperature is greater than or equal to
10 suppose this is a knob with different
settings the numberers 0 through 10 this
temperature equals
10 in case they type in a million it'll
just max out at
10
else this temperature equals
temperature I could attempt to set the
temperature to a million but it would
just max out at 10 or we could try a
negative number like
-3 well now the temperature setting is
set to zero as if the stove was off or
anything in between maybe five something
right in the the
middle the temperature setting is five
so yeah that's kind of the purpose of
Getters and Setters they make a private
attribute either readable or writable or
both if you use both one additional step
you can take too is that if you have a
Constructor you can invoke the Setters
within a Constructor within my stove
class I have a Constructor if we were to
receive a
temperature we could set the temperature
right away so we already have this line
of code within our Setter so we don't
necessarily need this line again we
would instead invoke the
setter set temperature pass in our
temperature then if I was to instantiate
a stove object I would have to pass in a
temperature I'll set it to be
zero and this temperature setting is set
to zero so yeah those are Getters and
Setters everybody a getter makes a
private attribute readable a Setter
makes a private attribute writable
within the Getters and Setters you can
perform additional checks or logic which
is pretty nice if you're looking for
some additional practice post a class
that has a getter and Setter in the
comment section down below and well yeah
those are Getters and Setters in
C++ hey guys let's talk about
inheritance inheritance is when a class
can receive attributes and methods from
another class the receiving class is
known as a child class the class that's
being inherited from is known as the
parent class it's kind of like how
children will inherit their parents
genes and some of their physical traits
it's kind of the same concept a benefit
of inheritance is that it helps to reuse
similar code found within multiple
classes here's an example we will create
an animal class the animal class will be
the parent class class animal
I'll make these members publicly
accessible all animals will have a
Boolean attribute that we will name
alive if you're an animal you're alive
then let's add a method maybe an eat
method all animals should be able to
eat
void
eat we'll just print a generic message
standard
output this animal is is
eating I'm going to create two classes a
dog class and a cat class they will
inherit from the animal
class let's begin with dog class dog to
inherit from another class you would add
a colon then public the name of the
parent class dog will inherit from the
animal
class then out of curly braces semicolon
add at the end and we now have a dog
class now check this out if I create a
dog object it will have a Boolean
variable named alive as well as an eat
method so let's create a dog object dog
dog so I'm going to display that Boolean
variable dog.
alive if I display this
attribute this will give me one which
means
true this dog object also has an eat
method dog do eat add aide of
parenthesis to invoke
it this animal is
eating so even though there's nothing
within this dog class it's inheriting
everything from within the animal class
and we could add some additional
attributes and methods as well maybe
just a method this time I would like to
give my dog the ability to speak so
let's make this public
void maybe
bark standard
output the dog goes
woof my dog is alive and it can eat my
dog can also bark as well it has its own
attributes and methods too I would like
my dog to
bark okay my dog is alive that's set to
one the animal is eating the dog goes
woof so now let's create a cat
class class cat the cat class will
inherit from the animal
class I'll make its members publicly
accessible I will give cats a meow
function void
meow standard
output the cat goes meow
there okay now we can create a cat
object Cat Cat Let's print the alive
Boolean variable of my
cat cat. eat now I'm going to try and
use the bark method of a cat which we
don't have let's attempt to use that so
class cat has no member named bark
that's because that method is found
within the dog class and not the cat
class cats have a meow method I'm
instead going to use the meow
method are cats alive the animal is
eating the cat goes meow so that's kind
of how inheritance Works a class can
inherit attributes and methods from
another class it helps with code
reusability you know technically you
could add these attributes and methods
to each of these classes for
example I'll just add the Boolean
variable alive to each of these
classes as well as the eat method
you know this would work too but we're
repeating ourselves and with programming
we try not to repeat ourselves if we
don't have to especially because if we
have to make a change to the eat method
let's change eat to n Nom Nom well I
would have to go to each class and make
that change manually and that can be
inconvenient if I have hundreds of
different classes it would be a lot
easier if I just had to make that change
in one place so I'm going to revert all
those changes
if I need to make a change to one of
these methods I'm going to change e to
display n Nom
Nom well then I just have to make that
change in one place instead of for every
individual class let's try another
example we'll create a class named shape
this will be the parent
class we'll make the members publicly
accessible any class that inherits from
the shape class will have a double
attribute that we will name area for
surface area double volume in this
example we won't have any methods this
time just some attributes I'm going to
create class Cube cube is the child
class it will inherit from the parent
class shape so
colon public the name of the parent
shape even though there's nothing within
my Cube class my Cube class has an error
area and volume
attribute then let's make a sphere class
class
sphere there we go I'm going to add a
public access modifier all cubes will
have a double side property then with
spheres they will have Double Radius
then I'm going to add a Constructor for
both cubes and spheres let's begin with
Cube Cube
then
sphere in order to instantiate a cube
object I need to pass it aside as an
argument when I construct an
object double
side then for the sphere we need a
radius Double Radius I think what we'll
do is that when we construct a cube
object and a sphere object we'll
calculate the area and the volume based
on either the side that we pass in for a
cube or the radius for a sphere let's
begin with the cube first let's assign
the length of a side remember with a
cube the length the width and the height
are all the same this Arrow side equals
side to calculate the area we can use
this formula so this area
equals side * side * 6 because there's
six sides to a cube then if you need the
volume you could say this Arrow volume
equals side to the^ of three we could
just say side time side time side just
to keep it
simple now with the sphere it's a little
more complex first let's assign the
radius this Arrow radius equals
radius let's calculate the area of a
sphere this Arrow area equals to
calculate the area of a sphere that
would be 4 * Pi let's just say
3.14159 time radius
squared so radius time
radius then let's calculate the volume
this Arrow volume equals to calculate
the volume of a sphere the formula is 4
/ 3 * pi * radius cubed so that would be
4 / 3.0 make sure to divide by 3.0 and
not 3 because in this case we would be
using integer division we would like to
keep that decimal so
3.0 time Pi that's
3.14159 time radius cubed to keep it
simple we can say radius time radius
time
radius and there we
go okay so let's create a cube object to
begin with
Cube I'll name this this object just
Cube then in order to construct a cube
object we need to pass in the length of
a side let's say
10 so my Cube class inherits the area
and volume attribute from the shape
class within the Constructor of the cube
class we will calculate what the area
and the volume is going to
be and I will display that standard
output
area q
do area then I'll add
centimet then let's do the same thing
with
volume
volume cube. volume if the length of a
side is
10 the area is going to be 600 cm squar
the volume is 1,000 cm cubed now let's
try this with our sphere sphere I'll
name this object sphere then we will
pass in the radius let's say five I
would like to display the sphere's area
and the sphere's
volume the area would be 314 cm squared
the volume is 523 cm
cubed so yeah that's inheritance
everybody a class can inherit attributes
and methods from another class if you
have multiple classes and they share
similar attributes or methods you can
place them within a parent class and all
of those individual classes can inherit
from that one common class it helps with
code reusability and you don't have to
repeat yourself if you're looking for
some additional practice post a parent
class and a child class in the comment
section down below and well yeah that's
an introduction to inheritance in C++
Loading video analysis...