Welcome to the ultimate C++ course. In this course, you're going to learn everything you need to know about C++ 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 C++ course for you. You don't need any prior knowledge of C++ or programming in general.
Everything you need to know about C++ is in one place. So you don't need to jump back and forth between random tutorials. My name is Mosh 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 Code with Mosh.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. Before we start coding Let's spend a couple of minutes and talk about C++, what you can do with it, and how to master it. C++ 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. Even government agencies like NASA just to name a few Every three years we get a new version of C++ 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++ is no longer relevant because of the newer languages like Java or C sharp? That is not true. C++ 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++ is a great choice This is an advantage that it has over languages like C sharp and Java C++ 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 C++ is a great investment and opens a lot of doors for you according to indeed.com The average salary of a C++ programmer in the US. It's just over $170,000 a year now to master C++ There are two things you need to learn one is the C++ language itself Meaning the syntax or the grammar of this language The second thing you need to learn is the C++ standard library or STL, which is a collection of pre-written C++ 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++ 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++ a bit extensive and intimidating But in reality you don't need to learn all of C++ 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++ step by step and as we go I'm going to show you you can write some really cool programs as you're learning C++. 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++ is not really that difficult.
So if you follow along, by the end of this course, you'll be able to write C++ code with confidence. Alright, next we're going to talk about the tools you need to write C++ programs. To create C++ 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 c lion which is cross platform so it runs on windows mac and linux You can try it 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++ programs. In this course, I'm going to use CLion, 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++ language itself. Now, if you're an absolute beginner and you have never coded before, I recommend you to download the free version of CLion 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 slash 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++ program together. So the first time you open CLion, 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 JetBrains 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 CLion, 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 CLI and 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++ 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.
Alright, here's our first C++ 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 cmake lists.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 gonna delete all this code because we're gonna 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 as C++ 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++ 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 a white space and then the name of the function Now white spaces in C++ 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 parentheses 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++ 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 and 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 you 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 gonna 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++, 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 and countered an arrow. 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++ 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 are 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++, 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 the 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 is 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 Compared 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. Alright, let's move on to the next lesson. 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're not using sea 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 theme, but feel free to play with these themes and find the one that you personally like. So.
Let's install this. Accept. Good.
Now, okay. So this is the Dracula theme, which is much better than the default theme that comes with CLion. So that brings us to the end of this section.
In the next section, we're going to talk about the basics of C++. So I will see you 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++ 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++, 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 solid understanding of C++ 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++ skills to build games. You just need to learn about Unreal Engine. So I hope you'll stick around and master C++, one of the fastest and most efficient programming languages available.
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++ 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++ course in this section. We're going to talk about the basics of C++ 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++ now Let's jump in and get started Alright, 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++, 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 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 nine point 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 zero. Now in languages 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++. 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 gonna 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 2 and b to 1 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 a temp and we initialize it with what we have in a that is the value of 1 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 Constance there are situations where we don't want the value of a variable to change. This is where we use constants Here's an example.
Let's declare a variable of type double and call it pi and set it to three point one four 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 0 with this our calculations are gonna 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 cons qualified type counts 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.
The error is happening in main that 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 modify the value of this variable or more accurately constant 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 specifies 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 is 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 camel case 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 I 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 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 gonna 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++ 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 five. Here's how we do it. We type x equals x plus five.
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 five from x, we can multiply x by five, 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 one to x, we can say x equals x plus one, 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 gonna 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 you 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. 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 you print z, in this case, z is 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 is the 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 you 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++ 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 one plus two times three. 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 gonna 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++. 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.
Alright, here's the solution. I'm going to declare x and set it to 10. Then why we set it to 5 and 4z 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 you don't use parenthesis here our denominator is going to be three, and the result is going to be different. So we wrap this whole thing in parentheses.
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 teaching, right? So don't let that discourage you.
And let's move on to the next lesson. 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 cout 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 cout 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 plus specifically This is called a string. We'll talk about strings later in the course So here I'm gonna print X equals and right after we want to print the actual value of X So we terminate this statement and you see 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. Alright, 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 city namespace and pick up Endel 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 these brackets 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 4% whereas county tax is 2% 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 solution. 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 cent 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 multiply it 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 separated 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 state 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 tax 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 gonna rename this to County tax rate, which is going to be 2% 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 are 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. All right, now let's see how we can read input from the console.
So you have learned that Cout represents the standard output string. Now, in this file, in IOStream, we have another object called cin. 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 cout You'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 a 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 cout 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 you start from the console you 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. Alright, here's the solution. It's pretty easy First we use cout to print a label like Fahrenheit Then we declare a variable for storing the temperature in Fahrenheit.
Fahrenheit. Next, using cin, 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 cout we print the temperature in celsius now let's test our program so 90 in fahrenheit is equivalent to 32.2 in celsius 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++ reference One of them is C++.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 C math 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 represents the old c language C++ 98 is one of the early versions of C++ that came in year 1998 then we have C++ 11 that was released in year 2011 So you can see how this function has evolved over Different versions of C or C++ that 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're executing it.
We're 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 power 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 sea lion adds these labels L CPP underline X and L CPP underline Y These are the name of the parameters of this function. So sea lion adds this to make our code a bit more understandable Okay. Now if you 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.
Alright, here's my solution. First, we use cout to print a label into radius, then we declare a double variable called radius. Next we use seen 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 2. 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 Alright, 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++, 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 plus 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 generate 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 why's and how's not what's let me show you what I mean so here I can write a comment and say declare a variable and Initialize it to zero.
Well, it is obvious that that's what we're doing on the next line. So this comment is completely unnecessary 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 why's and how's 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++ course. In this section, we're going to explore the fundamental data types in C++ 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'll 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. So you have seen that in C++.
To declare a variable, we need to specify its type. That's why we say C++ 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 assigned 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++ 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 gonna 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 minus two billion to plus two 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 8 bytes of memory and allows us to store really large numbers Speaking of experience most of the time you would 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 would be using double specially 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++ again as we go through this section We'll explore these types in more detail Now that you're familiar with the basic built in types in C++, 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 you 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 float 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 uppercase or a lowercase L. Now the lowercase L can be confused with the number 1, so the best practice is to use a capital L. Now let's declare a variable for storing a character. So we say char letter, and here we use single quotes to represent character like a okay, and finally let's look at a boolean we're gonna 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 auto keyword to let the compiler infer the type of our variables For example, if we change bull to auto and then hover our mouse over is valid look, the compiler knows that is valid is of type full. 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 floats, 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.
Now there is one more way to initialize variables in modern C++ 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 1. Now there is 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 0 so if you run this program we see number is 0 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 you run our program we get a different value so this makes our programs unpredictable so we should either initialize are variables using the assignment operator to a proper value or we should use an empty brace initializer 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 0s and 1s. That's why we have the binary or base-2 system.
So a number in this system can only contain zeros and ones now we can take any number and Represented 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++. So I'm gonna 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 gonna 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 0 X and then we type a hexadecimal number in this case Double F which can be uppercase or lowercase. 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 might not represent a number as binary or hexadecimal Okay. Now irrespective of how we represent numbers our numbers can be positive or negative If you'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++ We have a special keyword called unsigned if you 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 C++ 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++, all of its features to build useful and substantial programs.
So, stay away from the unsigned keyword. 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's 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 int 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 1 million. So now if we print another and run our program with this 16,000, this is the result of narrowing conversion. 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're not going to encounter data loss So the additional bytes in memory are going to be filled with zero Alright, now.
Let's see how we can generate Random numbers in C++. 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 brand that is defined in a library called CSTD lib So on the top we need to include another file from the standard library called C Std. Lib. Okay.
Now we call this function and get a random integer. So let's store it here 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 gonna get something different now here's the thing every time you 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 seedRand. 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 you see this with a different number, now our 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 see 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 I fear on our program. This is the number of seconds elapsed from January 1st 1970 now every time you 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 run 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 going to return the remainder of division by 10. So that can only be numbers 0 to 9, right?
Take a look. So now we have 2, if we run our program again, we get 9, 3, and so on. Beautiful.
Now, we have a warning here under rand. The warning is saying the rand function has limited randomness. Use C++11 random library instead. So in C++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++ knows that time of 0 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 s-rand 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++ 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 1 to 6 now to limit the range of the random number use this formula on the screen You will see my solution next Alright, let's look at my solution. So on the top we are including three files I'll stream see std lib and see time now in the main function We are sitting 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 6 our minimum value is 1 and then we need to add 128 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 1 and Constant integer max value of 6 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 parentheses and add the minimum value to it. This will give us a random number between 1 to 6, so we can store it in a variable called die1 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 cout. 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++ 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