Transcript for:

welcome to the ultimate c plus plus course in this course you're going to learn everything you need to know about c plus from the basics to more advanced concepts so by the end of this course you'll be able to write c code with confidence if you're looking for a comprehensive easy to follow well organized and practical course that takes you from zero to hero this is the right suit course for you you don't need any prior knowledge of c plus or programming in general everything you need to know about c plus is in one place so you don't need to jump back and forth between random tutorials my name is mash hamadani i'm a software engineer with over 20 years of experience and i've taught millions of people how to code through this channel and my online school codewithmatch.com if you're new here be sure to subscribe as i upload new videos all the time now let's jump in and get started [Music] before we start coding let's spend a couple of minutes and talk about c plus plus what you can do with it and how to master it c plus is one of the most popular programming languages in the world and is the language of choice for building performance critical applications video games device drivers web browsers servers operating systems and so on that's why it's used by large companies like adobe google microsoft netflix and even government agencies like nasa just to name a few every three years we get a new version of c plus plus and the latest version at this time is version 20. the next version is coming out next year now there are people like our famous superstar developer john smith who think that c plus plus is no longer relevant because of the newer languages like java or c sharp that is not true c plus is still one of the fastest and most efficient languages available so if you want to build an application that needs to be fast and use memory efficiently c plus plus is a great choice this is an advantage that it has over languages like c sharp and java c plus plus is also one of the first languages often taught to computer science or software engineering students because it has influenced many programming languages like c-sharp java javascript typescript dart and so on so if you're looking for a job as a software engineer learning class plus is a great investment and opens a lot of doors for you according to indeed.com the average salary of a c plus plus programmer in the us is just over 170 000 a year now to master c plus plus there are two things you need to learn one is the c plus language itself meaning the syntax or the grammar of this language the second thing you need to learn is the c plus plus standard library or stl which is a collection of pre-written c plus plus code that provides functionality that is required by many applications examples are data structures like lists and maps and algorithms for searching and sorting data these functions are required in almost every application so instead of us creating all this functionality from scratch every single time we can reuse some of the c plus plus code in this library to quickly build applications in this course we'll explore major functionalities in the standard library but the standard library is huge so we'll only scratch the surface if you want to learn more there are books specifically written on this topic now a lot of people find c plus plus a bit extensive and intimidating but in reality you don't need to learn all of c plus to be able to write substantial programs for the same reason you don't need to learn every feature your tv provides just to use and enjoy it so in this course we're going to explore c plus plus step by step and as we go i'm going to show you how you can write some really cool programs as you're learning c plus plus i'm going to give you plenty of exercises to help you better understand and remember the concepts then you will see that c plus plus is not really that difficult so if you follow along by the end of this course you'll be able to write c plus code with confidence all right next we're going to talk about the tools you need to write c plus plus programs [Music] to create c-plus bus programs we use an integrated development environment or ide which is basically an application that contains an editor for writing code as well as build and debugging tools now there are so many different ideas out there some of them are free the others are commercial but the top three ones are microsoft visual studio for windows the community edition is free you can get it from the link on the screen there is also a mac version but the one on the mac is not really that great for mac you can use xcode which you can get from the app store we also have clion which is cross platform so it runs on windows mac and linux you can trade for free for 30 days but then it requires a license if you don't want to pay for a license you can use one of the free alternatives again there are so many different ideas available for creating c plus plus programs in this course i'm going to use c lion but you don't have to use it to follow along you can use any tool you prefer because our focus here is not on tooling it's on the c plus plus language itself now if you're an absolute beginner and you have never coded before i recommend you to download the free version of client so you can easily follow along and then later you can either get a license or use one of the free alternatives so head over to jetbrains.com clion slash download again you can see we have versions for windows mac os and linux just note that if you're on mac make sure to download the right dmg because here we have two different builds one is for intel the other is for apple silicon so depending on the type of processor that your mac uses make sure to download the right dmg because the difference in performance is significant all right so go ahead and install this in the next lesson we're going to create our first c plus plus program together [Music] so the first time you open c lion you're going to see this pop-up box for activating your license for now just select start trial now you need to log into your jet brands account so over here you can either sign in or create a new account it's really simple it's only going to take a minute or two so i'm going to sign in with my account good now back to client we can start our trial now on this page we're going to click on new project now on the top we can specify the location of this project so on my mac it's going to be on users slash my name slash client project i'm going to call this project hello world all in one word without any spaces okay now over here we can specify the c plus plus language standard so by default version 14 is selected but we can change that to a higher version like 20 or 23. now because 23 is not official yet i would suggest you to go with 20. good now let's create this project all right here's our first c plus program written in a file called main.cpp if you accidentally close it you can easily find it in the project window so expand this folder and here is main.cpp now we have another file in this project called cmakelists.txt we don't need that so let's close it from here now we have the same concept in other ids like visual studio or xcode so we have a project and that project contains a file that is the main file of our program now let's close this window i'm going to delete all this code because we're going to write it from scratch so you understand how everything works all right let's start with a metaphor think of your tv your tv has several functions it has functions for changing the channel controlling the volume and so on by the same token a c plus plus program consists of tens or hundreds or thousands of functions each serving a purpose now we have a special function here called main which is the entry point to our program this is like the power button of a tv okay now note that c plus plus is a case sensitive language so it's sensitive to lowercase and uppercase letters so make sure to type this exactly as i show you so if you type a capital m here this is going to have a different meaning okay so we're defining a function now before the function name we should specify the type of value it's going to return this main function should return a value of type int which is short for integer and that represents a whole number like 1 2 3 4 and so on so when we run our program the operating system like windows or mac os is going to execute this function and the value that this function returns tells the operating system if our program terminated successfully or not okay so here we have int followed by white space and then the name of the function now white spaces in c plus are often ignored so whether we have one or ten spaces it doesn't really matter but in terms of formatting our code it's better to go with one space because we want to format this code professionally just like how we write an article you want to format our code just like a published article okay now after the function name we type a pair of parentheses and inside the parenthesis we can specify the parameters of this function so a function can have zero or more parameters for now let's not worry about them we'll talk about them later then we type a space again for proper formatting followed by a pair of braces now inside the braces we can type the code for this function so whatever we type here will be executed when the operating system executes our main function now once again in terms of formatting there are two schools of thought for adding the braces some people like to add the left brace on the same line as the function the other people like to put the left brace on a new line there's really no right or wrong here so whatever you prefer just stick to that and make sure your code is consistent in this course i'm going to put the left brace on the same line where we define a function okay now in this function we want to write code to print something on the screen and for that we're going to use the c plus plus standard library so earlier i told you that the standard library provides a bunch of capabilities that we need in almost every application so on the top we type hashtag include and in angle brackets we specify the name of one of the files in the standard library that is io stream which is short for input output stream in this file we have capabilities for printing something on the screen or getting input from the user so just like a supermarket has different sections the standard library also has different files each serving a purpose now as we go through the course you will learn about the other files in the standard library okay so back to our main function now here we type std that is short for standard library and this is like a bucket or a container for the features that are currently available to us so the features we have imported on the top okay so if we type double colons we can see all these features now there are a ton of features here don't worry about any of them in this lesson we're going to use c out that is short for character out some people think this is short for console out that is not correct so using this object we can output one or more characters on the screen so we type a space followed by two left angle brackets another space and then in double quotes we type the text we want to print on the screen so hello world okay and then we terminate this line using a semicolon just like how we terminate our sentences with a period so in c plus plus this line is called a statement because it tells the operating system what to do so whenever we type a statement we should terminate it with a semicolon okay now finally we return the value of zero and once again we need to terminate this with a semicolon but why zero well zero tells the operating system that our program is going to terminate correctly if we return any other values positive or negative that means our program encountered an error okay so let's quickly recap what we have done so far on the top we included one of the files in the standard library for printing something on the screen then we defined the main function which is the entry point to our program now as you can see the main function returns an integer which is a whole number like 0 1 2 3 and so on and in between the braces we have written the code for this function so on the first line we print something on the screen and on the second line return the value of zero as simple as that this is your first c plus plus program next i'm going to show you how to compile and run this program now to run this program first we have to compile this code to machine code that can be run by the computer's operating system so the machine code is basically the native language that a computer's operating system understands and it's different from one operating system to another so if we compile this code on a windows machine we get an executable but that executable only runs on windows we cannot run it on mac or linux if you want to run our application on a mac computer we have to take this code on a mac and recompile it to get an executable from mac okay so back to our code to run this program we're going to click on this play icon on the toolbar now look at the shortcut on mac it's control and r always use shortcuts because they make your life easier so let's run this program we get this little window down the bottom this is called the console or the terminal window it's basically a way to see the output of our program so over here you can see the hello world message so we're using a console application here because console applications are easier to create especially for people learning a new language building applications with a graphical user interface or gui is way more complex so once you understand the basics of c plus plus you'll be ready to move on to writing applications with a graphical user interface if that's what you want okay now let's minimize this window and make a tiny problem in this code so i'm going to remove this semicolon now let's rerun our program all right look this time we get a compilation error pointing to this line so the error is reminding us that we have forgotten a semicolon if you're starting out it's completely normal to encounter these errors if you have a typo or miss a semicolon and so on don't let that discourage you remember patience is the first skill of a good programmer so if your code doesn't get compiled pay close attention to this video see what exactly i'm typing compare it with your code i promise if you pay close attention you'll be able to solve issues on your own so let's fix the issue all right let's move on to the next lesson [Music] now going forward i want to change the colors here and i wanted to show you how to do that because a lot of people ask me about the themes i use in my videos if you are not using c lion feel free to move on to the next lesson so on the top we go to the preferences menu then under appearance and behavior we select appearance now over here you can see the themes that are installed by default we only have four themes but we can get more themes by clicking on this link now on this page i'm going to sort this list by the number of downloads so we can see the popular ones i'm going to pick dracula theme it's a very popular thing but feel free to play with these themes and find the one that you personally like so let's install this accept good no okay so this is the dracula theme which is much better than the default theme that comes with c lion so that brings us to the end of this section in the next section we're going to talk about the basics of c plus plus so i will see in the next section now let me give you a quick overview of how i've structured this course so you can get the most out of it this course is the first part of my complete c plus series each part is about three to four hours long so you can easily complete it in a day or two in the first part which is the one you're watching we explore the basics in this part you will learn the fundamentals of programming in c plus data types decision making statements loops and functions now throughout the course i'm going to give you plenty of exercises to help you develop your problem-solving skills and build your confidence in writing code in fact many of these exercises are popular interview questions in the second part we'll explore intermediate level concepts such as arrays pointers strings structures enumerations and streams and finally in the last part we'll be talking about the advanced concepts such as classes exceptions templates containers and more so by the end of this series you will have a solid understanding of c plus and you'll be ready to apply it in real life for example if you want to build games with unreal engine which is a popular gaming engine you will have the necessary c plus plus skills to build games you just need to learn about unreal engine so i hope you stick around and master c plus plus one of the fastest and most efficient programming languages available [Music] hey guys mosh here i just wanted to say that you don't really have to memorize anything in this course i've put together a complete cheat sheet and summary notes for you that you can download as a pdf right below this video so click the link in the description to download this pdf so i have done my best to create the simplest c plus tutorial for you so if you enjoy this please support my hard work by liking and sharing this video and also be sure to subscribe as i upload new videos all the time welcome back to the ultimate c plus plus course in this section we're going to talk about the basics of c plus plus we'll cover variables and constants naming conventions coding mathematical expressions writing to and reading from the console working with the standard library and comments so by the end of this section you'll be able to write simple but really useful programs in c bus now let's jump in and get started [Music] all right let's talk about variables in programming we use variables to temporarily store data in the computer's memory now technically a variable is the name of a location in memory where we can store some value now because the value can change we refer to this location as a variable now to declare a variable in c plus plus first we have to specify the type of data we want to store let's say int or integer for storing whole numbers then we give our variable a proper meaningful name like file size now there are various ways to name our variables we have various conventions we'll talk about them momentarily once we declare a variable then we terminate this statement with a semicolon now i want to emphasize that you should always use meaningful names for your variables don't use abbreviations like fs because someone else reading this code may not know what fs is short for also don't go for names like f1 or f2 or thing these are all cryptic and ambiguous okay so we're going to call this file size and then we can give it a value like 100 so we assign it the value of 100. now here we can combine these two statements into a single statement and that makes our code shorter and more concise so right here where we declare our variable we can give it an initial value of 100. this is called initializing a variable now we don't need the second line okay now let's declare another variable for storing numbers with a decimal point for that we're going to use a different data type that is double we're going to talk about different data types in the next section so in this section we're only going to work with integers and doubles now we're going to call this sales and initialize it to 9.99 okay now that we have two variables we can print them on the console so instead of hello world let's print file size run our program we see 100 beautiful now while initializing variables is not mandatory it's a good practice to follow let's see what happens if we don't initialize file size and print it on the terminal well immediately we see this warning let's take a look the warning is saying variable file size is uninitialized when used here initialize local variable file size so our id is complaining that we are using a variable that doesn't have an initial value let's run our program and see what happens take a look look we get this random value and if we run our program multiple times we see a completely different value this is what we call garbage this is the data that is currently in memory so as a best practice we should always initialize our variables before using them so i'm going to set this to an initial value of 0. now in language just like c sharp or java we don't have to do this if we declare an integer it automatically gets initialized to zero but this is not how it works in c plus okay so this is how we can declare and initialize variables and by the way we can also initialize multiple variables on the same line so over here we can declare a second integer let's call that counter so we add a comma and then declare counter and optionally we can initialize it to some value now while this works it's often discouraged as a best practice we should declare each variable on a separate line so i'm going to remove this and declare another integer like this okay now i have a small exercise for you i want you to write code to swap the value of two variables this is a common interview question so let me explain what i mean we're going to declare two variables a and b now if we print a we're going to see one on the terminal right now here's what i want you to do over here i want you to write code to swap the value of these variables so when we print a we see two and when we print b we see one now i don't want you to reset these variables so i don't want you to set a to two and b to one this is not the right solution let me give you a hint imagine instead of these two variables we have two buckets the first bucket is filled with apples the second bucket is filled with oranges now if we have these two buckets in real life how can we swap their content think of a solution and then use that idea to write code to swap the value of these variables it's not that difficult just spend a couple minutes on this and then come back see my solution so to solve this problem in real life we need a third bucket first we empty our apples bucket into this bucket now the apples bucket is empty so we can move the content of the oranges bucket here now the oranges bucket is empty so we can move the content of the third bucket into this bucket now we have swapped the content of our buckets right so let's use this idea to solve this exercise we declare a third variable we can call that temp and we initialize it with what we have in a that is the value of one now we can set a to b so whatever we have in b which is 2 is now going to be in a and finally we're going to set b to temp so b is going to be 1. so now if we print a we're going to see 2 instead of 1. let's verify this so let's run our program there you go beautiful so this was your first programming problem if you got stuck don't worry it's completely normal as we go through the course i'm going to give you more and more exercises to help you build your confidence next we're going to talk about constants [Music] there are situations where we don't want the value of a variable to change this is where we use constants here is an example let's declare a variable of type double and call it pi and set it to 3.14 now with this we can calculate the area of a circle right but what if somewhere in our program i accidentally set pi to a different value like zero with this our calculations are going to go wrong right this is where we can use a constant to prevent the value of pi from changing how do we do that very easy we type the const keyword before declaring this variable now look on line 5 we have a red underline that is a compilation error so if you hover our mouse here we see the error saying cannot assign to variable pi with const qualify type const double and also if we try to run our program here in the terminal window we see an error so take a look this is the error there is happening in main.cpp on line five in column eight and here's the actual error cannot assign to variable pi with const qualified type okay so this will prevent us from accidentally modifying the value of this variable or more accurately constant [Music] now let's talk about naming conventions so we have different conventions for naming our variables and constants and different teams prefer different conventions so there is really no right or wrong here but let me show you the popular conventions so earlier we declared a variable called file size the way we name this variable follows what we call the snake case so with this convention we have to use lowercase letters to name our variables and constants and if we have multiple words we should separate them using an underscore now we have another convention called pascal case in which we should capitalize the first letter of every word so the same variable using pascal case looks like this this is pascal case and by the way the text that i put here that starts with two forward slashes this is called a comment we'll talk about comments later in this section but for now just remember that comments are a way to describe our code they don't get compiled okay now we have another convention that is similar to pascal case the only difference is that the first letter of the first word should be lowercase so file size this is camel case we also have hungarian notation which is a pretty old notation and it's not relevant anymore with hungarian notation we should prefix the name of our variables with a letter that specify their type so here we have an integer so we use a lowercase i and then file size just like pascal case this is called hungarian notation now quite frankly this is a very old notation it's not relevant anymore but i still see people using it i've seen it a lot in windows source code the reason this is not relevant anymore is because in the old days we didn't have good editors so if we declared a variable somewhere and we wanted to know its type we had to scroll up to find the type of that variable so with hungarian notation we could look at a variable and immediately tell its type but this is not the case anymore because these days we have powerful editors if we simply hover our mouse over any variable we can see its type so here you can see file size is an integer variable right so these are the popular conventions out there in this course i'm going to use camelcase for naming our variables and constants and pascal case for naming our classes we'll talk about classes later in the course now if you don't like these conventions and prefer to use snake case that's totally fine but make sure to stick to your own convention the more consistent your code is the easier it is to read understand and maintain it next we're going to talk about mathematical expressions [Music] so you have learned how to declare variables and constants now let's see how we can write mathematical expressions for performing calculations this is where the fun begins so i'm going to declare two variables x and y now we can declare a third variable and set it to x plus y so what we have here is called the addition operator and x and y here are called operands so now let's print z on the terminal so std double colon c out z take a look so now we see 13 beautiful we also have subtraction multiplication and division but division is a little bit tricky in this case because we're dealing with two integers the result of the division is going to be an integer even though in reality dividing 10 by 3 is going to result in a number with a decimal point which we call a floating point number in programming so if you're on our program we see three but what if you want to see a floating point number well changing the type of z to double is not going to solve this problem because as i told you earlier if both our numbers are integers the result of the division is also going to be an integer so to get a floating point number we have to convert one of these numbers to a double so take a look first the warning goes away now if you run our program one more time look we get three point three three three three okay so this is how division works in c plus plus now let me rewrite this back to integer and integer now we have another operator called modulus which returns the remainder of a division so what is the remainder of division of 10 by 3 it's 1. let's verify there you go okay now using these operators we can modify our variables let me show you what i mean so for simplicity i'm going to remove y and z we only have x and we're going to print it on the terminal let's say we want to increment x by 5. here's how we do it we type x equals x plus 5. so first this piece of code or this expression is going to get evaluated the result is 15 and then the result will be stored in x okay now similarly we can subtract 5 from x we can multiply x by 5 and so on okay now we also have two more operators you need to know and they are increment and decrement operators so let's say we want to add 1 to x we can say x equals x plus 1. that is totally fine but there is a shorter and more concise way to write this code we can say x plus plus this is the increment operator we also have decrement operator but we don't have the equivalent for multiplication or division only increment and decrement okay now this increment operator there are two ways we can apply it we can apply it as a postfix or as a prefix let me show you the difference so i'm going to delete these two lines let's declare another variable called y and set it to x plus plus if we apply this as a postfix first the current value of x which is 10 is going to be assigned to y so y is going to be 10 and then x will be incremented by 1. so if we run our program x is going to be 11 but y is going to be 10. let me show you so we print x x is 11 but if we print y y is going to be 10 okay so let me add this as a comment for clarity in this case x is going to be 11 and y is going to be 10. now what if we apply the increment operator as a prefix so we declare another variable and set it to plus plus x in this case because we applied this operator as a prefix first the value of x is going to be incremented by 1 so x is going to be 11 and then the result will be stored in z so in this case both x and z are going to be 11. let's verify so if we print z well in this case these 12 i made a mistake because in the previous statement we incremented x by one so if we comment out this line it's not going to get executed so now when we run our program x is going to be 11 and z is going to be 11 as well let's verify it so here's z beautiful and let's also print x there you go so here's what you need to take away if you apply the increment or decrement operator as a prefix first this piece of code is going to get evaluated so first x is going to be incremented by 1 and then the result is going to be stored in the other variable in contrast if we apply this operator as a postfix first the current value of x which is 10 is going to be stored in y and then x is going to be incremented by 1. hey guys mosh here i hope you have been enjoying this tutorial so far i just wanted to let you know that this tutorial is the first hour of my complete c plus series where you will learn everything you need to know from the basics to more advanced concepts so watch this tutorial to the end and if you still want to learn more use the link below this video to enroll in the full course the complete course contains three parts each part being around three to four hours long so you can complete them in a day or two you will also get a certificate of completion and a 30-day money-back guarantee again if you're interested the link is below this video in the description box when writing mathematical expressions especially the more complex ones you need to take into account the order or priority of operators let me show you what i mean so i'm going to declare a variable called x and set it to 1 plus 2 times 3. now let's print x on the console what do you think we're going to get pause the video and think about it for a second the answer is seven this is a very simple math question but unfortunately a lot of people get it wrong here's the reason in math the multiplication and division operators have a higher order or a higher priority so when evaluating this piece of code or this expression first this part is evaluated so 2 times 3 is 6 and then 6 is added to 1 so the result is 7. let's verify it so i'm going to run the program there you go we have 7. okay so here's what i want you to remember in math or any programming languages the multiplication and division operators always have a higher priority than addition or subtraction operators but we can always change the order of these operators using parentheses so in this case if we wrap this piece of code with parentheses first this piece is evaluated so 1 plus 2 is 3 and then 3 is multiplied by 3. so the result is going to be 9. let's verify it so run the program one more time there you go okay now here's your exercise for this lesson take this mathematical expression and implement it in c plus plus assume x is 10 and y is five so if you implement this correctly z is going to be 1.3 so pause the video and work on this for a couple minutes then come back see my solution all right here's the solution i'm going to declare x and set it to 10 then y we set it to 5 and for z first we have to add 10 to x but we have to wrap this in parenthesis because this whole thing is going to be our numerator once we have the numerator then we're going to divide it by 3 times y but here's the tricky part we have to wrap this whole expression in parenthesis because the result of this expression is going to be our denominator if we don't use parenthesis here our denominator is going to be 3 and the result is going to be different so we wrap this whole thing in parenthesis and now let's print z on the terminal so we should get 1.3 again if you didn't solve this properly don't worry don't let that discourage you remember you're a student you're learning if you know everything and you could solve every problem you would be the one teaching right so don't let that discourage you and let's move on to the next lesson [Music] so you have learned how to write to the console or the terminal window in this lesson i'm going to show you a few more techniques for writing to the console so let's start by declaring a variable now let's say on the terminal we want to print x equals 10. how do we do this well first we go in the std namespace and pick up c out which is an object that represents the standard output stream i know it's a mouthful but let me explain it for you in programming a stream represents a sequence of characters the standard output is our console or terminal window so using c out we can write a sequence of characters on the standard output which is our console window right now these double left angle brackets are called the stream insertion operator it's an operator for inserting something to our output stream in this case we're going to write a sequence of characters which we specify using double quotes now in programming or c plus specifically this is called a string we'll talk about strings later in the course so here we want to print x equals and right after we want to print the actual value of x so we terminate this statement and use c out one more time but this time we print x okay let's run our program and see what we get so we see x is 10 beautiful now we can combine these statements into a single statement so we get rid of the second c out and this semicolon and then put everything on the same line now we are chaining multiple stream insertion operators so if we run our program one more time we get the exact same result beautiful now what if we declare a second variable so let's declare y and set it to 20 and then repeat so one more time c out y equals and then we add y take a look all right here's what we get but wouldn't that be nicer if y equals 20 was on the second line well to solve this problem right here we need to add a new line so once again we chain the stream insertion operator and this time we go in the steady namespace and pick up end-all which represents the end of the line okay now let's run our program one more time that is much better okay now once again we can simplify this code by combining these two statements so again we don't need the second c out so let's remove that and this semicolon as well now if we run our program we get the exact same result however our code is not formatted properly it's a little bit hard to read this code so here i'm going to use tabs and spaces to align these operators so what we have in our code looks exactly like what we expect in the output okay this is better now there is a tiny problem in this code we have a bit of repetition of std double colons so we have repeated this in two places let me show you how to simplify this code so before our main function we use the using directive to pick up the std namespace so here we type namespace std now std is defined anywhere in this file so we don't have to repeat it in multiple places so we can simply access all objects in the std namespace so let's remove that and this one as well and finally let's realign this bracket great so now our code is cleaner more concise and easier to read great now here's your exercise imagine you have a store and you have made 95 000 now as part of your tax return you have to pay state and county tax at different rates so state tax is four percent whereas county tax is two percent now i want you to write code to show your total sales as well as your state tax your county tax and the total tax you have to pay on this income so pause the video and work on this exercise for five minutes then come back see my photoshop all right here's my solution first we need a variable for storing the total sales and for that i'm going to use a double so even though we don't have any sent values here but for monetary values we should always use a double so double sales equals 95 000. now right after let's print the total sales here we add a dollar sign that's nicer then we chain the insertion operator to print sales followed by the end of line now before going any further let's run our program and make sure everything works so run total sales is 95 000 great next we need to calculate the state tax so let's declare another variable called state tax and here we get sales and multiplied by .04 and then once again we print this on the terminal so state tax is this value followed by the end of line now once again let's run our program and make sure everything works so this is how i want you to write code write a bit of code run it make sure everything works before going further baby steps so run so our estate tax is 3800 great now let's improve this code the first thing i want to improve here is formatting so the first two lines are about the total sales whereas the second two lines are about the state tax these are two different stories right so here i add a vertical line to separate these stories just like how we have multiple paragraphs in an article we want to write our code so every story is separate from other stories okay so here's our state tax then i add another vertical line to separate it from the return statement great now this line is totally fine but generally speaking it's best to avoid magic numbers like this here because even though this is a very simple example in more complex programs these magic numbers might be confusing someone else reading your code may not know what that number represents so here we can make our code more expressive by storing this value in a separate variable so we declare a variable called state tax rate and set it to 0.04 and then we can reference that variable right here now it's completely clear what this value represents it's our state tax rate but this has another benefit if we use this variable in multiple places in our code and then tomorrow this day tax changes we don't have to come back and modify multiple places we have a single place where we have stored this value okay now there is a tiny problem in this code the problem is that i can accidentally change the state tax rate how can we solve this problem using a constant so we qualify this with the const keyword that's better now we have to repeat the same three lines for our county text so i'm going to copy this and paste it and again note the vertical line this is to separate these stories so over here we're going to rename this to county tax rate which is going to be two percent and over here we're going to calculate the county tax and print it accordingly county tax good nothing new and we should also replace state tax rate with county tax rate so let me show you a shortcut here look i haven't typed county tax rate i just typed kind of an abbreviation so count t r so we can use abbreviations to quickly type our code and press enter to complete it okay now let's run our program and make sure everything works so our county tax is 1900 beautiful now the final part we declare another variable called total tax which equals state tax plus county tax and finally we print it on the terminal total tax okay so once again see how i've named my variables all the variables are properly named they're meaningful there is no ambiguity in this code we don't have t1 t2 tr whatever don't write code like that next we're going to talk about reading input from the user [Music] all right now let's see how we can read input from the console so you have learned that c out represents the standard output string now in this file in iostream we have another object called c in which represents the standard input stream which we can use for reading data from the console let me show you how first we're going to use c out to print a label on the screen so enter a value now using c in we can read that value and put it in a variable but first we need to declare a variable so let's declare an integer called value then we use c in along with the stream extraction operator to read that value and put it in this variable okay so this is called the stream extraction operator it's the opposite of stream insertion operator i know it can be confusing but the easiest way to remember this is to think of the direction of data flow so in this case we have reading data from the console or the standard input and putting it into this variable in contrast with c out we're basically getting this sequence of characters and putting them into the console so this is the way to remember this okay now to verify that our program works let's print the value that we just read so let's run our program enter a value let's say 10 and we get 10 in the output beautiful now what if we enter a floating point number a number with a decimal point let's see so this time i'm going to enter 10.1 the decimal part is gone because we declared this value as an integer so if you want to read a floating point number here we have to use a double type take a look so one more time 10.5 now we get 10.5 beautiful now we can also read multiple values so let's change this label to enter the values for x and y now let's declare two variables called x and y first we read x and then we read y and finally we can print x plus y this is like a simple calculator so take a look we can enter 10 and 20 and the result is 30. now we can also separate these numbers using a space and the program will still work take a look so one more time 10 space it doesn't matter one or more spaces we add the second number and we get the same result okay now similar to c out here we can chain these statements together so we can get rid of the second statement and chain the stream extraction operator to read the second value so look we start from the console we read something and put it in x then we read something else and put it in y it's exactly like before but our code is shorter so this is how we can read input from the console now as your exercise i want you to write a program for converting temperatures from fahrenheit to celsius so when you run your program the program should ask the user to enter a temperature in fahrenheit and then it should convert it to celsius and print it on a terminal so pause the video and spend a few minutes on this then come back see my solution all right here's the solution it's pretty easy first we use c out to print a label like fahrenheit then we declare a variable for storing the temperature in fahrenheit fahrenheit next using c in we read that value and put it in this variable then we declare a variable of type double called celsius the reason i'm using a double here is because the conversion might result in a floating point number so here's the formula fahrenheit minus 32 we wrap this in parenthesis and then divide it by 1.8 now finally using c out we print the temperature in celsius now let's test our program so 90 in fahrenheit is equivalent to 32.2 in celsius [Music] so you have seen that the standard library gives us the capability to read from or write to the console now in this lesson we're going to look at a different part of the standard library that gives us several useful mathematical functions so on the top we're going to use the include directive one more time to include a file called c math this file declares a bunch of useful mathematical functions now if you're curious what these functions are just go to google and search for c math reference there are many different websites that give you a c plus plus reference one of them is cplusplus.com the other is cppreference.com and so on so as an example let's look at this page so over here you can see all the functions declared in the cmat library in this lesson we're going to look at a couple of them one of them is seal which rounds up a value the other is floor which rounds down a value now if you click on any of these functions you can learn more about it so on the top you can see different versions of c and c plus plus so c90 and c99 represent the old c language c plus bus 98 is one of the early versions of c plus plus that came in year 1998 then we have c plus 11 that was released in year 2011. so you can see how this function has evolved over different versions of c or c plus now don't get hung up too much about these details all i want you to pay attention to here is that this function takes an input of type double and returns another double so let's see this in action so back to the code here in the main function to use the floor function we type floor followed by a pair of parentheses and then we supply the input value which is called an argument so we pass 1.2 now we get a double value that we can store in a variable so let's declare a variable of type double called result and set it to the return value of the floor function and then we terminate this statement with a semicolon now over here we say that we are calling the floor function which means we are executing it we are giving it a value and getting a new value now we can print the result just like before and the result is one okay now some functions take multiple values or multiple arguments one of them is the pow or power function so let's take a look pow requires two arguments here we need to pass two values separated by comma so if we say two comma three that means two to the power of three now when we type this c lion adds these labels lcpp underline x and lcpp underline y these are the name of the parameters of this function so clion adds this to make our code a bit more understandable okay now if we run this we get eight okay now as an exercise i want you to write a program that asks the user to enter the radius of a circle and then it should print the area of a circle it's pretty easy you can knock it out in a couple of minutes all right here's my solution first we use c out to print a label enter radius then we declare a double variable called radius next we use c in to read the value the user enters into this variable now we declare another variable called area and here we have to use the old formula pi times r to the power of 2. so we can type the pi number here but earlier i told you that we should avoid magic numbers as much as possible so we're going to store this value pi in a separate variable or even better we can make this a constant okay now we can say area equals pi times this is where we use the power function to get radius to the power of two as simple as that now finally we use c out to print the area let's test our program so if we enter 4 the area is 50.24 [Music] all right the last thing we're going to cover in this section is comments we use comments to clarify our code and to make it easier to understand as i told you before comments don't get compiled now in c plus plus we have a couple of different ways for writing comments we can start with two forward slashes and whatever we type in front of these slashes will be considered a comment now we can add the slashes above a line or in front of it either way works but as you can see here we have limited space because we're basically bound to what is left here of course we can write a longer comment but then we'll have to constantly scroll to the left and to the right to see what is going on so it's more conventional to write the comment above a line now if you want to have multiple lines again we can start a new line of comment like this okay now in c plus was we have another way for writing a multi-line comment instead of two forward slashes we start with a forward slash and an asterisk and then press enter now c line automatically generates this block of comment these two characters represent the beginning of the block and these two characters represent the end of the comment block what we put in between will be considered a multi-line comment now different teams have different preferences in terms of which style of comments should be used so there is really no right or wrong here just pick one style and stick to it now one thing i want to emphasize about comments is that you should not overuse them because they make your code harder to understand and maintain so you should use comments only to explain whys and how not what let me show you what i mean so here i can write a comment let's say declare a variable and initialize it to 0. well it is obvious that that's what we're doing on the next line so this comment is completely unnecessary and it's making our code a little bit verbose we don't want to sprinkle our code with all these kinds of unnecessary comments instead we should use comments to explain whys and how if you made certain assumptions while writing this code we should comment those assumptions so in the future when we come back we see why we did things in a certain way okay so that's all about comments and that brings us to the end of this section so i will see you in the next section welcome back to the ultimate c plus boss course in this section we're going to explore the fundamental data types in c plus in detail we'll talk about various built-in types as well as their size and limits more specifically we'll explore various types for representing numbers and their differences you will learn how to generate random numbers which is a very useful technique especially for building games you will also learn how to work with boolean values characters and strings as well as arrays which we use for storing a list of values so by the end of this section you will have a deep understanding of these fundamental data types and how to use them to write useful programs so now let's jump in and get started [Music] so you have seen that in c plus to declare a variable we need to specify its type that's why we say c plus plus is a statically typed language meaning when declaring a variable we need to specify its type and this type cannot change throughout the lifetime of our program other examples of statically typed languages are c sharp java typescript and so on in contrast to statically typed languages we have dynamically typed languages like python javascript and ruby in these languages we don't have to give our variables a particular type the type will be determined based on the value that we assign to these variables and that type can change throughout the lifetime of our program okay so that is the difference between statically and dynamically typed languages now in c plus plus we have a bunch of different built-in data types so far you have only seen int and double but we have more built-in types that we're going to cover in this section in this lesson i'm going to give you a basic overview of these types but as we go through this section you'll become more familiar with these types so for storing whole numbers we have int which takes four bytes of memory on most systems this is not a hard and fast rule depending on the implementation the number of bytes taken by an integer can vary from one system to another but for the most part you can assume that an integer takes four bytes of memory in four bytes we can store numbers from -2 billion to plus 2 billion now if you want to store a smaller number we don't need to waste 4 bytes of memory so we can use the short type which takes 2 bytes of memory and in 2 bytes we can store the values from minus 32 000 to plus 32 000. now for storing larger numbers we have long which is often the same as int on most systems and long long which takes eight bytes of memory and allows us to store really large numbers speaking of experience most of the time you'll be using short or in types unless you're working on programs that involve complicated mathematical computations now for numbers with decimal places which we call floating point numbers we have double which you have seen so far the double type takes 8 bytes of memory now we also have float which takes 4 bytes of memory and long double which takes 8 bytes of memory as well again most of the time you will be using double especially for storing monetary values because the flow type can result in loss of accuracy now we also have the bool type for storing true and false values they're often used to represent a condition like is this person eligible for a loan or not we also have another built-in type called char for storing single characters so that was a basic overview of the fundamental data types in c plus plus again as we go through this section we'll explore these types in more detail [Music] now that you're familiar with the basic built-in types in c plus let's look at a few different ways to declare and initialize variables so i'm going to start by declaring a double called price and we're going to set this to 99.99 nothing new so far but what if we want to declare a float well we can declare a float called interest rate and we set it to 3.67 and here at the end we type the letter f that is short for float this is really important because if you don't type this by default the compiler will treat this number as a double and then it will try to store a double inside a float variable and this can potentially cause data loss so when working with float values always type an f at the end it can be uppercase or lowercase it doesn't really matter now there is another reason we should type this letter we'll come back to this shortly now let's declare a long so long file size we can set this to 90 000. now similar to the flow type here we should add the l suffix because if we don't type this the compiler will treat this number as an integer so to force the compiler to treat this as a long we type either an upper case or a lowercase l now the lowercase l can be confused with the number one so the best practice is to use a capital l okay now let's declare a variable for storing a character so we say char letter and here we use single quotes to represent a character like a okay and finally let's look at a boolean we're going to call this is valid and we can set it to true or false these are the acceptable values for booleans now with any of these types we can also use the other keyword to let the compiler infer the type of our variables for example if we change bool to auto and then hover our mouse over is valid look the compiler knows that is valid is of type bull similarly if we change char to auto and look at the type of this variable we can see it's of type char now here's the interesting part if we change long to auto we can see that file size is of type long because we added the letter l at the end if we don't type this and use the auto keyword look file size is treated as an integer so that is why we need to add this suffix similarly for float if we use auto now we can see interest rate is a float but if you remove the suffix it will be treated as a double right so this is the benefit of using the auto keyword it kind of makes our code shorter and more consistent you don't have to use it if you don't like it but the auto keyword is particularly useful when working with more complex types we'll look at that in the future yeah there is one more way to initialize variables in modern c plus plus that you need to know and that's called brace initialization so let me delete all this code and declare an integer called number and set it to 1.2 now here we get a warning because we have a yellow underline but our code still gets compiled so if we print number and run our program we see the fraction part is gone and we see one okay now there's another way to initialize this variable and prevent this kind of scenario where we assign the wrong value to a variable so instead of the assignment operator we use braces so we put this value inside braces now look we have a compilation error because we have a red underline so our code is not going to get compiled the brace initializer stops us from making such mistakes now there is another benefit to using brace initialization if we don't supply a value here our number variable will be initialized to zero so if we run this program we see number is zero however if we remove the empty initializer here and run our program again you can see we get this random value which we say it's garbage and every time we run our program we get a different value so this makes our programs unpredictable so we should either initialize our variables using the assignment operator to a proper value or we should use an empty brace initializer [Music] in math and programming we have different number systems that serve different purposes in our day-to-day life we use decimal or base 10 numbers which can contain digits 0 to 9 but computers don't understand these digits they only understand zeros and ones that's why we have the binary or base two system so a number in this system can only contain zeros and ones now we can take any number and represent it as a binary for example the number 255 in the decimal system is equivalent to eight ones in the binary system it's a very long number that's why we use the hexadecimal or base 16 numbers to shorten binary numbers a hexadecimal number can contain the digits 0 to 9 as well as the letters a to f as you can see hexadecimal numbers are more compact now in programming we use hexadecimal numbers to represent colors you probably heard of rgb or red green blue colors using only six digits of a hexadecimal number we can represent any color that's very useful we don't have to deal with really large decimal or binary numbers now let's see how we can represent these numbers in c plus so i'm going to declare an integer called number and set it to 255. now if you want to represent this number in the binary system we type 0b as a prefix and then we type a binary number i'm going to type 8 once so 1 2 3 4 5 6 7 8. now let's print the number take a look we get 255 okay now we can represent the same number in the hexadecimal system so instead of 0b we type 0x and then we type a hexodecimal number in this case double f which can be uppercase or lorikeez it doesn't really matter let's run our program one more time look we get the same number beautiful now most of the time i would say 99 of the time we use decimal numbers but depending on the kind of application you're building in some situations you may want to represent a number as binary or hexadecimal okay now irrespective of how we represent numbers our numbers can be positive or negative if we're dealing with a positive number we don't have to type a positive sign it's assumed by default but for negative numbers obviously we have to type a minus now in c plus we have a special keyword called unsigned if we apply this to a numerical type that type cannot accept negative values now on the surface you might think this is a good value but it can actually cause programming problems that are hard to spot for example let's print this number on the console and see what we get so we get this really large positive number as another example we might initialize this number to zero and then somewhere else in our program we might decrement this number now if we print this instead of negative one we're going to get this really large positive number so my suggestion is to stay away from the unsigned keyword just because two plus plus has this feature doesn't mean you should use it that's why earlier in the course i told you that you don't need to learn all of c plus all of its features to build useful and substantial programs so stay away from the unsigned keyword [Music] when working with numbers a concept you need to understand is narrowing and that happens when you initialize a variable of a smaller type using a larger type here is an example let's declare an integer called number and set it to 1 million now to make this code more readable we can separate these digits using a single quote that's better now let's declare a short called another and set it to number now we immediately get this warning saying narrowing conversion from end to sign type short is implementation defined i know it's a mouthful basically the warning is saying that because we're converting an integer to a short this conversion is a narrowing conversion so it's going to result in narrowing down our number which is one million so now if we print another and run our program with this 16 000 this is the result of narrowing conversion now obviously if we use a brace initializer here we could prevent this our code wouldn't even get compiled so this is another benefit of the brace initializer okay now what if we do the opposite what if we declare this number as short and put it in an integer now in this case we have a warning because this number is too large to fit in a short variable because as i told you earlier using the short data type we can store numbers from minus 32 000 to plus 32 000. so let's change this to let's just say 100 and then put it in an integer now we can use the brace initializer or the assignment operator it doesn't really matter let's run our program we get 100 so the opposite is not an issue so the short type takes two bytes the integer takes four bytes if you store a smaller number and the larger memory space we are not going to encounter data loss so the additional bytes in memory are going to be filled with zero [Music] all right now let's see how we can generate random numbers in c plus this is very useful we can use random numbers in creating games that involve rolling a dice card or other elements so we have a function called rand that is defined in a library called cstdlib so on the top we need to include another file from the standard library called c stdlib okay now we call this function and get a random integer so let's store it here and then print it on the terminal now let's run this program so this is the number i get on your machine you're probably going to get something different now here's the thing every time we run this program we get the exact same number the reason for this is that these numbers are not really random they're basically based on some kind of mathematical formula so to get a random number we need to see the random number generator with a different value let me show you what i mean so we have another function called srand that is short for seed rand if you see the random number generator with the value of five now we get a different random value but again every time we run this program we get the exact same random number if we see this with a different number now a random number is going to be different so how can we get truly random numbers well we have a function for getting the current time in terms of the number of seconds elapsed from january 1970. if we use that function every time we run our program we're gonna get a different number let me show you so first on the top we need to include another file called see time in this file we have a function called time that returns the current time in terms of number of seconds elapsed from january 1st 1970. now to call this function we have to give it a special argument called null pointer or null ptr we'll talk about this later in the course if this is too confusing for you just use the number zero but c lion is going to give us a warning don't worry about that it's just suggesting to use null pointer now this returns a long value which is elapsed seconds so to see this in action instead of printing a random number let's print the elapsed seconds now if you're on our program this is the number of seconds elapsed from january 1st 1970. now every time we run our program we get a different value right so we can use this to see the random number generator so instead of hard coding the number six we can use elapsed seconds now we generate a random number and print it on the terminal take a look so every time we're on our program we get a different random number great but this random number is way too large what if we want to specify an upper limit well over here where we generate the random number we can use the modulus operator and specify the upper limit so if we type 10 that's gonna return the remainder of division by ten so that can only be numbers zero to nine right take a look so now we have two if we're on our program again we get nine three and so on beautiful now we have a warning here under rand the warning is saying the rand function has limited randomness use c plus 11 random library instead so in c plus boss 11 we have a different way for generating random numbers but that's more complicated it's not suitable for beginners so for now this is a good way for you to learn how to generate random numbers now we can make this code a little bit more concise in this case we don't really need this variable elapsed seconds because anyone familiar with c plus knows that time of zero or time of null pointer returns the current time in terms of number of elapsed seconds so we can grab this function and pass it as an argument to the srand function and now we don't need this extra variable so this function will return a value and that value is going to be passed to this function as an argument okay so this is how we can generate random numbers in c plus now as an exercise i want you to write a program to roll a dice so every time we run this program we should get two random values between one to six now to limit the range of the random number use this formula on the screen you will see my solution next all right let's look at my solution so on the top we are including three files iostream csdlib and c time now in the main function we are seating the random number generator with the current time now to generate a random value we're going to use the formula i showed you earlier so we call the rand function and then get the remainder of division by this expression our maximum value is six our minimum value is one and then we need to add one to it now someone else looking at this code will probably have no idea what these numbers represent that's why i told you that you should avoid magic numbers so this is a great opportunity to use a constant so we define two constants constant integer mean value of one and constant integer max value of six now here we can use the short type because we don't really need to store large numbers here so it's better to use the short type to save system resources the memory so we have two constants now instead of hard coding these magic numbers we use our constants and this makes our code more readable and easier to understand okay so using the modulus operator we get the remainder of division by this expression now we need to wrap the whole thing in parenthesis and add the minimum value to it this will give us a random number between one to six so we can store it in a variable called die one or first whatever you prefer then we need to duplicate this and create a second variable called second and finally we can print everything using c out so first here we chain the stream insertion operator we can add a comma and the second variable now let's run our program so we get three and four one more time five and six six and six beautiful we have reached the end of this tutorial again as i said this tutorial is the first hour of my complete c plus series so if you want to learn more use the link below this video to enroll and please support me by liking and sharing this video thank you so much and have a fantastic day [Music] you