hey guys in this video you're going to write your first c plus 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 gonna tell you why you need to learn c plus plus c plus plus is a fast language like really fast it's commonly used in advanced graphics applications a few examples would include adobe applications video editing software anything that's graphics intensive c plus plus 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 plus plus is a middle level language programming languages tend to be on a spectrum the higher level of programming languages 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 c-sharp are very easy to write with and to understand but they tend to be slower c plus 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 plus plus 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 vs 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 vs code but feel free to use any text editor that you're comfortable with secondly we'll need a compiler a compiler 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 clang okay clang has a really cool logo it's blue eyes white dragon so let's get started well alright then everybody now we are going to download vs code that text editor i was talking about head to this url code.visualstudio.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 vs code there's two extensions i would recommend go to the left toolbar underneath extensions we will look up c c plus plus 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 plus projects go to the left toolbar explore open folder i'll create a new folder on my desktop new folder i'll name this c plus projects that sounds good to me then select folder within this folder we'll create a new file i'll name this hello world dot cpp make sure to get that cpp extension at the end that means it's a c plus plus file okay we now have a c plus 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.visualstudio.com docs let's head to c plus plus 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 clang 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 v 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 min gw64 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 5 we will type pack man dash capital s y u 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 sys2 then type this command pack man dash s u 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 dash s dash dash needed base dash dev l min gw dash w 64 dash x 86 underscore 64 dash tool chain then enter then just hit enter proceed with the installation type yes type y enter again then give it a moment then we can close out of this window we'll have to find the bin folder of mingw it's likely going to be within your c drive go to msys64 mingw64 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 plus dash dash 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 plus plus program at the top of our c plus file we are going to type include within angle brackets io stream iostream is a header file that contains functions for basic input and output operations by writing include iostream 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 parentheses 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 0 then add a semicolon if we reach return 0 that means there were no problems in this program however if one is returned that means there was a problem there is an issue so place return 0 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 altogether 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 ctrl 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 output uh oh 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 double left angle brackets for output std colon colon en 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 backslash n 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 endline is that endline 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 forward 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 plus 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 x equals 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 equals six then let's display whatever y is i'll add a new line let's copy this paste it okay x is five y is six we could even do something like this let's say int sum equals x plus y then we'll display whatever our sum variable is c out sum the sum of x plus y is 11. now there's different data types depending on what you need to store within 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 inch age equals 21. let's think of two more examples what about a year int year equals 20 23 how about days int days equals seven the int data type can only store a whole 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 in either celsius or fahrenheit then let's display maybe price price yeah and that decimal portion is not truncated much 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 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 c 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 booleans boolean a variable that's boolean has only two states true or false to create a boolean variable you type bool 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 bull student equals true if they're not enrolled in classes or they graduated you could set this to be false think of a light switch the light switch can either be on or off you can say a light switch is boolean there's only two states true or false how about bull 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 bool for sale equals true if an item in our store 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 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 one two three 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 u r 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 alright 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 plus 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 plus plus 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 read-only 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 equals five 3.14159 then we have double radius pick some radius i'll pick ten then double circumference equals and here's the formula to calculate the circumference of a circle it's two times pi times radius then we will display our circumference standard output we will display circumference then i'll add maybe centimeters our circumference is 62.83 centimeters 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 420 69 well then this is going to change the result of our program we may have not realized that somebody changed the value of pi before 2069 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 420 69 again then see what happens okay we have an error assignment of read-only 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 int light speed the speed of light in meters per second is two nine nine seven nine two four five eight let's think of one more example perhaps you're working with screen resolutions we have const int width of 1920 then const int height of 1080. these may be a few examples of variables you do not want to be changed or altered at all you only want them to be read-only yeah that's a const everybody it's a keyword that will modify a variable or some value so that it's read-only 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 it 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 namespace allows for identically named entities as long as the namespaces are different now what the heck does that mean suppose we have variable x x equals zero 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 read 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 equals two this is also valid so just to demonstrate 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 operator 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 2. so entities can have the same name as long as they're within a different namespace now one line that you may see is 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 xbond within the second namespace i would still need to prefix it with second x is two if i changed using namespace to second it's implied we're using the second namespace and i don't need that prefix 2 but i still would if i need x from the first name space 1. now there's this evil line called using it namespace std for standard now the reason that people include this line is to save a little bit of typing if we're using a 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 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 a 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 typedefs and type aliases now typedef 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 typedef 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 typedef then list the original data type so we're used to strings ins doubles well here's a really complicated 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 typedef 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 list underscore t so that's one of the main benefits of using the typedef 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 typedef 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 text underscore 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 def 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 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 typedef 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 typedef 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 typedef nowadays just because it's more suitable for templates and like i said that's a topic for another video all right everybody that is the typedef keyword and type aliases typedef 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 typedef and using keywords when there is a clear benefit so yeah that is typedefs and type aliases your assignment is to post a typedef in the comments section down below and well yeah those are defs and type aliases in c plus 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 plus 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 equal students plus one we could shorten this to students plus equals one that would do the same thing 21 if we need to add two students this would be students equal students plus two or students plus equals two 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 plus we now have 21 students you tend to see this in a lot of loops which we'll cover later okay now we have subtraction students equals students minus one there are now 19 students we could shorten this to students minus equals 1 there are 19 students if you need to subtract 2 we could say either students equal students minus 2 or students minus equals 2. that would do the same thing 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's subtraction to use multiplication you use an asterisk i'm going to double the amount of students that we have students equals students times 2. there are 40 students or we could 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 equal students divided by two there are 10 students the shorthand way is students divided by equals 2. there are 10 students now check this out we have 20 students what if i divide students by 3 we're working with an int variable so this variable can't hold any decimal portion 20 divided by 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.6 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 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 2 evenly where the remainder is 0 well it's even if the remainder is 1 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 operations that are first within parentheses then multiplication and division then lastly addition and subtraction perhaps we have this formula students equals 6 minus 5 plus 4 times 3 divided by 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 four times three first that is twelve then we have some division twelve divided by two is six then any addition and subtraction six minus five is one one plus six 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 negative seven 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 comments section down below and pin it to the top and well yeah those are some basic arithmetic operators in c plus plus 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 precede 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 output x well the value is 3. we truncated the decimal portion and implicitly converted this number into an integer what if x was of the double data type double x equals 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 double 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 the stubble x x now equals three 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 x well we will implicitly cast this number 100 as a character will convert it using the ascii 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 eight the user has eight questions that are right and 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 by questions times 100 then let's display whatever the result is standard output score then i'll add a percent sign to the end 8 divided by 10 is 0.8 right times 100 that should give us 80 uh we have zero percent well that's because we're using integer division questions is of the int 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 plus plus 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 plus plus we're familiar with c out followed by the insertion operator which is two left angle brackets well 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 because it's well for output if you're using vs code this is what we'll need to do if you're not you can skip this 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 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 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 zero years old if we need to read a string 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 parentheses 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 cn 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 getline function it accepts the newline 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 white 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 plus if you would like a copy of all this code i'll post this in the comments section down below and well yeah that's how to accept some user input in c plus hey guys in this video i'm going to show you eight useful math related functions in c plus plus 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 yet 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 as 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 c math header file at the top of our file let's include c math we have the pow function to raise a base to a given power z equals pow for power let's raise 2 to the power of 3 z would be 8 two to the power of four would be sixteen that's the power function then we have square root z equals sqrt what's the square root of nine well the square root of 9 is 3 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 negative three the absolute value of negative three would be three that is the absolute value function next we have the round function let's change x to 3.14 z equals round let's round x 3.14 rounded would be 3. if you need to round up there's a ceiling function z equals seal seal means ceiling 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 plus dot com slash reference slash c math 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 hypotenuse of a right triangle so yeah those are a few useful math related functions in c plus plus 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 equals the square root of a squared plus b squared we'll begin by declaring our variables double a double b double c make sure you include c math 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 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 power of two side c equals the square root of a plus 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 power of two plus b to the power 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 six point four 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 comments section down below and well yeah that's a simple practice project in c plus 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 parentheses 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 because 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 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 and to 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 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 negative 10 then i hit enter you haven't been born yet since this condition was false we skipped this 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 else 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 and to your age i am 120 years old i hit enter you are too old to enter the 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 comments section down below and well yeah those are if statements in c plus 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 2 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 write one i'm going to delete all of this we will type switch parentheses 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 standard 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 4 for april it is april one more time the month is 12 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 negative 42. please enter in only numbers 1 through 12. so the default case is kind of like the else statement if there are no matching cases we execute whatever's 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 parentheses 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 in a you did great what letter grade 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 comments section and well yeah those are switches in c plus 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 num1 double num2 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 will store the response within the variable op standard output enter number one standard input num1 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 because it's a character if the user wants to add two numbers we'll take result equals num1 plus num2 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 for subtraction case subtraction num1 minus num2 multiplication case multiplication num1 times num2 then division case division num1 divided by num2 what if somebody doesn't type in 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 one point two three enter number two three point one four the result is 4.37 let's run this again we will subtract two numbers 1.23 minus 3.14 is negative 1.91 let's multiply two numbers 1.23 times 3.14 that's 3.8622 now we will divide two numbers 1.23 divided by 3.14 that is 0.39172 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 plus 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 ternary 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 ternary 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's within our else statement and this would work the same if my grade 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 two 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 two 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 eight now it's even you don't necessarily need equals one or equal zero the number 1 does correspond to true and 0 corresponds to false so you could write it like this too 8 divides by 2 evenly that's even if it's 9 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 you 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 would be standard output then within a set of parentheses then we could use our canary 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 ternary 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 comments section and well yeah that's the ternary operator in c plus plus 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 temp with the andological 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 these 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 degrees this will be in celsius the temperature is good let's try it again uh what about negative 100 degrees celsius uh the temperature is bad yeah no kidding one more time uh positive 100 degrees celsius 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 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 is negative 100 degrees celsius 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 degrees celsius i should probably add some new line characters there enter the temperature it's 25 degrees celsius the temperature is good it is sunny outside if we use the not logical operator we can precede 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 it is cloudy outside else it is sunny outside let's change sunny to be false enter the temperature it is 50 degrees celsius 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 fair and height 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 left but you know maybe the user types in lowercase f i'll add an or conditional operator or unit 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 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 times our 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 minus 32 divided by 1.8 then let's display our temperature i'll copy this line of code paste it 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 fahrenheit enter the temperature in celsius so what's zero degrees celsius converted to fahrenheit that is 32 degrees fahrenheit let's go again let's convert to celsius enter the temperature in fahrenheit what's 100 degrees in celsius 37.7 degrees 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 plus plus hey what's going on everybody so in this video i'm going to explain some useful string 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 parenthesis the length method will give you the length of a string let's write this within an if statement if name dot 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 will 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 parenthesis wherever you invoke this method in that spot you will return the length of that string in characters the empty method will return if a string is empty or not type your string name dot empty parenthesis this returns a boolean value if name is empty will 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 dot clear 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 parenthesis within the parentheses we can add a string to the end of another string i'll add at gmail.com standard output your username is now name enter your name your username is yourname with at 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 dot at parentheses so the first character in a string has an index of zero i'll display whatever that character is enter 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 we'll 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 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 dot 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 zero one two three okay then lastly erase name dot 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 of 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 cplusplus.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 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 enter in 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 and to your name i'm just going to hit enter and not enter in 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 any time 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 at 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 comments section down below and well yeah those are while loops in c plus plus 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 i'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 zero is not less than 0 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 one two three the number is one two three let's type in a negative number negative one enter a positive number negative one enter a positive number negative one 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 do while 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 write 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 one nope negative one nope how about a positive number one two three the number is one two three 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 comments section down below and well yeah that's a do while loop in c plus alright 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 four 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 sequel 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 plus plus okay let's repeat something three times standard output how about happy new year happy new year 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 five okay one two three four five 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 we're starting at one then we're counting up to ten 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 2 after each iteration i plus equals 2. now we're counting up by twos one three five seven nine happy new year we can even set our index to be a different number let's begin at zero we're still counting up by twos zero two four six eight happy new year we could even increment i by three zero three six nine happy new year or we could decrement and go backwards i minus minus this time we will begin at ten then continue as long as i is less than or equal to zero so this would be a countdown ten nine eight seven six five four three two one zero happy new year okay let's decrement i by two after each iteration i minus equals two ten eight six four two zero 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 plus plus 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 we'll 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 1 standard output 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 equals 13 then we have the numbers one through twelve 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 plus 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 forward 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 and i i'll set this equal to b 1 the condition will be i is less than or equal to 10 then i will increment i by one 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 4 and i i'll set this equal to b1 i'll continue this as long as i is less than or equal to 3 then increment i by one 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 gonna 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 a 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 nested loop that we created previously so we have int rows int columns then char symbol we're gonna 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 one two three four five columns one two three four five 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 comments section down below and well yeah those are nested loops in c plus 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 parentheses 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 3231. 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 then 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 6 take the remainder and that's our number but there's one issue with this we have 5 2 and 0. technically the range of numbers is currently zero through five if we need one through six what we can do is add one plus one this should give us a random number between one 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 1. wow that's surprisingly low then i have a 14. maybe you need a random number between 1 and 100 rand function modulus 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 num1 rand function modulus 6 plus 1. then let's copy this paste it twice we have num1 num2 num3 let's display num1 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 five two two 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 comments section down below and well yeah that's how to generate some random numbers in c plus plus 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 monster 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 because we need access to the time function to work with random numbers we'll need to generate a seed srand 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 one through five but this will give us zero through four so i'm going to add one to the end my integer randomnum will be a random number between 1 and 5. i'm going to create a switch to examine this random number against many matching cases so we have case 1 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 i should probably break after these prize 2 will be a t-shirt prize three how about a free lunch prize for maybe a gift card case five concert tickets that sounds good so when i run this program we'll generate a random number between one and five depending on what that number is we'll execute the code found within one of these cases let's see what i won i want a free lunch if i try this again there's a good chance it'll be a different prize this time i want a bumper sticker i want a bumper sticker again come on i want those concert tickets i'll take 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 plus plus 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 and guess this variable will hold the current player guess and tries how many tries is it going to take for the user to guess the correct number we'll be using the s rand function to generate some random numbers pass in time pass and null we will assign our variable num a random number between 1 and 100 rand function modulus 100 then add 1. this function will give us a random number between 1 and 100 start with the 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 a 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 guess is less than num then we'll display too 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 too 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 comments 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 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 parentheses 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 i'll 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 one two three 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 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 while 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 u 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 and 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 comments section and well yeah those are functions in c plus plus all right everybody we are on the return keyword the return keyword will return a value back to the spot where you called to 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 a 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 times 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 data 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 times 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 the sequel 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 centimeters squared then new line the area of our square is 25 centimeters squared and i could change this to a different number like six the area is now 36 centimeters 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 times length times 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 centimeters cubed if the side of a square is 6 centimeters the area would be 36 if it was a cube the volume would be 216 centimeters 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 a misspelt 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 standard output hello the user'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 plus plus hey guys in this topic i'm going to explain overloaded functions in c plus plus 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 gonna 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 baked 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 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 to 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 topping 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 comments section down below and well yeah those are overloaded functions in c plus plus okay everybody we gotta 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 one 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 mynum was not declared in this scope functions can't see inside of other functions my function printnum has no idea what this mynum variable is mynum 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 int 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 mynum 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 three 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 3. 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 mynum within the main function will be 1 within the printnum function it will be 2. if i was to display my num for both of these i'm going to add a new line to each of these 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 two 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 mynum 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 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 we'll 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 gonna add some text decorations because i think that'll be cool maybe a bunch of asterisks and one more okay we have option one one show balance two will be deposit money three is withdrawal 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 three four then a default case okay case one the user wants to show their balance we'll invoke the show balance function but we need to pass in our balance balance and then we are going to break case 2 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 to 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 okay 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 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 dollars in our account i'm going to show my balance 123 dollars 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 i o 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 dollars and zero cents if i were to change this to 123.01 we should display two decimal places yep 123 dollars and one cent 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 r amount so i'm going to set balance back to zero then let's test it show balance one your balance is zero dollars and zero cents i would like to make a deposit uh 420 69 cents 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 now let's do so after withdrawal two okay let's try that again show balance zero dollars zero cents make a deposit 420.6 your balance is zero dollars and zero cents so what we're going to do is return our amount at the end of this function return amount 420 dollars 69 cents all right we have our balance the user is able to enter in negative money enter amount to be deposited negative one thousand your balance is now negative one thousand dollars 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 one thousand dollars that's not a valid amount your balance is zero dollars i'm just going to add a new line like right here then let's make a legitimate deposit deposit money i will deposit one thousand dollars in one cent your balance is one thousand dollars and one cent 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 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 one thousand dollars and one cent then let's withdraw money i will withdraw one hundred dollars and one cent my new balance is nine hundred dollars but we can overdraw our account still so i'm going to withdraw a million dollars and one cent our balance shouldn't be negative so let's prevent our user from overdrafting their account within our withdrawal 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 one million dollars and one cent insufficient funds your balance is zero okay now what if the user would like to deposit negative money withdraw money negative one thousand your balance is one thousand dollars we'll need to make sure that the amount is a legitimate amount i'll add an else if statement if amount is less than zero standard output that's not a valid amount now else we will return the amount to be withdrawn then within the elsif statement we'll need to return zero there okay let's withdraw money enter amount to be withdrawn negative one thousand dollars that's not a valid amount that's good let's withdraw again i would like to withdraw 100 insufficient 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 99.99 your balance is zero that's good then let's exit press 4 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 dot clear function so i haven't talked about this function this function will reset any error 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 plus 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 will 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 warnings 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 0 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 scissors game choose one of the following r for rock p for paper s for scissors uh i will pick w for wombo 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 one and three and num equals brand function modulus three plus one 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 1 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 omit this case 2 return the character p for paper case 3 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 will 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 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 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 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 be its rock will change this line of output to be you win if the user chooses paper and the computer chooses paper that 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 beats 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 plus 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 card that you like one card 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 one two three 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 the sequel to a camaro a chevy camaro now at parking spot number zero we have our camaro then our mustang then 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 arrays 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 1 will have our mustang cars at index 2 will be our camry see we still have an error though array size missing and 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 five dollars seven dollars and fifty cents nine dollars and ninety nine cents then fifteen dollars 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 two 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 comments section down below and well yeah those are arrays in z plus plus 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 bytes 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 eight bytes this will be helpful in the future when we begin working with arrays 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 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 byte let's try a boolean boolean student is somebody a student true or false i'll play student within the size of operator a boolean variable also takes one byte of memory this time let's find the size of an array in bytes 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 five bytes remember that characters take up one byte 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 the 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 and bytes of 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 plus alright 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 sequel 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 four parentheses curly braces we'll need an index and i i'll set the sql to zero 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 or whatever i'm going to use my counter variable i students at index of i during the first iteration i will be 0 then 1 then 2 once we reach 3 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 reaches 3. if we make any adjustments to this array we would have to go into our code and make some changes such as setting this for loop so that we discontinue when i reaches 4. 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 bytes 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 plus plus alright guys the for each loop the for each loop is a loop 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 for 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 for each loop we start at the beginning and go to the end there's less flexibility so let's change this to a for 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 for each loop it's a loop that eases the traversal over an iterable data set there's less syntax involved in a for each loop but it's less flexible if you just need to display the elements of an array a for each loop would work perfect so yeah that's a for each loop everybody your assignment is to post a for each loop in the comment section down below and well yeah that's the for each loop in c plus plus 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 15.5 cents 75 dollars nine dollars ninety-nine cents 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 arraign 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 int i equals zero 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 decays 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 the function know what the size is so let's calculate what the size is into 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 and 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 dollars and three cents 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 comments section down below and well yeah that's how to pass an array to a function in c plus plus 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 one through ten we'll probably need this later i'm going to calculate the size of the array and 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 mynum mynum 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 because 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 isn't i'll name this function search array there's a couple parameters we'll have three parameters an array of integers integer array the size of the array and 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 the sql 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 mynum 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 a for loop we'll begin at 0 into i equals 0 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 we'll return negative one in programming negative one serves as a sentinel value if you see negative one that typically means that something wasn't found we'll return either i or negative 1 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 negative one 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 that 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 4 20 69 420 69 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 int 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 getline 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 that index one hot dog hot dog is that index two 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 plus plus hey everybody in this topic i'm going to show you how we can sort an array first i'll explain the logic behind it then we'll write a c plus plus 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 the bubble sort we begin at index 0 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 temporary storage like a temporary variable take the element on the right move it to the left take whatever's 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 1 is not greater than 9 so we leave it alone then we check the next element nine is greater than two we would swap these two values i'll speed up the footage 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 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 int element in array i will display using standard output every element then i think i'll separate each with a 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 4 and i equals 0 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 minus i minus 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 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 plus one 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 at index of j equals array at index of j plus one then lastly array at index of j plus one equals whatever's 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 plus hey everybody in this topic i'm going to explain the fill function the fill function fills a range of elements 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 two three four five six seven eight nine ten 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 and 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 divided by 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 divided by 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 by three hamburgers will begin at foods plus size divided by three and end at size divided by three times two 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 fill function in c plus 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-size-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 5 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 5 and that might be a problem if we would like to enter in more than 5 items we'll discuss dynamic memory in a future video then i'm going to calculate the size of this array and size equals size of my array foods divided 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 four and i equals zero 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 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 q 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 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 sequel 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 queue 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 q 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 a for each loop let's use a standard for loop int i equals zero 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 the 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 limited 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 plus plus 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 the rays 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 three times four is twelve so that would give us twelve 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 3 to 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 a 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 car that is i'm just gonna add a space between these elements okay row zero column zero that's my mustang row zero column zero that's mustang let's print the next element that would be row zero column one that is my ford escape row zero column one i'm just going to zoom out there then we have row zero column two 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 one row one column two so this next row is our car is 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 one row two column two 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 int rows equals size of my array cars divided by the size of one of the elements cars at index 0 is good then to calculate the amount of columns that we have we can do something like this and 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 zero zero 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 and i equals zero 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 inner for 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 than 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 manufactured 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 comments section down below and well yeah those are two dimensional arrays in c plus plus hey everybody in this video we're going to create a quiz game using c plus plus 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 into mind for me what year was c plus plus created okay that is the first question i'll add an additional string question two who invented c plus plus third question what is the predecessor of c plus plus and i couldn't think of a fourth question so i'm gonna 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 plus plus guido van rossum he's the creator of python so that's not the correct answer yarn stro strip i'm sorry if i mispronounce your name dude hopefully you're not watching right now uh b is the correct answer in this case c john carmack d mark zuckerberg we're on question three what is the predecessor of c plus plus the correct answer is c that would be option a c plus c minus minus or b plus plus 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 bjorn strosstrup 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 and size equals the size of our array questions divided by the size of one of the elements questions at index zero we'll create a character to hold our guess and score to hold the score now we'll need to iterate over our questions for let me move down here and i equals zero 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 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 inner for loop for that we'll need a different index i is already taken let's pick j inch j equals zero 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 plus created who invented c plus plus what is the predecessor of c plus plus 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 to 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 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 try this so far what year was c plus plus created c who invented c plus plus that would be b what is the predecessor of c plus plus 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 gonna 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 gonna work because we're using integer division but i'll explain that momentarily about typecasting 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 zero percent even though we got one right we'll need to add a cast to the divisor 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 twenty five percent now let's go for a hundred remember that the correct answers are c b a b 1985 bjorn strostrop the language c but that's option a is the earth flat no b correct guesses four number of questions four score one hundred percent well yeah everybody that is a quiz game you can make in c plus plus 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 comments section down below and that is a quiz game written using c plus hey everybody welcome to the exciting world of memory addresses a memory address is a location in memory where data is stored in c plus a memory address can be accessed with an ampersand known as the address of operator suppose we have some variables i'll create a string the variable name will be well named assign this a string of text i'll create int age set sql 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 hexadecimal so these are kind of like street addresses hey for fun let's decode these to decimal you can easily find tools online to convert hexadecimal to decimal let's see what these numbers are here are the hexadecimal 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 byte 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 byte of memory that's why the distance between the memory address of age and student is only one forty minus thirty nine is one integers take up four bytes of memory 44 minus forty is four four 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 comments section down below and that is an introduction to memory addresses in c plus all right everybody so i'm gonna 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 will need the help of a temporary variable at temp to swap two variables we would assign a temp equal to x x equals y y equals 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 and y and all we're doing is switching the two copies and not the original values so that's passed 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 addressof 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 swap 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 plus 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 read-only 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 parameters in action i have standard string name assign your first name then int 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 const 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 zero 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 read-only 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 read-only 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 alright everybody those are const parameters they are parameters modified by the const 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 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 plus 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 as four nine doubled as 18. since we have the number 18 that's two digits we need to split them we'll split 18 to 1 and 8. then 6 doubled is 12. we'll split that step 2 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 2 and steps 3 29 plus 21 that equals 50. step 5 if step 4 is divisible by 10 that number is valid we could say our result modulus 10 if that number is divisible by 0 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 will 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 xero 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 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 into i equals then we'll need to find the size of our card number there's a built-in function for that card number dot 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 minus two the very last digit would be minus one 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 two i minus equals two 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 i times two 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 ascii 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 ascii table the character 0 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 0 or its equivalent 48 that would give us a range of numbers zero through nine 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 zero through nine according to the ascii 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 nine times two is eighteen we need to split those two numbers to get one and eight so i'm going to return number modulus 10 plus number divided by 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 eighteen nine times two eighteen modulus ten would give us eight eighteen divided by ten that would give us one since we're using integer division one modulus ten is one eight plus one is nine 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 can just copy all this then paste it but there's a couple changes to make int i equals card number dot size function minus one we need to begin at the end and then sum plus equals card number minus zero 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 mostly for practice if you would like a copy of this code i'll post this in the comments 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 plus 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 to door 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 we'll 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 to 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 of the string data type then type asterisk that dereference 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 dereference 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 into 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 dereference operator p age equals the address of age then let's display whatever value 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 one pizza two pizza three pizza four then pizza five 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 dereference 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 plus 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 pointers 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 dereference 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 equals one two three i would just take my pointer set the sequel to the address of my variable if you dereference a null pointer it can lead to undefined behavior or if you dereference 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 null 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 null 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 dereference operator pointer so my pointer contains the number one two three if i were to dereference this null pointer that would lead to undefined behavior i have no idea what's gonna happen don't try this at home kids 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 because that can lead to undefined behavior so yeah everybody those are null pointers in c plus hey guys in this topic we're going to create a game of tic-tac-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 to an 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 function declarations so after the main function let's paste these we do need to return some value for check winner and check tie 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 spaces the size will be nine nine spaces will 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 else computer pick a character for the computer let's begin with o boolean running i'll set the sequel to true when we begin our game we will immediately invoke the drawboard 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 dropboard function we will display a grid so let's write something like this standard output i'll add five spaces one two three four five then a vertical bar five spaces again one two three four five vertical bar one two three four 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 numbers three four five then 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 seven eight let's copy one of these empty lines paste it underneath uh 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 drawboard function we can close out of this we're done with it when we invoke the drawboard 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 drawboard 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 i'll create a local variable named number the user will enter in a number between one and nine 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 eight 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 one through nine 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 one and nine 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 player's marker then we'd 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 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 uh negative one okay so we're limited to the numbers one through nine even if i were to type zero we still can't uh so let's try something in the middle that would be one two three four five yeah and there's our marker i'm just gonna 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 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 parentheses 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 the sequel to rand function modulus nine number will be random between zero and eight 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 the sql 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 try it 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 arguments our 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 right down here we'll need to check all of the different win conditions they're 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 ternary 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 0 is equal to the player's marker ternary operator like we're asking a question if the player occupies the first row then we'll print standard output u win otherwise standard output you lose then 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 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 space is at index 3 is not equal to an empty space and space is at index 3 is equal to spaces at index four and spaces at index four is equal to spaces at index five then does spaces at index three 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 space is at index six six is six equal to seven and is seven equal to eight so these conditions will check all of the rows then we'll need columns let's copy one of these elsif statements paste it so we have 0 0 is 0 equal to 3 and is three equal to six okay now time for the second column space is at index one one right here as well is one equal to four and is four equal to seven copy this again paste it then we have the third column two two is two equal to five and is five equal to eight okay now the diagonals space is at zero zero is zero equal to four and is four equal to eight then the last diagonal space is at index two two is two equal to 4 and is 4 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 gonna try and lose one two four seven 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 main function after our if statements we'll add else if we'll invoke the check tie function pass in our spaces check tie 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 2 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 four and i equals zero we'll continue this as long as i is less than nine 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 gonna try and get a tie this time one two six seven eight 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 comment section down below and well yeah that's a game of tic-tac-toe using c plus 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 the reference operator p num now it's good practice 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 the sql 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 pnum 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 dereference 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 dereference operator p number 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 someplace 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 the sequel to null if we're not going to assign this pointer right away then to dynamically create an array we will take our pointer set the sql 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 int size will 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 and i equals zero i will continue this as long as i is less than size increment i by one standard output enter grade number i plus 1 because i will be 0 to begin with and i'm just going to add colon space afterwards standard input p grades that's our pointer now we can either add plus i or use those straight brackets at index of i either way let's display all of the grades and i equals zero i is less than size i plus plus 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 p 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 plus hey guys i gotta 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 coderight 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 a 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 void 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 int i equals zero 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 1. 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 an 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 end result this will be a local variable i'll set this equal to one i'll create a for loop and i equals one 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 ten that would be three million six hundred twenty eight thousand eight hundred 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 1 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 ten is three million six hundred twenty eight thousand eight hundred 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 plus hey everyone let's discuss function templates 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 and y will return i'll use the ternary 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 to 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 1 and the character 2. technically we could use the max version that accepts integers because there's an associated ascii 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 2. 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 w x 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 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 plus well okay then everybody we gotta 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 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 axis operator i'll assign the name member and set the sequel to spongebob i'll assign student one's gpa student1.gpa i'll give spongebob a solid 3.2 then i could set his enrolled status student one dot enrolled i'll set this to be true then we could access these members i'll display them standard output student1 dot name i'll add a new line let's do the same thing with gpa and enrolled student1.gpa student1.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 1 corresponds with true 0 corresponds with false enrolled is 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 two's members student2.name student2.gpa then student2.enrolled these first members correspond with student1 spongebob 3.2 one for true the second set is for student two 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 student3 student3.name student3.gpa student3.enrolled student 3's name will be squidward squidward has a gpa of 1.5 let's set enrolled to be false then display student three's members student three dot name student three dot gpa student three dot enrolled and here are student threes members squidward 1.5 and 0 that means false now with members you can set a default value i'll 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 1. with members you can set a default value so yeah those are structs it's a structure that groups related variables under one name structs 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 axis operator so those are structs your assignment is to post a struct in the comments section down below and well yeah those are strucks in c plus hey everybody in this topic i'm going to show you how we can pass a struct to a function in c plus plus 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 end here then a color standard string color then let's go ahead and create two car strucks how about car car one car car two then we'll assign the members car one dot model pick a model of a card that you like then a year and a color let's do the same thing with cartoon car 2. model car 2.ear car 2.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 dot model should probably add a new line too then do the same thing with year and color car dot ear car dot color let's test this by printing car one print car 1 we will pass the name of a struct as an argument 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's red now with structs they're passed by value rather than pass 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 car 1 before and within the function standard output address of operator car 1 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 passed 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 1 and car 2. this time let's change one of the members within a function let's create a function to paint car paint it 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 dot 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 struck and a new color let's paint our mustang silver then let's paint cartoon 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 strucks and change 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 plus hey everybody we gotta talk about enums enums also means enumerations it's a user-defined 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 do 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 enum 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 zero monday equals one then we'll just continue on 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 gonna change today to be friday case zero is sunday monday is one two three four five six it is friday so that also works but i don't think it's as readable another cool thing with enums is that enum variables take only one value of the set if i try and make up some value like 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 two three kind of like what i did up here but we explicitly assigned to 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 user-defined 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 comments section down below and well yeah those are enums in c plus plus 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 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 axis modifier we'll learn about axis 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 eat method void eat i'll just display a message standard output 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 axis modifier which is a dot name equals rick then human one's occupation equals scientist human one's age equals 70. let's verify that this worked by printing out these attributes standard output human one dot name i'll add a new line then let's repeat this for occupation and age human one dot occupation human dot 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 structs 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 human1 and let's have human one eat so humanone dot eat add a set of parentheses to invoke this method okay this person is eating let's also test drink and sleep human one dot drink human one dot 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 to i'm going to copy these lines let's change human one to human two human two'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 ok human 2's name is morty their occupation is a student morty is 15 years old then morty 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 two i'll display the attributes of human one first then human two human one dot name occupation age then we have human two'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 axis 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 one dot make maybe ford car one dot model equals mustang i like mustangs car one dot year equals 20 23 then a color car one dot color maybe silver okay then just to test these let's print these attributes standard output car one dot make 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 car1 dot accelerate car one dot 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 two 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 plus hey everybody welcome back so in today's video we're going to discuss constructors 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 one dot make equals ford well with the 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 student1 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 constructor then pass arguments let's set up some parameters we have standard string name int age 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 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 aero gpa equals my gpa so now let's test this i will display student one's name age and gpa standard output student1 dot 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 the 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 two student student two 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 twos and name age and gpa okay we got patrick he's 40 years old gpa is 1.5 one last student student student three student three will be sandy sandy is uh how about 21 years old and sandy'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 for 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 and 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 parentheses 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 1 add a set of parentheses 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 car1 dot make i'll add a new line then i will display the model year then color model year color car 1 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 red i will display cartoons attributes we have a forward 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 a class add a set of parentheses then add your arguments within the constructor 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 comments section down below post a class that contains a constructor and well yeah those are constructors in c plus overloaded constructors are when we have multiple constructors with the same name but different parameters they allow for a varying number of arguments 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 we'll 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 dot topping one okay we have pizza one that contains pepperoni now what if you would like a pizza that has two toppings suppose we have pizza two pizza pizza two 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 two let's display topping one as well as topping two now pizza two 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 three 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 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 comments section down below and well yeah those are overloaded constructors and c plus 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 dot temperature the temperature setting is one 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 unnecessary 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 dot get 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 numbers 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 ten or we could try a negative number like negative three well now the temperature setting is set to zero as if the stove was off or anything between maybe five something right in 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 and c plus 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 well just print a generic message standard output this animal 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 that is out of curly braces semicolon 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 dot alive if i display this attribute this will give me one which means true this dog object also has an eat method dog.e add a set of parentheses 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 dot 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 cat's 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 nom 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 it to display nom 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 area and volume attribute then let's make a sphere class class sphere there we go i'm going to add a public axis 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 in a side 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 times side times six because there are six sides to a cube then if you need the volume you could say this arrow volume equals side to the power of three we could just say side times side times 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 times pi let's just say 3.14159 times radius squared so radius times radius then let's calculate the volume this arrow volume equals to calculate the volume of a sphere the formula is 4 divided by 3 times pi times radius cubed so that would be 4 divided by 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 times pi that's 3.14159 times radius cubed to keep it simple we can say radius times radius times radius and there we go okay so let's create a cube object to begin with cube i'll name 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 cube dot area then i'll add centimeters then let's do the same thing with volume volume cube dot volume if the length of a side is 10 the area is going to be 600 centimeters squared the volume is 1000 centimeters 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 5. i would like to display the spheres area and the sphere's volume the area would be 314 centimeters squared the volume is 523 centimeters 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 comments section down below and well yeah that's an introduction to inheritance in c plus