Learn to Program with C++

View non-AMP version at androidpolice.com

Course Overview

Course Overview

Hi, everyone. My name is Kate Gregory, and welcome to my course. Learn to program with C plus. Plus, I'm a consultant and mentor. Aggregor consulting. I've been using C plus plus for over 30 years, and I've really enjoyed watching it change over the decades. You know, a lot of people think C plus plus is too hard to learn as a first programming language that you should go learn a different language first, then come back and learn c++. If that's what you want. I think they're wrong, and this course is my proof. In this course, you'll learn basic programming concepts along with the corresponding supose plus in tax. Some of the major topics that will cover include variables, loops and branches, the C plus plus standard library classes and objects, and how to use templates, operator overloading and other features that makes people's plus stand out from other languages. By the end of this course, you'll know enough C plus plus to read and write simple working programs. Before beginning the course. You should be familiar with editing text files on your operating system. All cover everything else you need from here. You should feel comfortable diving into even more supose plus with courses like Suppose plus fundamentals, including Cipel's Plus 17. Some of that will be a review, and some will be new or beautiful. Suppose plus STL algorithms and first look Suppose plus core guidelines in the Guidelines Support Library. I hope you'll join me on this journey to learn suppose plus with the LEARN to program with C plus plus course, that plural site.

Getting Started

Text Becomes Executable

when you write a program, when you create an application, you type some text into a file, and then that text turns in tow, something that people can run in order to do that. There are some tools that you need in the case of C plus. Plus, it is a compiled language, so that means you start with source code that you can read and write, and a compiler transforms it into a different format into machine language. If you've made any mistakes when you were creating your source code, the compiler may give you error messages. If it can't basically understand what you're saying and what it creates, we typically call an object file. The next step is for all of the object files that were made from individual source files to be turned into an execute herbal, you see, although I'll start with demos that just have one file. Riel applications are made from lots and lots of different files. Each of those is compiled one at a time, and then the object falls are linked together, and that makes the execute herbal. Not all projects actually try to make execute a bles. Sometimes what you're making is a library for other projects to use. But whatever you're making, the linker makes it. And if it has problems linking together the different objects that the compiler produced, it may give you some messages, and then that produces an application that you can run. And ideally, you have some way of interacting with that application, and that application interacts back to you so you might type or you click or touch or drag or any other number of ways of sort of human computer interface. And it might put words on the screen or draw a picture on the screen or animated picture or make noises, or again, any kind of way of making a human computer interface. What I'm focusing on in this course is how to create the source code that the compiler and a linker can turn into something people can run, and not very much about designing all that human computer interface. That's a whole separate thing. Toe learn. We'll start with the simple, which is the language and the syntax

C++ Is Unusual

when you want to get started using a particular programming language, you need to get the tools that can transform that text source code into something that could be executed. And normally you just have one choice of what tool you use and where you can get it from. But C plus plus is not like that. Suppose plus doesn't belong to just one vendor, so you don't just go to the people who own C plus plus and get the tool. There are all kinds of tools available. Some of them are free. Some of them cost a lot of money, and different developers and different development teams will choose different tools. But all of the vendors are implementing what's called Standard C plus. Plus, there's actually an ice, oh, standard that controls the language. So what keywords it has what the different kinds of punctuation means. Even what's in the libraries that ship with the compilers. This standard updates every three years and compilers generally come out more often than that, So what will happen is a version will come out that implements most of the current standard, and then the next version. What kind of catch up and maybe managed to implement all of the current standard, and then an updated version of the standard will come out. So it is a good idea to be using as reason to tool as you confined.


Well, that sounds nice. You have a choice, but its sometimes easier if you don't have a choice, right. Let me tell you what you need. You need a text editor, you're going to be typing in source code. And you do that in any thing that can edit text. There are text editors that come with your operating system, and then you need a compiler and a linker, and they very often come together. But you can also get what they call an integrated development environment, which starts with a code aware editor. That, for example, does syntax coloring for you so that variables are a different color than keywords. You can get in d ______, and I'll show you a tiny bit of debugging over the entirety of this course so that you can get an idea of what a debug Ercan do and then all kinds of other tools that you don't know what they are yet because you haven't started programming yet but that once you have a little bit of experience, are very useful to help you find bugs or write more effective code. And very often the tools can come with specific libraries and frameworks. There are a lot of tools available. Many of them are free, and because the languages standardised, you don't have to pick one and stick with it for the rest of your days. You can use one particular tool now while you're learning, and then take that same code toe, a different set of tools, and it will work just the same. And I'm going to demonstrate that to you in this module by repeatedly using different tools to compile toe link and to run the exact same source code. It's a pretty good guess. You probably would like to start with something free. There are other things out there. These are things that have free versions. If you're developing on Windows, Visual Studio has a community addition, which has essentially all of the features of the more expensive edition. You just have to qualify because you're learning or you are in a small company and there's a tool called Min G. W, which stands for minimalist good new for Windows. And it is a way to have another compiler in this case, GCC, the Canoe C plus plus compiler on Windows on the Mac. There's X Code and on Windows, Mac and clinics. You have visual studio code. I don't know why you use that on Windows, because you could just use visual studio on Windows. A lot of people love visual studio code. It needs some plug ins and set up to work for C plus plus, and I meet. People have trouble getting configured. So maybe not as a very beginner choice to go with visual studio code. Despite being a cool tool. There's Q T creator. And if in your future, you think you're going to be building a DUI application with Q T, you might want to start with that and learn how to use that. And then in the compiler world, we have clang and GCC, which I mentioned earlier, and you can use Klang and GCC at the command line with just any text editor. And it's a very simple, bare bones way to do your work

Demo: Tools

so there are all kinds of different tools available from all kinds of different vendors. How are you supposed to find them in order to pick just one of them that you might want to use? Well, that's one of the reasons why we have a standards body. This is the website of isil CPP dot org's The Standards Committee. Four. The supposed plus language and libraries. Now this is a great website in its own self. If you're interested in the standards process, if you're looking for podcasts or articles, Blawg posts for people who care about c++. But for now, let's just click on this get started link. Here are links to the various tools you might want to use. Now you don't have to install them through the's links. When I wanted to use clang, I just used apt to do the get and install and everything else and presto I had claimed. But there are links here if you want GCC, if you want playing. And although this says Visual Studio 2017 Link actually points to the latest version, which on the day I'm recording this is officials to do 2019 and this sort of marketing a page that explains why it's a wonderful product has a button down at the bottom for the free download so you can download visual studio. If you're on Windows and you can download, let's say clang if you're on a Mac or UNIX machine and I'm going to demonstrate those three combinations, I'm primarily going to use visual studio for most of the demos. But you should be able to follow along not only doing the exact same demo, but using the files that you get from the course downloads, using those very same files on other operating systems and with other compilers.

What Can You Write?

I'm going to assume that you got some tools and you're ready to Rincon application again. In most languages, I would be able to tell you all applications look like this. Here's what you need to make. But C plus plus again is really unusual. It targets all platforms, and I mean all So yeah, sure, you know your desktops Windows Mac Lennox, obviously. But that's nowhere near all phones as native applications, not necessarily through intermediary frameworks, but then embedded C plus plus is also a thing. So if you want to code robots or the Internet of things, there's someone who's teaching 12 year olds how to program bracelets in C plus plus, make them light up and flash and things according to various triggers, such as time going by or a sensor detecting something. And all of this happens using the same language C plus plus. What's different is the coding patterns that you use and the libraries that you use to create the application so you could learn to write games in C plus plus. But the problem with me doing that when you don't know the language yet is I had to teach you a bunch of foundational game concepts. And then I have to choose a game framework for you to learn, and you'd be learning that as much a C plus plus. And if you wanted to end up working in finance all of that, learning of game wouldn't be super useful. We do a lot of people's plus work in high performance low Layton see concepts including finance. And there you write a completely different kind of cold. Because you're so focused on performance, you could do some sort of a server, something that doesn't even have a user interface. That sounds like a great idea. They're usually very native and tailored to a single platform. Of course, that would exclude everyone who didn't have access to the platform. I could write a corporate application, you know, with _______ and and text boxes and things. But again I'd have to teach you the framework that you used to make that kind of user interface. And if you want to write a game, you don't want to put any time into learning that framework In that user interface. I want to show you the language itself and the Standard library, and I want to therefore show you the absolutely simplest kind of application, one that will work on any platform without you needing any special tools or frameworks. Because the most important thing about all these different kinds of applications games the high performance stuff, the user interface free stuff, the very corporate gooey stuff. All of these applications Air Hole based on the same language. The syntax is the same for all of them, and the standard libraries is the same for all of them.

Command Line

so I know this might sound odd, but I'm going to teach you how to write kind of application. You will probably never write professionally, and that's a command line application. Thes run in depending on your operating system, you might call it a console or terminal or a shell. It writes letters, characters on the screen, no graphics, just ordinary letters. Maybe the odd bit of you know, punctuation and you interact and tell it what you want by typing characters to it Once upon time, you know, this was what we had would say Enter a number and you would say seven. And then it would do something with seven. All right, no graphics, no sound, no animation. But even though you won't write them for riel, thes kind of applications are a common denominator. Whatever platform you're using, it has a command line, and so you can write an application in C plus plus that after you compile it, targeting the right platform, the exact same source code will work on Windows on Mac on Lenox on anything with a consul that makes it a place for us to learn the language and learn the libraries without having toe learn the frameworks and libraries and so on that surround your code and interact with your code when you want to write a gooey application or a game or a server, or what have you focus on that common denominator off the language?

Smallest C++ Application

One very nice thing about Consul applications is that they don't have a lot of code in them. They can be very, very simple. This is a complete c++ console application, and I'm going to prove that to in a moment in a demo. But there's a few things that I want to point out to you. First of all, see Post Plus is case sensitive. Every single letter you see in this application is a lower case letter there, no capital letters anywhere on the screen. And if you were to write something similar but to put some capital letters in parts of it, it would not work. Everything in C Plus plus is case sensitive. Secondly, we have two different kinds of brackets on this screen, and they're both very important after mean. We have what a lot of people call round brackets, and some people call parentheses on my keyboard. There a capital nine and a Capital Zero. After that, on a line of its own, there is a brace. Sometimes people call it a brace bracket or curly bracket. I've also heard face bracket and wiggly bracket. Try to say brace all the time and the last line is the opposite. It's a closed brace, and these braces are different from the round or parentheses, and you can't mix and match them. You have to use them where you're supposed to use them. So if you open a parentheses, E, you have to close the parentheses. If something starts with an open brace later on, there will be a close brace. Always coming these beginning end pairs and they have to match, obviously, and most lines end with a semi colon. And this particular example. It's true that three of the four lines do not end with a semi colon. But as this application gets longer, the into Maine and the begin brace and the end brace stay the same, and everything in between would have semi colons at the end of the lines. Now, finally, although a console application has this structure with a main, it isn't true that all c++ applications do, depending on what platform you're targeting, depending what kind of application it is, it might not, but if you see a main like this, that's a really good sign of this, a console application. So let's see it in action

Demo: Smallest

this is visual studio, and here in the editor window, which takes up the majority of the screen, real estate is the same source code that you saw on the slide. This is the code for a very tiny little console application. It literally doesn't do anything. It starts and then immediately quits without putting any characters on the screen. But it is an application, and it is a thing that you can build and run. So to build an application in visual studio on the build menu and you say build solution, I get two lines of output. First line of output, says the name off the CPP file. In real applications, in real life, you'll have lots and lots of CPP files, and you'll see one of these lines for each file as it is compiled. And then you always get an extra line at the end. Which is that the linker pulling everything together and it's actually made a file called small dot dxy. Here's the folder that my source code is in. Now. Visual Studio has a number of companion files that it keeps next to your source code. If you're not planning to work in visual studio and you get the download, you can ignore these kind of companion files. So there's something here called S l N and V C D. B. You can ignore those here in this folder called Small. Here's the actual small that see PP, which is the code that sort of matters. And these VC X project files again are strictly for visual studio purposes. If you're not a visual studio user, you can ignore them. And if I go into this debug folder these to the actual object fall, I was mentioning earlier. There's another debug folder up here, and it includes this E x e, which is the actual execute herbal. Now I'm going to get a command prompt by holding the windows key and pressing our windows run and then typing cmd for command. This black box If you're old enough, you call it a DOS box is the consul on Windows and in here I can use the CD command to change directories, and I'm gonna grab this little file folder, drag it here, and that will put that path. I didn't want to type all that, so if I do a directory, you can see, there's a file called Small Dottie XY, and if I type that well, nothing appears to happen. But the application does run, and here's a way to prove it if I type something different, says Little. Dotty XY is not recognized as an internal or external command operable program or batch file. And it didn't say that when I ran small Daddy XY. So you know it doesn't do anything. It is a program it is recognized by. The operating system is a program, and it runs successfully in its nothingness. But that's an actual application. And before I leave visual studio, I want to show you some other ways to run. Your application can also run it like this debug start without debugging. It doesn't do very much, but if it had something to do, it would do it here. And I can just press any key, and that consul goes away. So it's your preference whether you set up your own consulate and type the name of the program, or you can run it off the debug menu here. I have a Lennix installation I've already installed cling on it and you can see that under documents I have a folder called Small, and there's one file in it. Small that CPP, and it has the same content as you saw on the slide and the same content as you saw on the windows demo so that I can go in here to the terminal and issue this command. Clang plus plus small that see PP clang plus plus is the command to do the compiling and linking if you try it without the pluses. Plus, if you just say clang, it will appear to work because this is such a simple application. But you'll run into trouble later when we start to use a standard library. So just build a habit from the beginning of saying clang plus plus in the name of the source file, which is small that see PP. You can see that another file has appeared here called a dot out and I can run that and yeah, again, nothing appears to have happened, but let's make a typo tribe be got out. No such file or directory. So as on Windows, the fact that it ran and nothing happened is a good sign. It means we made an actual application from this source code and compiled it and ran it. Now this is the Mac again. I've already installed clang on the Mac. You can see that under documents, I have a folder called Small with one file in it small that see pp and the contents of small that CPP is just like on the other. Platforms are very tiny little console application, and I've already installed clang again the command clang plus plus and the name of the file. And you see that again a file has appeared called a dot out. If I run it, it says nothing. But nothing is good news, because if I were to get the name wrong, I'd get an error message about no such file or directory. So as before, we've actually created a tiny little application which runs and does nothing. And now you've seen the exact same source code, compiling and running on three different desktop platforms


the thing about Demel's is they work. I practice in practice to make sure that my demos are flawless. If a certain file is supposed to exist, it exists. I don't have mistakes in my set up, but when you go to write applications the first time, you might have some errors. Now the C plus plus compiler insists that your code follow certain rules, but it assumes that you're trying to make sense. So as a result, the air messages can sometimes be confusing. Let me tell you that there's an error online. Four. When the real problem is that the end of line three, that kind of thing, you get both compiler errors. You can also sometimes get linker errors, and you need to understand the difference between them and we'll talk more about that. As we go through the course, I'm gonna give you several opportunities to see common mistakes and what a particular compiler error message means. And I really encourage you to make some deliberate mistakes and see what happens so that you can understand later when you get that message. Oh, I remember what causes that and you'll know how to fix it. But You should also know that compilers in addition to errors, give warnings. The difference is, if you have a compiler error, you don't produce an output file and e x e. You're in a dot out and therefore you can't run your thing, but with warnings, it makes that execute herbal for you. But you probably shouldn't ignore the warning. And you should probably actually do something about it and not just say to yourself. Oh, hey, it runs. That's fantastic. You need to figure out why you're getting that warning. We don't have very much code in our sample application to get wrong, but I'm going to show you some errors.

Demo: Errors

I'm going to start by deleting the execute herbal, and then I'm gonna make some deliberate mistakes. Let's start by forgetting the semi colon. If I build it, says Syntex. They're missing semi colon before close brace bracket, and it also says, failed in capital letters. And then down here says zero succeeded. One failed zero up to date and zero skipped. If I take a look back in the folder, there is no small Dottie XY. We didn't successfully create something for me to run this output. It says. Six comma one right here and that means line six column one. I can actually double click this, and the cursor gets put in the place where the error is. That's part of what using an integrated development environment is all about. It'll do things like take you to the line where the error occurred. The problem is, this isn't really where the problem ms right from is this missing semi colon from up here. Like I say, it does its best. It doesn't realize that you were missing a semi colon until it bumps into something that's not allowed. When you haven't had a semi colon yet, I could make another kind of error, like spelling return wrong. And this is a code aware editor. It knows that this isn't okay. Return is a special key word in the language. Without the you, it's just some letters, and you can't just type some letters like that if I build it. It says that I don't know what return is. And also before you say zero, you should probably say semi colon. That's the other thing. You need to know what compiler errors. Sometimes when you get more than one, you just need to fix the 1st 1 Sometimes all the others air caused by it, trying to make sense out of something that's kind of gone a little bit off the rails, so always fixed from the 1st 1 down. And it's a good idea to compile after you fix the 1st 1 and see if that magically fixes all of them. So I'm just gonna put it back to a good state so you can see that it's succeeded and that the E x e file is back in here. Something that surprises many new C plus plus programmers is how different the air messages are from compiler to compiler. In fact, the air messages in most compilers got a lot better As soon as they got good in one, everybody had to kind of keep up with the competition. So if I go over to my Lennox machine, do the same thing, get rid of this a dot out and then I'll make a mistake. We'll start by taking away the semi colon. Run the command again. It's his error expected semi Colon after return statement. And there's this little asking art with the hat and pointing at the place where the semi column probably should be and notice. Here it says three colon 10. So this compiler is able to figure out the problem is out here, not at the beginning of the next line. Let's fix that one and misspell return. Try again. Their use of undeclared identifier retrained and to its credit, it doesn't also throw in a complaint about how there should probably be a semi colon between retrain and zero. The way that visual studio. So fix that try once again, and this time we get a doubt out and we're back in Happyland. Let's just repeat on the other platform, delete day dot out. By the way, if you're new to command lines, whether on Windows, whether on Lenox, whether on the Mac and you're wondering how I'm getting my old commands back without having to constantly retyped them up, Arrow up Arrow is your friend. So again we clang plus plus it and pretty much identical, expected semi colon after return statement and the little green Ask er trying to show me where it thinks the problem is. So if we deliberately misspell, return and compile again, use of undeclared identifier retrained and then just to be complete, make it perfect again. And you see the a dot out file appear so again on all three platforms. If you make specific kinds of mistakes, you get specific kind of error messages, and you can learn how to interpret what they're telling you. They may not all will be the same in terms of, especially where they tell you the problem is, but you can figure it out based on what it's saying to you.


C plus plus is on language that doesn't belong to just one vendors, so you can get compilers for all kinds of platforms from all kinds of places. In this course, I'm going to use visual studio because that's what I'm familiar with. But everything will work with other compilers and tools. And from time to time, I'll show you how to do particular things in the other compilers just so that you don't end up trying to puzzle it all out by yourself. The same source code will work. You can download the course files and just pull out just the relevant dot CPP files and later dot h files. But we'll talk about that later and ignore all of the bits and pieces of files that help visual studio to do its thing. This works because Samples plus is a standardized language with a standards committee. So as long as all the compiler vendors implement the standard, the exact same source code will successfully compile and run in any set of tools. The heart of the tool you use is to build your source code into execute herbal code with a compilation step by the compiler and then followed by a linker step. When you only have one file that seems really pointless. As we go through this course, we get into more and more files. It'll start to make more sense. The output of the linker is an execute herbal. That's what you run. It was called small Dottie XY on the Windows boxes and a dot out on the others. You can run an application right from inside visual studio or from a command prompt. And when you're using a command prompt or terminal to compile the code, that's also how you can run it. You can also double, click and execute herbal on a lot of platforms. I didn't show that, too, with smallest because it doesn't do anything, so it would just run an exit and you might not even see it. But as we write more complicated code, you'll get a chance to see that when you write a console application. Specifically, you have this structure with the int main and the round parentheses, and you have to follow that particular structure in order to write a console application. And now that you've seen it, you can start to put some real code into those council application, so it actually does something

Stream I/O and Local Variables


I know this course is aimed at people who don't already know a programming language. But I also know some of you may have seen code elsewhere, and in some languages there are keywords to get certain things to happen. For example, if you want to print something, there's a keyword print. C plus plus uses functions and objects and classes for just about everything, and really tries hard not to add keywords where they're not needed. There are things going on in C plus. Plus, they don't look like function calls that are, and I'll show them to you As we go, you can take a pile of functions or a pile of classes or a mixture and put them in a library and let other people use the code you wrote. And then they get linked in to your application, along with the things that you wrote. Generally speaking, there's a part of the library that has to be we call included into your code and actually compiled by the compiler. Every compiler that meets the standard includes a library called thus Standard Library, the C++ Standard Library, and they're configured to know where to find it because they were installed together. That means that without writing very much code at all, you can start to use code other people wrote and build your application up out of that.

Stream I/O

the C plus plus standard Library is enormous, and I'm not going to cover all of it in this course. Nobody covers all of it. In any course. In fact, it's quite likely that nobody knows all of it. You just know the parts that you need for the kind of work you're doing. So I'm going to start with the part of the Suppose plus Standard library that provides a capability called Stream Ill. I'll stands for input output stream. I'll means getting input because people type something on the keyboard and putting out put onto the screen. It can also include reading things from text files and writing things out to text falls. There are other places input could come from and other places output could go to, and as long as they support streaming, then they can be used with stream I'll parts of the library. Now this is different from record based or fixed I'll, you know, back in the day in the eighties, you might read files that had a particular format, and you could jump ahead to the 15th line and get the 10th field on that line. Stream doesn't work that way. Stream reads from the beginning to the end, so you can't really use stream. I owe to build a database or even to just go to the middle of a very large file and get what you want. But that doesn't mean it's useless. It's great for the keyboard and screen, and it's also okay for certain kinds of files. I'm gonna be focusing on it for the screen. Supers, plus has a lot of punctuation in it. You haven't met much of that punctuation yet. Some of the punctuation is what we call an operator like if you add two numbers two plus two. The pluses. An operator. It's in between the numbers, and it says, How do make them interact with each other? So this operator, which is two characters, both less than signs. But it's a single operator, and it means take whatever is after this operator and send it to the stream that was named before the operator. And there's the opposite direction where you can take the stream before the operator and send some data from that into typically a variable. And that's how you can read input from the keyboard. Sounds fine, but where do I get a stream from? Well, don't worry. The library can create objects that represent useful streams and specifically see out. That's how you always pronounce. It stands for consul output, and it represents your screen. So if you send characters to see out, they will appear on the screen and see in Consul. Input represents the keyboard. And so if you're ready to read from CNN and somebody type something on the keyboard, you'll end up getting those characters in your program. So let me show you some examples. Here's how you read this line it says stood. See out. That's the full name of Sea out. I'll get to that in a moment. Then these air called. I believe this stream and one's called the insertion of one's called the Extraction, and I never remember which is which, cause I tend to pronounce the mus from stood See out from Hello and this will put everything between the double quotes _ _ _ _ O exclamation mark onto the screen. If you do too stood see out from hello in a row, you'd see Hello, hello. With no space between them and both on the same line. If you want it on a line of its own, you actually have to put the new line character in there. I have to tell you a little bit of history because C and C plus plus both go back to a time before you know graphic interfaces. There was always this requirement to put special characters into streams, especially if they were in files. But even if they weren't and so double quoted strings in C Plus plus have this built in capability that air called escape sequences and you also see them in single characters. But we'll talk about single characters a moment, So if you need to put a tab or a new line character or whatever in a regular string, you do it with an escape sequence, and they always start with a backslash. You can even escape a double quote if you want to put a double quote in your string instead of having it marked the end of your string. He's a backslash double quote, then carry on and then you'll eventually need a real double quote to end the string. So what you see here, back slash end? That's the escape sequence for a new line, and when you send a new line to the console, it will make the cursor move down to the beginning of the next line. And that way the hello will be on a line of its own. And whatever you print next will not be smushed up against it on the same line. You don't have to glue them together into a string like that, with the escape character kind of embedded. You can send things separately, and that's what you have to do when the things you are sending are of different types. Like if you wanted to send a string and then a number, you would do it by using the operator twice, and here I'm using different types. The double quoted String Hello is a string and the single quoted slash and that follows. It is a character, single character, and that's an important distinction that will come back to

Demo: Stream Output

I've made another tiny little console application. This one's called Output, that See PP, and I have tested this code on the other platforms. If you want to work on those other platforms and you get the files for this module, the on leaf, all you need is this output dot see PP, and you can compile it and run it exactly as you saw in the previous module, with the small that CPP have added two lines to the program. The first is this. Include. Whenever you use a library, you're going to use the include directive and the character that it starts with. You might like to pronounce that hash number Sign. Octo Thorpe. There's lots of different names for this character, and it is a special instruction to a part of the process we haven't really talked about, called the Pre Processor, and it's separate and apart from the language. So it's actually as part of the compilation process. Bring me in everything in this Iot stream because I want to use it. The second thing that I've added is Justus. You saw on a slide stood see out from Hello and you'll notice there's no backslash And in this one, If I build the project and the build succeeds and this is a command prompt in the debug folder of that project and then I run output, you can see it says hello now on Windows, it automatically moves down to the next line. I have to tell you that when I run this exact code on the other platforms, the prompt actually appears right after the Hello. So you don't get an automatic new line put in on other systems, but I do happen to get them on Windows. It's a good habit if you want your stuff to be on the line of its own, to be in the habit of doing it on a line of its own. So let's put a new line character, and you can stack as many different things together with the from operator repeatedly, and they'll just be all chained together and they'll all come out is output that builds When I run it, you see the extra line now it doesn't have to be a string. It could be anything. I could put a number in here, and that's what you see on the screen. Now. I can duplicate this line with copy and paste in visual studio. I just have to output statements in a row, and there you see them each on one line. If I take away the new line character, then you see they're still on the same line. You're in charge, you ask for what you want. I'm gonna put my new line character back because I liked it. And finally, I'm gonna show you how to sort of hide something temporarily. And it's quite common to put output statements in your program so you can figure out what's going on. And then once you figure out what's going on anymore, you don't want the output. And that's one of the reasons that we use to comment code. When I put these two slashes at the front of the line, the line turned green. That's because this is a code aware text editor, and this line is now invisible to the compiler and doesn't cause anything to happen. So now when I run it, it just says 34 because the hello part has been commented out, and that's not the best use of comments. Comments are really more for explaining what you're doing and why. But we're not really doing anything that needs to be explained. We're just messing around and you can see that anything you put after a comment is completely ignored. So if I were to write, I'm just trying stuff here. Not surprisingly, that gets me all kinds of compiler errors. You can't just type some words in that you feel like typing in. But if they're in a comment, then you can. Let's put our hello back and I'll read it. It's back to the 34 new line. Hello, New line. You can use comments toe leave notes to yourself in your code for next time. Here's where I left off. Here's what I still need to do or to explain what you're doing and why Comments are on important part of programming. A lot of demos don't have many comments in them because we have only a limited amount of lines on the screen to show you the important stuff. But I'd like to encourage you to comment your code as you go. Explain what you're doing. Explain why you're doing it. Leave an explanation for the next person who is probably gonna be you tomorrow. Who could do with a reminder right

Some Syntax Notes

I want to call out a few things you saw in the demo to make sure that they stick with you because they're important. I showed you a comment. Once you type a slash slash from there to the end of the line, that's a comment it might look like. Code. It might not look like code. It doesn't matter. The compiler won't read. It won't try to understand it. It's simply a note to your fellow humans, including future You you saw in that code. I had double quotes around multiple characters like _ _ _ _ O and single quotes around single characters. And I know it looked like it was two characters. It was a backslash on an end. But that's an escape sequence that maps out to the single character called New Line, which you can't type any other way. Single quotes only belong around single individual characters. When you put double quotes around just one character, you make a string literal anyway, and I will later explain why this distinction matters. For now. Look closely and carefully because if you use single quotes where double quote should be used or vice versa, you may get errors that are really hard to spot. So one of the first things to look for is, um, I using the right kind of quote and as you saw pretty much every line in the demo ended with a semi colon. All of those see out statements. Always look at the end. I will point out when we come across the occasional line that doesn't get a semi colon at the end of it, but you should expect that normal lines of code will have semi colons at the end of them.


Well, now it's your turn. In this course, there's several places where I'm going to ask you to write some code on your own. For this exercise, start with output dot CPP. You can get it from the downloads, or you could type it in. It's pretty short from just looking on the screen, but then change it so it prints more words and more numbers. Whenever you want to use multiple characters, words and groups of words, remember to use double quotes. You can put a backslash ends whenever you like. You could embed them into the middle of strings or send them to see out on their own with single quotes around them. You can type in numbers like I did the 34 in that demo. Or you can put in simple arithmetic expressions two plus 23 times seven. That kind of thing. You may need to experiment a little, cause I haven't told you what all the operators are, but that's one way to find things out. Plus and minus or obvious multiple. I'll tell you its star and divides is this forward slash the regular one. That's by the question, and not just integers try 6.2 or 7.3. What happens if you send those to see out? This is not the time to see what it does if you ask it to do ridiculous things that are not possible. Que three divided by zero is not possible. It's not a number that could be represented on the screen, and what happens when you do that is probably something that it would be better if there was someone at your shoulder to explain to you. So just don't do that. Similarly, you can take a string like Hello and try to add a number to it or multiply it by a number of those kinds of things. You will get error messages, but they won't be error messages that you currently understand. So confine yourself to things that do make sense. Three plus 14.7 minus 2.3 That kind of stuff. Mix and match. Run the program and just get in. That habit makes some code. Change some parts of it. Save it, build it, run it and you'll figure out what the rhythm is on your particular machine. You know, sometimes when I'm using ah, command line compiler. I'll make a bunch of changes and forget to safe. Then when I build it and run it, it builds and runs the old code, and I don't understand why I don't see my changes. All right, I gotta remember to save, So just take five or 10 minutes and play around going around that cycle, seeing what happens and getting comfortable and familiar with writing code that you thought up and running it and seeing what it does.


in order to use stream ill. You have to include angle, bracket, io stream, close angle bracket. You saw that on the slide. He saw that in the demo code, and we call this including a file in your application, right. This is how it looks like. Once again, this is how you bring in a library. This is how you get to use someone else's coat. There are literally hundreds, thousands, millions off things you could say instead of Iot stream there, that would bring in different capabilities. And for Iot stream, that's all you have to do for everything in the C plus plus standard library. That's all you have to do, just include it. There are other libraries out there where you also need to link it in. But I'll show you that if and when I show you those kinds of libraries and whoever is telling you about a library like that and you want to use it, they'll tell you whether there's something you have to Lincoln or whether it's what's called a header only library


Here's a problem that I want you to imagine. You're including a library, and it includes something helpful that's called I don't know rectangle. And then you're including some other library, and it also has a rectangle. And those two things are very different from each other. And you don't even want one of those rectangles. You just want the one from the first library and not the one from the second library. How can you make sure you get the one you want? Well, good libraries are in what's called a name space, so all of the things in them have a full name, and the first part of full name is, in a way, the name of the library. Sometimes it's a short form or what have you. So then you Comptel, you're too in this case, rectangles apart, but calling them by their full name that includes their name space. The things in the standard library are in the name space called S T D, which is short for standard. So when you want to use something from a name space, you call it by its full name. STD, colon, colon, see out the colon. Colonists called the Scope resolution operator, and you'll see it again in some other contexts. It is a single operator that's made up of two characters. Suppose postures does this. You just need to get comfortable with it. Now you can imagine if you had, ah, 100 places in your code where you talked to see out. It's great that we're not getting a conflict, but it's kind of aggravating. If I'm not set up for a conflict, there isn't another see out anywhere. Why do I have to keep saying STD colon colon See out all the time? Why can't I just say see out while you can? You have to set something up to tell the compiler when I say this, I mean this longer name. There are two ways to do it, and one is better than the other. The not so good way is to say, using name space STD. That says every time you see something that doesn't make any sense much don't think has been properly brought in. See if putting STD colon colon in front of it would fix it Great. That can accidentally bring in some things you didn't intend to bring in, so a better approach is to name specifically the thing you want to use from the name space. So here what says using STD Colon colon. See out from now on, when you say see out, you mean stood see out. Excellent. That also has the advantage of telling people what you're using for my all stream. In the case of I all stream specifically, it's not super important. Everybody brings in, I'll stream to you see out and maybe seeing. But there are other libraries that might have 100 things in their header file when you included, and you're only using two of them. And by making these statements using name space Colon, Colon, the one thing I'm using using name Space Colon Colon. The other thing I'm using. You tell people what to things you're using from that header. So that's actually a form of documentation, and at the same time it saves you typing the name space Colon colon in front of every single time you use that thing

Local Variables

I hope you enjoyed doing the exercise Printing out. Hello, Goodbye. My name is doing some simple arithmetic, trying some things that worked on some other things that didn't work. But if that was all your application could do, it wouldn't be a very exciting application. Just printing out a bunch of hard coded text applications get interesting when they do stuff, calculate things, figure things out, decide whether to do this or that, and the first step in that is to have local variables. Variables in C plus plus have a tight, so it's not a thing to keep any old information in. It's a thing to keep a number in or a thing to keep a string in or thing to keep a date in. Variables have a type, and, as you'll see shortly, C plus plus is a type safe language, so it enforces your decisions around type. Now some types, like integer, are built into the language and some or what we call user defined types, but you should know that some of the users are actually library writers. So, for example, when you use I'll stream, you use a variable, which is not a local variable called C out and it has a type, but you didn't write the type right? The person who wrote the Ill Stream library wrote the type. So there are some things that feel pretty built into us because they come as part of the standard library. Technically there user defined types you must declare a variable before you put a value in it before you use it for any purpose. And part of declaring it is saying what its type is, along with what its name is. So, for example, this line int limit semi colon declares a variable called Limit, and it is of type int type comes before the variable name this line float rate semi colon declares a variable called rate, and it is of type float these air, actually not fantastic lines. And I'll tell you why. Variables of built in types like int and Float float by the way that stands for floating point. And it's kind of a bad name because it's revealing an implementation detail that you don't care about. But afloat is a non integer number, you know, like 3.7 or minus 11.2 and where they're not initialized for you. So if you just say in limit, it's not got the value of zero. It literally has whatever used to be in that memory before, effectively a random number. And that's bad. Some user defined types are initialized for you, but as a best practice when you declare a variable, you should initialize it at the same time. And you do that like this, and limit is equal to 100. Now. Limit is the name of the variable enters the type, and 100 is the initial value, so it'll be declared and have that value put in it, and then you can change the value later. That's what variables do they bury here. Float rate equals 0.23 if you make it a habit of always initializing your variables when you declare them, you can ask the compiler to figure out what's the appropriate type to keep that value in. So this line Auto X equal. Seven. You see the comment slash slash x is an integer Now this is important because there are languages where variables could be whatever you can put like a number in him. And then a minute later, you can put the date in them, and then you can put a string in them, and then you can just reuse them with whatever And simple spots does not allow that everything is strongly typed. X is an interior exactly the same as if you'd said into X equal seven. You just didn't have to do the thinking of, like, what would be a good type to keep seven in that the compiler can do. You don't have to do that.

Type Safety

I want to expand on type safety because it's really an important C plus plus concept, C plus plus in forces, the types of variables. So you can't just say it's a variable, whatever it is a variable with this type. Like it's an intern, let's say and then that's its type forever and it can't change and expressions like two or two plus two. They also have a tight and they have to go together. Now it's okay to do what we call promoting. So if I have an integer like three and I want to put it into a variable like rate that I declared as float, that's fine. You know, it basically gets promoted to being three point. Oh, and now it's a floating point number and it's kept in the float variable. That's fine, but the compiler will warn you if you throw away information. So if I have 4.9 and I try to put it into that limit, there's nowhere to put the 0.9 part right. The compiler will warn you that you're trying to put something into a type that it's not right for it, and again, this is true whether you said int limit float rate or whether used auto and initialized something. If you initialize a variable with an integer and say auto X equal. Seven X is an integer, and if you try to put 4.9 into it, you'll get a warning exactly the same as if you had said into X in the first place. Now certain combinations, you don't get a warning, you get a flat out error. So, for example, if you put a number like 4.9 into an integer, it's possible to figure out what to do about that. I can throw away the 0.9 part and just put four into the integer. I can figure something out, but some combinations, they just don't make any sense. Say, for example, want put hello into an integer What what on earth would I put in there? There's no sensible way to handle that and remember that you also have expressions, so makes sense to multiply two integers er and had to adjourn afloat. But what would it mean if I tried to multiply a string and a float mean? It's just a nonsensical thing Toe asked to do. And in those cases, the type safety will get you a compiler error as opposed to a warning When you're just using things that are completely incompatible. Typical, you'll see warnings if it's the wrong kind of number and errors if it's just two things that can't be combined.

Demo: Local Variables

I've added some more code toe output. The first thing I've done is right after include I'll Stream. I've put the using stood, see out and that way throughout the rest of the application. I can just say see out is that having to say stood, see out That saves me some typing and makes it a little easier to read as well. The old code is still here. Just with stood Colin Collins taken off. But I've put in some new codas well here. I'm printing out to blank lines on declaring online 11 a local variable called I, giving it a value. I know on the slides the values were just liberals, like two or seven. But you can put an expression here as long as the expression turns out to be an integer or something that's OK to put into an integer that I'm gonna print that out, I'm gonna change the value of I so you don't mention it's type again. The next time you talk to it, you just call it by its name. I equals the new value here I could again to a hard coded number like seven or an expression like two plus two. But the expression can also include variables, and the only variable we have is I. But this takes the old value of I multiplies it by three and puts that into I. And then we're gonna print it out again. So if I run this C 34 hello couple of blank lines a four and a 12 taking a look at the code again. 34 Hello, Isaac with a two plus two, which is force we print out. I came out for good. I times 34 times three is 12. Put that and I print that out. Excellent. So it's working as we expect. There's another way to do this, and that's with the D ______. Now, exactly how you debug is a little bit different in every tool, But in visual studio, I could go on the debug menu. It's a toggle break point, and this red dot appears in the margin. Then, when I hit this green arrow, I can actually watch the program run. So there's Yellow Arrow here saying, This is the line that's about to happen. This symbol represents stepping over the line. Now the yellow arrow is down a line, and it's about to do this. Anti equals two plus two. I can step over that down here. I can see that I has the value for step over this line. I still four. Nothing's happened. I equals I times three. Step over that. Now I has the value 12 and at this point, the yellow arrows pointing to that final see out that's gonna print out the 12. If I flip over to the output, you see the 34 the hello in the four. But you don't yet see the 12 because that line hasn't run yet, so you can actually watch your program run a line at a time, see the values of variables and see what happens and whatever D ______ you have in the tools you're using, being able to use it is a fantastic way to understand what's going on in your program. I'm gonna stop debugging because I want to show you some mistakes and surprises. I've added some more code. We have a second variable now, which is called J, and these names are not great. I and J. They're the sort of names that developers use when they mean adds Justin Integer I don't really care. And while that may be appropriate in a demo in real programs, you want your verbals toe have names that represent what they do like this is the number off entries and this is the limit. And this is the total so far and riel understandable words for now we have I and we have Jay and you see, I'm gonna take I and try to put 4.3 in it. And then I'm gonna take seven. Divide that by two and try to put that into J. If I build, My compiler is warning me here, and I'm gonna double click to go to the line. The warning is, as it says down here in the blue, conversion from double to end. Possible loss of data double is like float. It's a non integer number. It just can hold more decimal places of precision. When you type a number like 4.3 in your code, the compiler treats that as a double. So anyway, you can't put 4.3 into an integer. You have to throw away the fractional part. And so it's warning me. There's a possible loss of data. Interestingly, there was no warning for the next line. If you look at the open again Onley one warning but seven divided by 2 3.5 Right, let's run this. It prints out on the last line for and three. So the 4.3 When it went into the integer we threw away the fractional part and it became just for with the seven divided by two. When you have expressions like this, the type of the expression is based on the type of the things that are in it. Since these are all integers, the compiler works out an integer version of seven, divided by two and can't fit 3.5 in an integer. So it just keeps the three and then it puts three into J without any warning. It doesn't warn you about the loss of data in the calculation of your expression, which is sort of a shame. Now, at this point, you might think that it is rounding, but I want to make it clear that it is not just gonna replace my calculations for I and J. So 4.9, if we were rounding, would come out us five. I get the same warning and if I run it, see the last night of output is four and one. 4.9 comes out as four. We don't round we truncate and nine divided by five, which is 1.8 comes out, is one we truncate. I never believed that the compiler will round for you. It will not now. What if I try to be silly and put hello into an integer I cannot convert from? And then it goes on. There's a lot of stuff. There's no context in which this conversion is possible. Like, you know, there's just you have done a really bad thing, and that's actually good. This is what I call the compiler is your friend. You can't do things that are nonsensical. You can't try to put a bunch of words into something that's supposed to hold an integer that's type safety right there. So if I want to actually hang on to some variables that have fractional parts, I can make a double or a float local variable. So here's a float called F Again, a sort of throwaway name in real life, you to use the name that represented what it stood for. I can put 4.9 in there and we'll print it out and you'll see the 4.9. It's going to have the same issue when I Duthie integer arithmetic though nine divided by five it's not gonna come out as 1.8. Let me show you Get to mornings now one here when I'm putting the 4.9 into the integer and one here about truncating from double to float because double is a more precise number type than float. If I ignore these warnings and run, see the prints up 4.9 and one. So Float F is successfully representing 4.9 and life is good, but nine divided by five is still getting truncated down to one. And then we successfully put the one into our floating point number. That's probably never what you wanted. And I mentioned that the reason that was happening is because all of the numbers in the calculation were integers. So this is how you fix it. You go to that nine and you say nine point. Oh, now when I build, you get the same warnings about Double two ends and doubled. Float there. Okay, And now that last number comes out as 1.8 because the expression 9.0, divided by five, comes out not as an integer expression. We do actually calculate 1.8, and that's we can put into F because it's of a type that can hold 1.8 with the integer variables. Could not. Now I don't tell you all of this to say, Wow, c plus plus is so difficult in its picky That's exactly the opposite of what I want you to hear. What I want you to hear is C Plus Plus is a strongly typed language, and this typing permeates everything it does, even when you just type something right into your source code. Like two plus two. It has a type, and you can't mix and match types. There are certain cases where it just warns you and throw some of the data way, but you really should never mix and match types. If you doing some integer calculation, keep it in an in ginger. If the CAA collision doing is not an integer calculation, if you care about the part after the decimal place then don't do it with integers. Do it with floating point in double numbers. A compiler will protect you from doing things that make no sense at all, like trying to multiply two dates, and it will keep you on the straight and narrow in terms of thinking clearly about what you're storing and what it represents.

Keyboard Input

I said I would show you stream I'll, but I only showed you the old part so far, just output. But now that you have local variables to keep values in, we can talk about the I part input because you can get something that someone typed at the keyboard and put it in a local variable where you can work with it. For example, if I've already declared an integer called I and I say see in into I two character operator and then someone types some numbers at the keyboard impresses enter whatever numbers they type will end up in that integer I you can imagine. It's probably a reasonably difficult job to take a pile of characters and actually turn them into a number. Like If I type the minus sign before the numbers, it'll end up being a negative number. And if I I'm putting it in a float and I have type a dotted decimal place in the middle of it, it's gonna convert it into a floating point number and so on. None of that's your problem. The Iot stream library takes care of that for you. You just say I'd like you to put what they type into this variable. Of course, the type rules still apply. As always, it's a very tight, safe language and library.

Demo: Keyboard Input

I've added another using statement up with the top. I'm still on Lee, including Io Stream. But now I've added using stood See in so that I can just type C in anywhere down here and it'll mean stood seeing and down here at the bottom of added what we call a prompt where you write something onto the screen to let people know what to expect, enter a number and then see in into I. You see how the pair of operators is in the opposite direction, as it was for the sea out statement. And then I have a c out statement to show the value of I. This builds, Let's run it here. You see all the output from earlier demos, which you can ignore. And then it says, Enter number. Well, type 44. And if I just sit here, nothing happens. I have to press enter and then it prints out 44. If you don't necessarily believe me, that's really using the number. Let's print out high times to build that renate, and this time I'll choose 11. Press enter imprints out 22 which is two times 11. So, just like that, I'm able to ask the user ________ information and get that information from the user. Right now, the only thing we know how to do it is printed back out under the screen. Maybe with a little bit of arithmetic, multiplying it or something in the modules to come, you'll learn how to do a lot more with the information that your program gets hold off.


in this module. I showed you how to write characters onto the screen and read them from the keyboard, using capabilities from the standard library. It's part of that. You learned how to include a library file and how to use name spaces to be able to get to the things the library file provides to you. You saw how to declare local variables, and they always have a type, and that's their type forever. And you saw that expressions like two plus two or seven, divided by three also have a type. There are rules that the compiler and forces, either in the form of warnings or just errors, and the program won't build that keep you from mixing and matching types. So you only put the appropriate kind of values into your variables, and I've hinted at this you'll see more of it later. New types can be written and added used by your applications. You're not just restricted to the set of things that are built in, which is good, because the set of things that are building is pretty small

Flow of Control

Flow of Control

the phrase flow of control refers to the way that your code executes. Normally, it's top to bottom. That's what you've seen so far in all of the Demel's first line of main rooms and then the second line of main runs. And if there's more, the third, the fourth and so on until you get to the end of Maine, where it says return zero and then that's the end of it. There are keywords in the C plus plus language that change that behavior. A very important one is if this is a way of branching. If you were writing a game, you could say If the player has the key, you know the door will open for them optionally if can haven't else. So if the condition of the F isn't met, maybe you do one thing or another thing, but the else is optional. You might do one thing or nothing. In addition to branching, most programs contain some form of a loop. A very simple loop is a while. You have the program. Repeat Siris of actions. As long as some condition remains true, there's a slightly more complicated to write, but paradoxically easier to use loop called four, and they're a little bit interchangeable. Anything you could do with a while, you could do with a four, and I'll show you all of these keywords in actions very shortly. If while and four all rely on conditions and a condition is a logical expression that can work out in the end to be true or false. So, for example, the condition X greater than sign. Zero means if X is greater than zero, that's a true and when X is not greater than zero, including when it's equal to zero. That's a false and have put parentheses around brackets around the condition as a reminder. Because an ifs and wiles, you must have those brackets you can just write. If X greater than sign zero. You have to put the parentheses in. They could be a little more complicated here. My condition is whether or not why, minus two. His less than be C plus plus has all kinds of operators. That's special punctuation and an important category. Operators are those that can compare to things you see greater than and less than already on this slide. There isn't not surprising set available. Some of them are two characters long. So in order, I have listed here greater than greater than or equal to less than less than or equal to equal, to and not equal to. And let me spend a little bit of time on these last two when you want to ask a condition in C plus plus whether or not X is equal toe, why you have to use to equal signs you can write a condition if X single equal sign Why, but it won't do what you think. Well, actually set the value of X to be whatever wise value is right now and then in a little return. That and if it's anything other than zero, it'll be converted to true. And so you'll go into the F and you'll be very confused by that behavior. So to equal signs to compare and the exclamation mark equal exclamation mark throughout C plus plus means not. So that's the not equals operator. All of these operators return either true or false, and no matter what kind of a condition you right. No matter how complicated it is, he will eventually be reduced down to either true or false and you'll go into the F or you won't. You'll keep going around the loop or you won't based on the results of your condition.


I'll start with If this is your simple branch, for example, like it right? If round bracket I is less than J. Always the round brackets on the conditions, then an open brace. Any number of statements one or thousands, although your programs a lot harder to read when it's a lot of statements and then a close brace. Whatever statements are between those braces, they will run on Lee when that condition returns. True. Technically, if you want just a single statement to run when it's true, you can leave off the braces. But I strongly recommend you never do that. Just because the compiler will let you do something doesn't mean it's a good thing to do. And there have been some very serious riel bugs in code that was in production worldwide that cause significant problems because somebody came along and added a second statement after an F and didn't fix up with brace brackets, and their brain just kept seeing what they wanted to see instead of what they'd actually written. If you always put the braces, that will never be you put the braces now. Sometimes you just want do this. If this is true, But other times it's like if this is true, do this otherwise do that. And for that situation, we have the else keyword. You can only use an else right after. If you can't have one just floating in space and same deal, you have the brace brackets, and in between you have the statements that are going to run when the original condition does not work out to true. So in this particular case, when I is less than J, the first set of statements will run. And when I is greater than or equal to J, the seconds at a statements will run. That's an if, and simple as it is. You can build an entire world out of that once you know how to put the pieces together.


when you want to do things over and over, you used the key word. While you figure out some condition, it could be a simple is just a variable name in this case, Keep going. Or it could be the same sort of condition as you saw in the If, like I is less than J. If the condition is true, the loop will happen. Just like the if the things that are gonna happen when the condition is true are surrounded by braces like this, and just like the if, you could technically omit them if there was only one line. But you don't ever want to, even though you can. If you see someone else's C plus plus code that leaves off the braces when there's only one line that's running in a while, or only one line that's running after an if you'll know how to read it. But trust me when you're writing the code, put the braces in, so the thing about a while loop is that it may not run even once the condition is checked. If it's true, the loop runs. When you get to the bottom brace, you're gonna come back up to the top and check the condition again. If it's still true, you're going to do the loop again. When you get to the bottom brace, you're gonna go up to the top, check the condition again. If it's not true any more, then you're gonna leave the loop and continue on running the code. That's after that close brace. So you must have code in the loop that will change that condition in some way. So if I was comparing I and J, the body of the loop has to change I or J so that their comparison can change. Here we have this keep going variable that's controlling our loop somewhere. There must be some code in this loop that sets keep going to false. One way might be if some particular condition is met. If you were looking for something and you found it, you might set a variable to indicate that you found it. Whatever you've got to change, whatever is controlling the loop in the loop. Otherwise you have what's known as an infinite loop, and that feels like your program being hung or stuck, who are not responding and it's not what you want So when you're designing something with a loop, don't just think about the circumstances under which you want the loop to keep going. Also, think about what's going to trigger the loop, actually stopping and not keeping going anymore.


you could get by with just the if and the while, but I really also want to show you the four loop. It's an important part of suppose. Plus, on the surface, it seems a little bit more complicated, but these three parts actually make it easier to use than a while loop. If you remember the while loop I showed you on the previous slide, we would have had to set keep going to something probably true before we ran the loop. And then the condition was whether keep going was tour false. And then, somewhere in the body of the loop, we had to change. Keep going in orders. Stop the loop. The four loop kind of spells all that out for you and leads you through the process. There are three parts to it and look carefully. The three parts are separated by semi colons. A lot of people expect those to be commas, and they don't get the behavior. They want those air semi colons, so the first part is called the initial Isar. The initial Isar can declare a variable. That's the most common approach. So said into loop equals zero. You could also just give a value to some other variable that was declared earlier, but it's more typical that you are declaring the variable is you go the continue condition. That's the middle part. In this case, loop, less than 10 is just like the condition in a while. The four loop will keep going as long as this condition is true. So for this particular loop, we're gonna start the variable loop at zero. And if you look ahead a moment, you'll see that we're going to increment it by one each time. So go 012 when it gets to nine. Nine is less than 10. So we'll go through the loop and then it'll increment again to 10. And 10 is not less than 10 and we will not go through the loop. It will go through the loop 10 times with the values zero through nine. And that's a very common c++ behavior to do everything starting at zero, and as a result, you see a lot of less Stan rather than less than or equal to. You could write this condition as less than or equal to nine. But we just don't you just idiomatic Lee. No When a loop goes from zero to less than a number, it's that number of times. So if I see zero less than 100 I know it's 100 times zero through 99 that's why we do it that way, rather than having to add and subtract one to account for. Starting at zero. The third part of the four loop is called the Incremental, and here we've written Loop Plus Plus, that's another operator. And when you use it on a single variable like this, it increments. That variable loop is an integer so plus possible incriminated by one. You can actually do that anywhere that you want to add one toe a number rather than saying X is equal to X plus one. You're gonna say X plus plus. So if you were writing a loop to count something, for example, you could increment How many things you had found. I just the variable name plus plus and that will bump it up by one. But in this four loop, we're gonna start at zero zeros. Lesson 10. So we'll do the whole loop when we come back up to the top, will run the incremental er, so it'll plus plus upto one one is less intense, will run the whole loop, and someone, and remember, the three parts are separated by semi calls. Then this is probably getting boring. Now the thing you want to do in the actual loop is surrounded by brace brackets. Unlike the while loop, this loop body doesn't need to change a variable that's involved in the condition because the incremental will change the variable that's involved in the condition. That's why I find it easier to read and use. If imagine you had a 20 line while loop, you were carefully reading through the whole loop to see if any of it changed the variables that are in the condition. Where is here in this four loop? All that information is up at the top. It's easier to read, and just like the if in the while, the braces are technically optional. If it's just one line, as you see here, but use them, always use them, you won't regret it

Demo: Flow of Control

I've written a small consul application that should be starting to look familiar to you. The structure of it. We're including. I'll streams, weaken, put things on the screen, and I'm using stood, See out and stood Seon. So I intend to put things on the screen and ask the user for input. I start with in Maine. Open close parentheses, open brace and down at the very bottom Close brace. In between, I've put a program that I hope you can read. I'm going to read it to you, and then we're going to run it and you'll watch it happen. So I've declared to local integers they're called first number and second number. You know, you could call them I and J or A and B or X and Y, but I like giving things names that explain what they are. Then I'm gonna write on the screen, enter a number and notice how I have a space after the colon. Your program will look a little neater if you do this sort of thing. When the person goes to type, the cursor won't be right jammed up against the colon. Then we have seen into first numbers so whatever the person types, it's going to go into that variable. I'm just gonna echo it out. You entered first number, Enter another, and I'm going to see an into second number. So far, that's just review from the previous module. Now let's look at these three if statements, the 1st 1 says, If first number is less than second number, I'm going to send to see out the first number comma space, and then the value is less than the second number. Let me just scroll over. It's comma space, the value and a new line, and they all end like that, so I don't have to scroll every time. So that's using the less than operator the middle. If uses the is equal to operator, which is spelled with two equal signs. And if that's true, it'll print that they're equal to the second number, and the last one uses the greater landside Now because of how math works on Lee, one of these three ifs is going to be true. That's not a requirement of any kind. It's just how this happens to work with this number. So if I go to the command prompt and run this application. Inter number four. You entered four. Mentor. Another number. Okay, 700. The first number four is less than a second number 700 which I hope isn't a surprise. 21. Let's do it with some different numbers. I'll enter a minus three and minus 27. The first number, minus three, is greater than the second number, minus 27. And you can amuse yourself running that program for as long as you like. It's going to get the math right. In an earlier model, I asked you to try asking the user for some input and then printing it out. And I I warned you not to type things that really didn't make any sense. Say I put 3.6 for my first number notice. It says you entered three and then immediately says, Enter another number. The first number three is good in the ____. Number zero. What What's happening? This is again 4.3. Same thing. What's happening is it's only expecting an integer, and the dot is confusing. The basically input part sir, and zero is ending up in the second number right away before you really have a chance to interact with the system and then you get nonsense for the output. Back when I started learned a program in 1977 we had a saying Garbage in garbage out. If you take apartments expecting integers and you give it numbers with decimal places in them, you don't just get wrong answers. You get something that's like not anywhere near wrong, although it is true that three and four are both greater than zero, so it's sort of partly right. It's just that the inputs all misstep in the same spirit. If I run it again and I type words well, thanks 10 and it thinks one of them is minus a very large number that starts with eight, and this again has to do with how it interprets the things that I type in. And the solution to this is don't type that stuff in. Yet you haven't learned how to do error checking how to make sure that if you ask someone for an integer, they only type an integer we have to start somewhere. And so for now, when you're writing applications like this and when you're testing them, you have to cooperate with the design. So right now we're set up that I'm going to assume you're going to give me an integer. You can learn how to accept any and all input, turn it into an integer yourself and give sensible air messages when people don't follow the rules. We got enough to learn at the very beginning. I just want to show you that I want to go back into visual studio, and this will be different in your tool set. If you don't have a D ______ yet this I hope we'll tell you why you want to do ______ and you can find one for your platform and one that you're comfortable with. But if I come in here and say Run to Cursor, I can step through with this button here and watch the application run so it puts and her number on the screen. It wants me to into a number. Have to flip over here to enter something. Let's enter five is gonna put that on the screen once. Another number you entered. Five. Enter another number. Let's go with 11 and you can see those values five and 11 down here in what's called the autos window, and now I can actually watch which of the ifs comes true and which does not. So if first number is less than second number, the yellow arrow here indicates, were going to run this line. That's going to print out about how it's less than and if I continue to step the next If. If first number is equal to second number, we don't go in there. The yellow Arrow skips down here. It doesn't do the body of this if that's gonna ask if this first number is greater than the second number. And if I say next again it skips over that you just take a quick look at the output, you'll see that it printed out the first number five. It's less than the second number 11 which isn't a shocking mathematical discovery or anything, but I just want you to see if I was 100% sure that everyone had a d ______. I wouldn't need output statements in these little demo APS. We could just look at the values of the numbers, and we could just watch the D ______ go in and out of if statements and we wouldn't need to print things because some of you may not have any ______. All of the sample code does at least print on the screen, but it's obviously more illustrative to watch it happen a line at a time, then to puzzle it out from what gets printed. I do strongly encourage you to experiment with a D ______ for this work. We've already run this application a number of times. It doesn't even really do anything. Imagine if I wanted to make it so that it would run multiple times. I could put a while loop around it. So the entire enter a number you entered on all the if statements are all in a giant while loop that will run over and over again. I could declare first number and second number each time through the while loop. But there's no real benefit to that. And it's kind of a bad habit to get into if there really large objects, integers or little objects. But later Ah, well, care a little bit about this, so I'm gonna put the while here right now. It has no condition. I'm gonna jump down here to the very bottom of the program and put the matching embrace and then in visual studio by holding shift and down arrow Aiken multiples to select a bunch of lines and press tab and push them over. Depending on the editor you're using, it might even do the in den thing for you As you go. Don't get too worked up. But whatever you do, don't do in denting like one line at a time. Space, space, space down arrow space, space space Your editor can surely do better than that. Now, how am I going to run this like 10 times and then stop or until the person says they want to stop? You have lots of options. I'm gonna go until they say they want to stop. And I'm going to do that by asking them if they want to stop or not. And if they say the right value in response, then I will stop. And today we only know one variable type, which is an integer. So I'm gonna ask them to enter a number, and this is kind of going back in time. 40 years ago, applications would be enter one to continue or two to stop that kind of thing because asking people numbers is easy. So up here before the while going to paste in two declarations. The 1st 1 is a verbal of a type you haven't seen yet. A boolean variable which is spelled bull the same lawyers integers or spelt into called Keep going And I'm going to initialize keep going to true and my loop will be while keep going So it's gonna start out is true We're gonna go through the loop at least once And then you know something inside the loop has to change. Keep going otherwise would be in an infinite loop. There are lots of ways you can do that but I'm going to do it this way. I'm going to ask, Do you want to compare another pair? Zero. If you want to stop, not compare anymore pairs any other number for yes. Then I'm going to use Seon into answer to put whatever they typed into an integer. And if whatever they typed is equal to zero, keep going will become false. Otherwise, keep going. We'll still be true and we will well, you know, keep going. So let's run this. I'll build it. And then in the command prompt again and her number, so I could do five and two. The first number five is greater than the second Number two. Great. You want to compare another pair? Zero means no, I'll say one. And her number. Okay, 11 and minus seven. First number 11 is greater than the second number. Minus seven traffic. Compare another pair. This time I'm gonna say zero for no, and we stopped. So now this demo, it's starting to kind of do things, pushing it to call it a game unless you're a very small person. But you can see how you know this could turn into something that was actually a useful application from these tiny building blocks. Just for the sake of completeness, I'm going to give you and else so on this first, if if the first number is less in the second number, we're going to say the first numbers less in the second number Else we're going to say the first number is not less than the second number, just so you can see and else and so you can step through and else in the D ______ if you want to and I'm going to throw in a four loop. It's the same four loop that you saw on the slides. I'm gonna put it before we ask if you want to go again. This makes no sense in the middle of comparing two numbers. I'm just gonna count from 0 to 9, but it's just a place for me to put some code. I'm going to build this and read it, and I'll compare four and four. I don't think I've compared to numbers that are actually the same before, so you see what happens. It says the first number four is not less than the second Number four. That's this else happening, all right, was it? If it's less than two, this else do that and we did that. And then it says the first number four is equal to the second number four, and that's from this. If which hasn't been true before, and then I have 012 improvised in at nine. That's from this four loop that you can see in the background and they're all in one line. There's just a space between the numbers, which is why then says, compare another pair without jumping down to the next line. And if this was a slightly more serious application, I'd probably want some new lines in there. But that's fine. And I'm gonna say No, I don't need to compare any other pairs because you've seen this run now. So you've seen if else while and four and seeing how to put an application together from these.


it's your turn. I want you to write some code of your own. I want you to write a guess. Mine number game. You'll probably want to use flow. The sample I just showed you as a starting point. If you're using visual studio, DoubleClick flowed out. S l N It'll open up everything you need for using anything else. Just get flowed out, See PP. But you're going to change it so that instead of asking for two numbers and telling you which is bigger, it only asks you for one. The other number is the secret number, and we're gonna kind of compare those until the person gets it right now in a riel guest. My number game, you generate a random number, maybe within a range. But let's start simple with hard coating. Hard coding is when, instead of calculating something, the number is just in the coat so you could write into answer equals seven. And that would be the secret number that the person was trying to guess. When it's working, you can change the code, so that answer is 11 or minus three or something and make sure it still works and you can build and run it as many times as you like. So here's the overall structure of guests. My number. You ask the user for a guess, and then you compare it to the secret answer and you tell them your guess is higher than the secret answer. Your guess is lower than the secret answer or congratulations. Your guests matches the secret answer, and you're going to keep going until their gas matches the secret answer. So in my demo, we kept going until someone said, I don't want to keep going anymore. You're gonna change that. So you keep going until they get the answer right? Until they guess it. I haven't shown you how to cope with people entering words or decimal numbers when you're just expecting an integer. So don't feel that that's something you have to cope with. And when you're testing it on Lee, enter integers. This is about understanding ifs and wiles, not about error checking and converting things back and forth between different kinds of numbers. Okay, it's just write a kind of simple, nice spirited application. If the secret answer is seven, you say enter your guests. Let's say they say eight you say it is too high. So you ask them again into your guests. Then they say to and you say to is too low. Until however many times through the loop, you say into your guests and they say seven to use Yes, seven. Is it? You're right. But you know you're not comparing to seven, right? You're compared to this variable called answer. So then you can edit your code and give answer a different value and run it and you should end up guessing the new secret number. I want you actually pause the video player and go and do this now. And don't go any further until you've written code that plays. Guess my number when it's working, I'll show you my solution. But really don't skip trying to do it yourself. It's time well spent. I hope you wrote some code. I hope it's working. I'll show you my code now. And maybe if you have a little bit of a problem in yours, this will get you the rest of the way there. So in my code on this occasion, my secret answer is going to be three. And I'm declaring a verbal called guests to put their guests into. And I'm run my wild lupas while they haven't guessed it yet And just, like, keep going, I'm gonna start. That is true because after all, when we first start, they haven't guessed it yet. Print out. Guess my number. You see in to get their guests. If the guest is equal to the answer who have winner I print out that they're right and I set the not guest variable to false because it's no longer the case that they haven't guessed they have. So not guest is false that maybe you called your variable guest or answer is correct or got it or time to stop or anything else and that's fine. But then you have to use the Boolean operator. Not that I haven't talked yet. Ah, so you start out with success is false and you say while not success and so on this way you start out that they haven't guessed it and you set that to false once they have. If they didn't get it right, perhaps the guest is less than the answer will say too low. Or perhaps the guest is greater than the answer. Will say too high. And then here's the end of the while Loop. Come back up around the top of the while. And if not, guest is still true, we'll go in again. We'll have another try. I'm going to build this. If I go to a command. Prompt and run, Guess the number. Dottie XY Is it 11? That's too high. OK, is it minus two? That's too low that I'm going to suddenly get really good at guessing and say, Is it three? Yes, it's three. Let's just confirm it works with a different number. I'll build that. Can I run it again? I'll say, Is it three? No, it's not right because it's five. Obviously, if you've seen the source code, it's a little bit easier, but, you know, simple and silly as guest. The number is this is a game and you've written a game. It doesn't have a super sophisticated user interface, and the replay factor is not very high, right. Once you play it once and you know the numbers three or five or whatever it is, then you played again and the number is still the same number. Z not really compelling. There's not much plot, but it's a game, and it's a game that you can write with Onley, the little pieces of c++ that you've learned so far.

More Flow of Control

samples poses a complicated language. There's a lot of it, and when I pick up a couple little pieces of it to show you, I don't want to deceive you and pretend that there's only those pieces. So I'm going to mention some other flow of control keywords very briefly. Not so you can learn them now, but so you know they're there for later. Let's take switch. Can you imagine writing some code where you were making some decisions and you were writing sort of. If X is equal to one, do this. This and this. If X is equal to to do this, this this and this. If X is equal to three, do this. This this and this switch statement is a great thing for that, and when you need it, you can learn it. There's also another kind of four loop, which I will be covering in a later module when I talk about collections, there's also Cuba called Break that makes a loop stop early and continue, which makes a loop skip some of its processing. You can learn more about those when you're familiar with the basics. There's also something called Do, and there is go to. We almost never used those. I'm mentioning them only for completeness. I don't expect you to learn them. And as I mentioned in an aside return is also a key word that changes the flow of control. You've already met it because our magic main ends with return zero. Soon we'll be talking about functions and then you'll get to meet the return key word in a little more detail. Don't go and try to learn these set of keywords. Now I only mention them so that I'm not deceiving you by pretending all we have is, if else foreign. While there are lots of things that affect the flow of control But the four I've just shown you, if else foreign while are the most useful ones and you can build riel applications using them

Functions and Headers


a little terminology about functions. Before we dive into seeing some and using to use a function, we say that you call it, but before you can call it, the compiler has to know that's an okay thing to do. So technical term is that you declare the function that makes the compiler content that this is an okay piece of code for you to write. Then somewhere in your program, you or the library you're using implement the function. And the technical term we use here is that you define the function. When I say somewhere, you know, it could be anywhere because the Link er's job is to link the function to the code that calls it. So let's see some examples. This is a function at, and I'm actually defining the function here that counts as declaring it. I can do that up above Main and then in Maine, I can call ad, and I want you to see some things about it. Functions have a return type ad, has a return type of int and just is when you're declaring variables, the type comes before the variable. So when you're declaring a function, you can put the return type before the functions name. So in ad means that ad is a function that returns an integer in the round brackets. The parentheses are the parameters of this function now. Some functions don't take any parameters, in which case they'd have empty brackets. But adhere takes two parameters. They're separated by a comma, and each of them looks a little bit like a variable declaration. There's a type and a name, so add takes an integer, which is going to be called X, and another integer, which is going to be called Why, when you call the function, you don't have to pass it things that are called X and Y in your calling scope. But that's what the parameters you give it will end up being called inside the function. Then you have an open brace. I returned statement and a close brace, and in that you may be reminded of the main function that you've been writing all this time without realizing return is the calculation of the return value, and add is such a simple function that that's all it has. It's just using the plus. It's kind of a pointless function, except that it's one you can read and understand. If you give it to integers, it will use plus toe. Add them together, and it will return that integer to whoever called the code. So then, somewhere after this in your source file, you can have a line like into a is equal to add at three comma four. We generally pronounced the open round bracket, as at if you were taught functions in school and your teacher said F at X, that's what that's about. I know you may have had a teacher who said F off X because teachers very but our habit of pronouncing that open bracket at comes from that history. The line in A is equal to add at three Comma four will make a call to the ad function, and once we're inside the ad function, X will have the value. Three. Why will have the value for they'll be added together to get seven will return seven. Control will go back to the calling site, and seven will be put into a notice that everything here is an integer. The compiler will enforce this, and I'll talk more about that after I let you see some successful functioning

Demo: Simple Functions

here in visual studio, I have essentially the code that you saw on the slide I'm declaring and defining ad. It's a function that takes two integers and returns an integer, and the body of it is just that it adds the two of them together. Then, down here in Maine, I'm declaring a variable called Total, and I'm calling ad and passing in three and four to that function and then gonna print out the total if I run it. It says three plus four is seven, which I hope surprises no one. Most of the time, you don't write a function if you were only gonna call it once and especially not if it's only one line. Long functions really come into their own. When they let you achieve some kind of abstraction, you can take something complicated, like calculating sales tax and put it in a function called calculates sales tax and then other people who are reading the code. I don't have to necessarily understand that they can just see that you're calculating the sales tax and continue reading along through in whatever the main is in that application. The reason I use really short and obvious functions in my demos is so that you're not wasting energy on trying to understand the sales tax rules of the place where I live and how they're different from the place where you live and that kind of stuff. We can all agree the three plus four is seven and very quickly See that programs doing the right thing, going to add some more code here. Now I'm declaring a variable called another, which is of type double, and I'm giving it a value by calling Add also. But the liberals that I'm passing to add our doubles their 1.2 and 3.4 they're not integers. And then I'm gonna print out the result if I build this so that I get to warnings conversion from double to end here and here. So it's letting me know that the 1.2 and the 3.4 are going to be turned into integers when their past toe ad. That's a really important warning because, as I hope you remember, when doubles and floats are converted to integers, their fractional points air just thrown away, there's no rounding. Sure enough, if I run this, it says 1.2 plus 3.4 is four. And if you were to do this math in your head and keep the fractional parts, you'd get 4.6, which you'd round 25 But that's not what's happened. The 1.2 has been truncated toe one, the 3.4 has been truncated toe three. Those integers have been added, and that gives us the value of four that you see on the screen. Now. There are lots of ways around this, but one possibility is let's change the function so it works with doubles. Now the function takes two doubles and returns a double. Let's build this, still getting a warning right here because now add returns a double. I'm gonna put that into the integer total. I know by inspection that if I add two integers, there isn't going to be a fractional part, and I don't need to worry about losing the fractional part when you put it into an intra chur. But in general this is a really good warning, because if I was doing something complicated like calculating a sales tax and getting back a double, just putting that into an integer would be silly. So this is progress. Let's run this it correctly, as the integers three plus four is seven, but now it also correctly adds the doubles 1.2 plus 3.4 is 4.6. It's not perhaps the world's most useful function after how we do have the plus key, but it lets you see type safety in action when it comes to function. Of course, in real life, you know the types of the things you want to work with. For example, if you're writing a program that shipping things, how many of them your shipping is an integer. I can't ship you 7.2 socks for 1.3 apples, but the cost of them, or the weight of them or various other attributes of them probably would be represented as a number with a fractional part. So choosing the types for your functions to take in return, it's not complicated. It arises naturally out of what the functions do. It looks a little complicated in the demos on Lee because they're artificial and simple

Type Safety

see Post Plus is a type safe language. The compilers always checking if that's really what you meant to do, we're meant to say, and it often warns you when you convert between types, So when you call a function the parameters that it takes have types, you provide arguments, and sometimes the arguments need to be converted to the type the parameters are. And if that's risky, you'll get a warning from the compiler. So in order to convert the double 1.2 into an integer, we have to throw away the fractional part. The compiler warns you. The function in its body figures out what value it's going to return and returns it, and then you put it into a variable that may involve a conversion, and that may also involve a warning from the compiler. I want you to develop the mindset that the compiler is your friend, that it's warning you when you're doing something foolish, such as throwing away information when you're thinking of things as being the same when they're fundamentally not. I can't tell you how many times a compiler has saved me with these warnings, because I understand that I'm putting things together that don't belong together. When you're working with arbitrary demo code that doesn't have a meaning for you to hang on to, it can feel irritating that you have to get it right. But when you're working with real code, it will be natural, and the compiler will be on your side.


In the demo, I wrote a function called Ad that takes two doubles. This notation that you see here where the parameters don't have any names is old style way of describing a function. It lets it fit more easily on the slide, so I'm using it here. But imagine I now want to add up three doubles. Should I write a function called Add three that takes three double parameters? Should I maybe loop back and change the name of add to add to so that someday I can write an ad for an ad five and so on and will be consistent because it will be called Add to know one of the really cool things about Suppose plus is that function names don't always have to be unique. As long as the compiler comptel the to function calls apart. You can have two functions with the same name, and this is called overloading. In other languages, people will often put parameter information in the function name like how maney parameters it takes, or even what types of parameters it takes as long as the compiler can tell them apart. You don't need to do that in C plus, plus the number. One way for it to tell them apart is to take a different number of arguments. The one way you cannot ever tell them apart is by their return type. You can overload on parameters you can't overload on return type that is, have two functions with the same name. Same parameters, but different return types that's not allowed. When two functions have the same name and take the same number of parameters. In theory, they could be distinguished by the tights off those arguments. I wouldn't call that a beginner technique. A lot of beginners get tripped up by helpful conversions and by some assumptions around what conversions get done with what priorities. So you may not get the exact behavior you expect. I'm gonna show you that in a demo.

Demo: Overloads

I've added an overload of ad into my small program. So the existing ad is there. It takes two doubles, and the new ad is here, and it takes three doubles. There's no requirement that the parameter names be connected to each other in any way. So the two double version of ad works with X and Y and the three double version of ad works with A B and C, and that's fine. They are independent entities. I couldn't just start talking about a B or C in here. They're not in scope in Here are the only things that add knows about his ex and want. And similarly, in this version of ad, it only knows about a BNC when you download the sample code. If you want to, you can try the alternative implementation of add that I've put here, where the three parameter ad calls the two parameter add to get the job done. Not because that's an efficient way to add three numbers, but because it's quite common in bigger and more complicated applications. To have one overload of a function actually call the other overload of the function. So is not to repeat yourself let's scroll down and look at the code of added to use the new function. You can say I've declared a variable called Total of Three and then I'm calling the version of ad that takes three doubles. And if I build this application now, I still have the warning that I had before that you're putting the result of ad into an integer total. But that's all. Everything else is fine, so the compiler has no problem. When I make this ad, it knows to call the two parameter one. And when I make this ad, it knows to call the three parameter one, and that's just fine. I'll run it just to prove that it works. In our new line of output. Down here, 1.1 plus 2.2 plus 3.3 is 6.6. Yes, it is now. One of the things that sometimes surprises people about C plus plus is that you don't have to use the return value if you don't want to. This is a legitimate code. It'll built just that same warning we've had all along. In fact, that's why you can't overload on return type. If you had two functions that took the same number and type of parameters but had different return types. And then you put in a line of code where you didn't use the return type. The compiler would be unable to decide which function to use, so you cannot overload on return type. Instead, you overload on the parameters that it takes. I'm gonna paste in another pair of functions up here above main. This is to overloads of a function called test one takes a Boolean tour, falls and returns that value true or false. The other takes a double and returns. The Expression X is greater than zero. And those expressions you remember from the talk about branching and flow of control they evaluate to true or false. So 1.2 is greater than zero, so that would come out as true. But minus 7.3 is not greater than zero. So that would come out this false. And then I have written three calls to our test overloads. The 1st 1 passes. The literal true bulls can be either true or false, and if test returns true, that's what just putting the function call inside the round brackets does. Then it will print out that it passed the test. The second call passes 3.2 and again just puts the function call in here. You know, you could write this if test it true is equal to true. It's not wrong. It's just not idiomatic c++ and C plus plus. If a function returns a Boolean, you don't compare that bully into true. You just put that Boolean return from the function into the condition. In this case, the if so, that's fine tested. True, just a 3.2. But then down here I have a test where I planned to pass three. And if I build, I get this Siris of errors. It's actually just one error spread over multiple lines. Test and Biggie was called overloaded function. Could be bull test that double here, pull test at Bull while trying to match the argument list. It's just gonna double click to confirm this is the line with the problem. My i d knows that it has put this red wiggly underline under the word test. What's happening here is there is no overload of test that takes an integer, so the compiler is going to have to convert my integer to another type in order to be able to successfully find an overload to call. If I only had the test that took a bull, the compiler would be, Hey, I know how to convert insta bulls. Any non zero number is true. Everything else is false. It's fantastic. I can convert this to a bull and call the version that takes a bull if I only had the version that took a double. The compiler also knows how to deal with that. It can promote, you know, three up to 3.0 theta. It's a floating point number. It's a double. It can pass it in to test, and we'd be away to the Racists. But when you give it two choices, then it throws its hands in the air, the word ambiguous to a compiler. It's like a swear word, as I don't know what to choose. And now you have a problem. Now what could you do about it? You have lots of choices about what to do about it. One is that you could explicitly convert three to a Boolean or to a double in order to make the right overload Get chosen by the compiler. Or you could write 1/3 overload of test that took integers. Any one of those might be the right choice. It depends on the system you're building. The reason I show you this is not to make you think C plus plus is difficult because remember, my theory is that C plus plus is not difficult, but it just doesn't think the way you and I dio for me three is a number double is also a number clearly just promoted to a double and call the double version. That's, like obvious. If I was doing this with a paper and pencil, that's what I would do would never occur to me to consider converting three to tour false but the compilers and think that way. Types or types and they're all the same and it does what you ask it to do. And if it can't figure out what you want it to dio, then it complains. So in real life, I'm just gonna comment this code out. You would understand that wouldn't be called test would have some real meaning, and you would either write 1/3 overload. The handle integers, or you would explicitly promote that three toe a double or convert that three twitterer false and then pass it to the function, just going to rebuild just to make sure we can. And yes, one succeeded. It's now good.

Multiple Files

did you notice that the demo file is getting kind of long? In theory, you could build an arbitrarily large application out of one very, very large CPP foul, but there would be a number of problems with that. One would be that when you made any change at all, you'd have to compile the whole thing. So far, you have had compile times small enough not to notice. But when you get up into 1,000,000 line applications, you notice compile time. I worked on a system once. It took 45 minutes to compile. Yeah, you go for a coffee, you catch up on your email. 45 minutes is a long time to wait, and you don't want to do it very often. And if you're working as a team, it's just easier to say I'll work on this file and you work on that file even if you have nice distributed source control systems that can work out that both of you have made changes to the same file. Life's just simpler if that's not what you're doing. And even if you're all alone If you have a 10,000 line file, how do you find your way around in it. How do you remember where things are? No individual files that have names are much easier to explore. And to find what you need to change your look at, let me remind you about the build process in C plus. Plus, you start with your source code, say example, not see PP. It's been small that CPP and a lot of these demos and you compile it that produces an object file. And then you link that object file to make and execute herbal example Daddy XY or a dot out or whatever. In real projects, you have multiple files. The compiler compiles each of them exactly once, and that makes a bunch of object files. And then the linker links all of those together. Exactly how you do that depends on what tool your using. I'm gonna show you in visual studio and in a later demo, I'm gonna show you for claim

Demo: Multiple Files

visual studio is an integrated development environment. And whatever i d e, you're using X code, Sea Lion, whatever, they will have similar concepts and mechanisms to this. Over here in what's called the Solution Explorer, there's a list of all of the files that I'm working with, which is one file now, and we're about to change that. So in an I D tool like this, you need to teach the tool ham working with multiple files. And it's usually not a simple as a file appeared in a folder. You actually have to add it to a project or a workspace or whatever it's called in that tool. So here I'm going to ad a new item. It's gonna be a CPP file, and I'm gonna call it functions. Visual Studio opens that file, and now you can see there are two files listed in the solution Explorer. If I go back into small, you can take all these functions, cut them out and paste them in here if I want to. I can now compile just this file, and that succeeds so all these function implementations or passing compilation. But if I come in here too small and I try to compile it. I get a ton of errors and you can see by the underlines that this code, the compiler says I don't know what ad is. I don't know what test is. I don't know what you're talking about, I said. You have to declare functions before you use them back. When they were implemented in here, they were also declared, Now they're not. So if I put them back for just a moment, I'm going to change these definitions into declarations, matting a semi colon at the end to sort of end the sentence and removing the bodies. And the way you can read thes declarations is Hey, compiler. There is a function called at that takes two doubles and returns a double. There is a function called ad that takes three doubles and returns a double. There's a function called test that takes a bull. There's a function called test that takes a double. You can see the function bodies aren't here, but the compiler is content with that promise. Now I can compile and succeeded. I'm going to build the whole thing because that gives the linker a chance to combine the objects from small and function and make my small Dottie XY If I run it, it's just the same as it ever Waas. I don't know if you've seen the true passes. The test in 3.2 passes the test output before because we didn't run in the previous demo. So now the functionality is split across two files, one that has the functions in it on one that uses the functions. But I need these declarations in the file that uses the functions because the compiler has to know that the functions exist on what they take.

Header Files

This is a really important rule. You can implement a function in one file and calling in a second file as long as you tell the compiler about that function, what its name is, what it takes, what it returns, do you declare it? But you can imagine it might be kind of tedious to keep pasting declarations into the top of filed. If you wrote a really helpful function and it's used in 10 other files, do you really want to pace that debt into all 10 of those files? Well, that's where Header falls come in because, yeah, if everyone of your file starts with 10 lines or 100 lines off, here are some functions I use. There's a lot of problems with that. For one thing, imagine that I have 100 files and about 50 of them use some function called update, and I have changed something about update what parameters it takes, or the type it returns, or I decided to spell it differently. So now it's called Update inventory. Now I have to wander around trying to find all the places that were declaring updates so I can change them to match the new declaration. It can also be hard to see the code that matters if every file starts with 50 or 100 or more lines of heroes, some functions that I promise you I use somewhere down here later. So with a header file, you can put all the declarations in a single file and include that file wherever you use those functions you've already met. The include directive When you go, include I'll stream cause you want to send stuff to see out or read stuff from See It you can also use include for your own files. As an aside, this symbol hash number Sign off the Thorpe Scott lots of names is not technically a compiler directive. It's to something called the pre processor that runs before the compiler. The pre processor used to be really important in the life of a simple suppose programmer and is becoming less and less important thes days. For now, you use it for include, and that's about it. The pre processor is really ancient technology, and it's really simple technology. When you include a header file, the entire contents of that fall get pasted in right where the include statement was then. Later, when the compiler compiles it compiles all your source code that was in your CPP file, along with the pasted in Things From Header Files. All is one giant. It's called a translation unit. But while it may look messy to the compiler, it looks neat to you. You can see what's being brought in from elsewhere, but you don't have to wade through lines and lines and lines of function declarations and as well. If you need to change your function declaration, you just change it in the header file and all of the places that include the hair file well, they'll get the new version.

Demo: Header Files

I'm going to add another file in visual studio. This time I'm gonna choose _________, and I'm gonna call it functions. You can see that visual studio has put a pre processor directive in here for me that says pregnant. Once you can ignore this for now, it generally will not hurt you. And explaining what it saves you from is a topic for another day. It's a fairly harmless thing that you can just ignore until you're working on really large projects and you have some other considerations to take into account. I'm going to take all these declarations from the top off small and put them into functions. Whitespace doesn't matter to compilers and pre processors at all, but it matters to me. So now I've put the two ads together in the two tests together. That's nice. And then I'm going to include functions where I had that line and I have to pause for an important decide when we included I'll stream we used angle brackets. When you include your own code stuff from your project, you use double quotes, part of the configuration of your compiler that's done automatically when you install it, but that you can override is to teach it where toe look when you use angle brackets to include a file and where to look when you use double quotes to include a fall. And you could jump through a ton of hoops to fix this from the defaults. But you don't want to do that because what punctuation you use here is sending messages to people who read your coat. When I see and include with angle brackets, I know it's some kind of external library that's not part of this project. In this case, it's the C++ standard library, which is fantastic because I can look up the documentation for that. And I know how to learn more about it. When I see double quotes like functions dot each has, and I know that it's somewhere in the source and header files for this project. I'm gonna build and my projects succeeded going to run it, and it still runs exactly the same as before. All that's happened is I've split my one file into three files and now I have some maintain ability. If I want to change the signature off one of the ads or one of the tests or at another test or whatever. I will make the change here in the header fall and here in the file that implements the functions. But I won't need to make any changes at all in small because it just includes that functions header. And there might be in a really large project, 2030 100 files, including functions dot h. And none of those need to be edited by me. When there's a change in function study each. I'm going to repeat this now on the Mac, I have the same three files. Here's function dot h just declaring the two tests and the two ads. Here's functions dot CPP. It includes functions dot h. In this particular case, it really doesn't matter. They work fine if you don't, but it's a common thing to do if you're implementing a bunch of things to include the header that declares the things you're implementing. Not wrong. But then that you can see this is the same coat, including the comment with the alternative implementation. That's because I copied the files between the machines and then here's small that CPP, including functions dot h again with the double quotes and then exercising it in exactly the same way. So when I go to compile it, I just say both CPP files on this important. I don't need to mention the header Fall header file is brought in by the CPP files. I don't compile it itself. I'm just listing my to see pp falls. Silence is golden. That means compilation has succeeded. When it runs, it says the same things as before. And now on the 12 machine, you can see that I have the three files functions dot CPP functions dot h and small dot see pp and I have them open in this tabbed editor. So small includes functions and then does the same stuff is before Here's the functions header Here's functions dot see pp same command because it's clang plus Plus it's not platform specific. Same silence that lets you know it worked and same output

Building with Multiple Files

I want to revisit that diagram about building when you have to see PP files known to your project. If it's an i D E that works with projects or work spaces or whatever, or named on the command line with clang plus plus as part of the compilation Step the pre processor pastes in the contents of the includes, which could be thousands of lines. But that's not your problem. So, for example, small that CPP includes I'll Stream, which is a file and that gets plunked in there for compilation. But Small also includes functions that h so that also goes into small that see PP functions. That age also goes in two functions dot see pp. Don't worry about repetition when it comes to the compiler. That's the compilers problem. You don't have to repeat yourself. So then each of these CPP files with their include files, paste it in our compiled into O. B J files, and then those are all linked together to make the execute herbal

Complier and Linker Errors

I've mentioned before that Demel is always work, and that can leave you at a loss when your stuff doesn't work. So I want to talk specifically about kinds of mistakes you can make when you're setting something up. With more moving parts like this, you have to declare functions before you call them. Well, that's something you can forget to do. You can just decide to be a great idea to call add without having declared ad. Perhaps because you forgot to include the header. That ad is declared in, or perhaps because you remember to include the header. But there's a mistake in there and adds not declared in it. The compiler only needs to know that the function exists. It doesn't care about the body of the function or anything like that just needs to know that the function exists has to be declared. But you can also get linker errors, and these can happen when you forget to implement a function. So you declare Oh, I have this ad function, takes two integers returns an integer, but then nowhere in any of your files Do you actually, you know, implement the function. So the code for that function isn't in any of the CPP files. You generally find that one fairly quickly. What you don't find is Oh, I wrote the code, but I'm not linking in the O b. J that came from the CPP where I wrote the code and the number one reason why that happens is because you didn't add it to the project workspace, whatever the word is or you didn't include that CPP on your command line. If you're compiling at the command line, you can spend so much time and trouble trying to fix something that's not wrong. People will tell me. It's complaining. I have no add function. But look, you can see I'm including the header file. And if you look in the header fall, you can see I'm declaring the function. Yeah, but it's a linker air. Are you compiling the CPP that implements the function? Oh no. Or the other way around have implemented the function. I don't know what's going on, why we're getting this air because you haven't declared the function over where you're calling it and so it doesn't know to go looking for it to have the linker link in this implementation. Trying to fix what isn't wrong will frustrate you. So being able to understand what your air messages are telling you will make your programming experience so much smoother.

Demo: Compiler and Linker Errors

I'm going to demonstrate some errors to you so that you can see what they are. And I strongly encourage you to do this for yourself so that you can recognize and get familiar with these error messages and, uh, go beyond this. Try even more than what you see me doing. The first thing I'm gonna do is I'm going to comment out this declaration of ad. Obviously, I could delete it, but I want to put it back, find out, build. I get errors in small, we think. But it won't make any errors in small when ah small wasn't changed. Well, small was sort of indirectly change because it includes functions that h right here. The output says add function does not take three arguments. And that's true because we've now on Lee made a version of ad that takes two arguments, even though I've still implemented a version of ad that takes three arguments Small that CPP has no knowledge about that now specifically for visual studio compiler errors all start with a C. They have numbers. You can look them up on a website. In fact, I think you can hit F one and it will bring up some help for it. But compiler errors start with The sea is an important thing to know. I'm gonna put this back. I'm gonna go into functions and I'm going to take away by turning it into comments the implementation of this function and build again. Now let's not jump straight down to the errors. I want you to first see this line that says functions that see pp And this line that's a small that see pp both of those lines. The compiler is perfectly happy. I've made it a promise. There is a function called ad that takes three integers. Then I call it Everything's wonderful. We Onley gettinto a problem when it says here generating code and this'll error starts. L N k is a linker error. There's a real hard to read. The magic is one unresolved externals and here you can see add double, double double. The linker can't find the implementation of the function to connect it to the place that called it to link it. And that's why I would get a linker air. I can also get a linker error if I forgot to add say functions that CPP to my project so that it wouldn't get compiled and have its objects linked in. There are lots of different things you can experiment with doing. Now. I want to show you the errors on the other platforms. So again I'll comment out that three argument double and the text editor here is not a code aware one. So there's no magical color change to tell me what I've done. If I repeat my compile no matching function for call to at and it also says there is a candidate function, but that's not viable. It requires two arguments, but three were provided. That's pretty good. So there's no indication, necessarily that it's a compiler era versus a link Ehrlich starting with the letter C. But I think it explains itself quite well. If I say that back to what it waas and I'll delete this, I can put it back later. So now it's declared, but it's not implemented. Undefined symbols add double double double referenced from symbols not found, and there's an L. D. Right there is a linker diagnostic, and it specifically says linker command failed. So again you can tell this is a link. Her error that the implementation of ad that takes three doubles is missing over on the bone to machine. Same thing I can comment out the declaration, Save that and noticed This text editor is code aware. Compile again and it's not surprising it's clanging both places. I'm gonna get the same errors. So this is the missing add. There is a two argument one, but not a three. I put it back. I'm delete these. I get the linker error that it can't find the implementation and what I really encourage you to dio is try different deliberate mistakes. What if I don't implement it? What if I implemented? But don't declare it? What if it's not in the header file? What if I don't include the header file? What if have a header file that includes a bunch of functions like in this case, four. And I don't include the entire file, so I get four times as many errors, that kind of thing. And in this way you'll be familiar with these errors. When you make those mistakes accidentally, you'll say, Oh, the old undefined reference linker command failed with exit code would oh, I got you. I know what that is, and you'll go straight to it and fix your problem


C plus plus gives you the opportunity to break up your logic into functions, which you can call. This is always going to be better than just having a lot of code, all in a line if certain things have to be done. Ah lot having functions that you just call satisfies, don't repeat yourself some 100 line calculation and then paste that same 100 lines later. No, just both of those places would call. A function could also enable you to write more expressive code by giving things names like calculates sales tax so that your code actually explains itself to someone who's reading it. Usually you'll put functions in a different CPP fall from the code that calls them. If you do that, you have to be sure you declare them in the code that calls them before you use or call them. I'm an easy way to do. That is by writing a header file that it's full of function declarations. You can then include that header file into the calling code, and it's also quite common to have an include of that at the top of the implementing codas. Well, now that you have a build process that's actually pulling together a whole pile of different CPP files. You can have the opportunity to have a situation where the compiler is happy. But there's a linker error where the linker is happy or would be. But there's a compiler error. And to gain the skill of, well, that's compiler error. I should check my header file or oh, that's a linker error. I should make sure that I'm compiling all the CPP files I think I'm compiling will make you much quicker at reacting when you've made the kind of simple, everyday mistakes that we all quite commonly do.

Strings and Collections


Hi. Welcome back toe. Learn to program with C plus. Plus, my name is Kate Gregory, and I'm introducing you to programming using suppose plus as your first programming language. This module is where you start to understand classes you know in early name for C plus plus was see with classes on. While object oriented programming is not as important a paradigm throughout the industry as it once was, it's still a big way to make your programs organized and sensible. Now a class is a type like int or double, but it's defined by a programmer, not by the language committee. The way you use most libraries is by using classes from them, and later you'll write your own classes as well. I thought it gets started by showing you two incredibly useful classes in the standard library string and vector. While you're learning how to use them, you'll also kind of learn what is a class? What is this all about? So we'll cover plenty of ground

Objects and Classes

So far, the applications you have been writing have been lines of code that you wrote and calls to functions from libraries in some languages. That's what you build applications out of your own code and functions. But in C plus plus, your applications are also made of classes and objects. For this reason, we say that C plus plus is an object oriented language. Now it doesn't insist on everything. Being an object, you can write that application with no objects in it. That's what's been happening so far, but it allows you to have objects and classes. A class is the idea, or the concept often object. What data All of the objects will have all objects. That air of a particular class will all hold the same kind of data, although they'll have different values and what it can do. This is really important. A number you know, like three can't do anything, doesn't have any capabilities of its own. But an object which is an instance of a class can do something. So, for example, I might have a class to represent a date, and if I have a date, I might be out. Ask it what month are you in? Numbers? And it would say, Oh, it's month 11. What month are you in words? It's month, November. So if the classes, the idea or the concept, the definition objects are individual instances. So if I had a class to represent dates, then I could create an object and put the right values in it to represent May 1st 1990. I could make a different object and put values in it to represent December 3rd, 2017 and then I could call member functions on those objects. Hey, tell me what month you are or tell me what year you are, that kind of thing. You've already met some functions that don't have anything to do with classes, you know, like add that takes two integers and returns an integer. Those air actually called free functions or nonmember functions. So is to tell them apart from member functions. And C plus plus has both kinds off functions, and they're both fine. You don't have to make on a utility class to put a bunch of free functions in, because every function has to be part of a class. You could have free functions. That's cool, but you could also have member functions, and they are very powerful, too


almost every application needs to work with text and the string of letters representing a message or something that someone typed a person's name from a database. We call that a strength, and there's a header file in the standard library called String that you can bring him with includes string, the same as we were doing include I'll Stream, and that brings in this very useful string class. Once you have a string object, you can put text into it and you can do things with that text. For example, I can compare two strings. I can put two strings together to make a longer one, all different kinds of manipulation. And I can't answer questions like, Does this string have a space in it? Or how Maney ease are in this strength? Many people when they first see some code that works with strings in C plus. Plus, I feel that it's just a built in type like integer, and it certainly feels that way because you don't have to install anything special to use it. It's part of the standard library. It's just there, and also because when you know how to do things for integers, you know how to do things for strings to There's no special All you got to remember, it's an object and do it a different way in C plus plus, and you'll see that when I start to show you some code. If you know you're gonna have to work with the Unicode characters, say Chinese characters or Korean characters or really anything that wouldn't be on a North American typewriter, then you maybe need Unicode. And there is a slightly different thing called W String W stands for wide that will work happily with Unicode characters. Everything you learn about string applies to W strength, so I'm not going to tackle it separately. You first met operators when we were talking about comparing two integers would say less than. But it's also an operator to say, plus or minus to add two numbers or subtract two numbers, and you can combine two strings with the plus operator. So string one plus string to and that will produce a new, longer string. There's a shortcut, e plus equals for if you want, attack something onto the end of a strength. If you want to know if two strings of the same you use the equals equals test exactly the same as if you want to know if twin teachers with the same and there's less than and greater than and not equal as well. And if you want to put a string onto Consul output, the from operator that you used with C out works just fine. And the into operator that used with CN also works with strength. And this is a really important concept. You already know how to compare two integers using greater than less than and so on. Well, that's how you compare strengths. You already know how to add two integers with the plus. Well, that's how you add strings and you know how to print an integer onto the console. Well, that's how you put a string onto the console. So as you learn how to do things, new things become easier and easier to learn. It's just a thing you already knew, and the amount of knowledge that you have starts to really increase rapidly

String Member Functions

although strings do a lot of things exactly the way integers do, they're not integers their objects, and that means they have member functions. So when you have an object that is a member of the class string, you can call member functions on that object. So I might set up a string called Greeting and initialize it by using quote Hello comma space end quote and then, of course, have a semi colon at the end of the line. Now greeting is a strength, and I can call member functions on greeting if there's particular things that I want. So, for example, there's a member function called length. It doesn't take any parameters, but you still have to use round brackets when you call the function of parentheses, So greeting dot length, open parenthesis, close parenthesis is a call to the member function length of string, but it runs the member function on that particular instance greeting. Now here the length of hello comma space is seven characters the five letters in hello plus the comma, plus the space so that number seven will be put into the variable for length. There's also a member function called sub stir which stands for sub string, and it gives you another string that's only part of the original string, and the characters are actually copied into the other string in this example were starting from character to, and that's the third character. Indexing and C plus plus is always zero based, So character number zero is H character number one is E and character number two is l as the first parameter of substance. The second parameters. How many you want. We want three, so we'll end up with L. L O in that string s two. There's another version of sub Oesterle where you don't provide a second parameter. You just say where to start, and if you use that one, you'll go from there to the. But there's more. Here's a member function called fine Again. It's greeting dot find. I want to search specifically in this string and not in some other string that I'm not using right now, and you can pass a little string to find, and it will tell you what position it found. That hat you can pass a single character or like I have here a string like H E. And it's again going to be zero based. So it'll tell you that it found H E starting at character zero. The string class has a lot of member functions, and on CPP reference dot com, which is one of my favorite reference sites for this sort of thing, there's a member function called at. There's a member function called Begin. Here's Length, which I just showed you here's clear, clears the contents. Not surprising and lots more. Besides, nobody needs to memorize all of the member functions of a particular class. What you really need to memorize is that the people who designed the class thought of most things you might need. And so if you have a string and there's something you want to do, there's a good chance you'll find a member function of it. That will help you to do that. But let me show you some of this code in action

Demo: Strings

I've written code that's doing some work with strings, and I hope you can just read it right along with me because I intend to write things on the screen I've included I'll Stream and I'm using stood, See out and stood CN. And then, in addition of including strength, an amusing stood string. That's the full name of the class that I've been just talking about its string so far. So here I declare an instance of a string. I write to the screen with a prompt and whatever the person types of the keyboard I put into that variable. Then I'm going to take the literal string. Hello, comma space and name. That's the variable that's just gotten a value because the person typed on the keyboard combine them with the plus and put the result into greeting. Then I haven't if on the condition in the office that I'm gonna compare that verbal name to this literal Kate and all comparisons and samples plus are case sensitive. So the capital K matters. If that's true, if they're equal, I'm going to use plus equal to add some more onto the end of greeting. There is no else so there's nothing going to be additive. It doesn't happen to be me. And then I'm going to print greeting on the screen. If I built this and then run it the first time, I say someone hello, someone for running again And I say Cate and says, Hello, Kate, I know you. And just to show you about the case sensitivity here it is with a lower case K. It's the same as when it was someone doesn't match the special treatment. This code is all just using operators to interact with strengths. Now I'm going to add some code to use a member functions. There's quite a lot to show you here, so I'm going to go through it a bit at a time. First, I'm calling the length member function to put at length into this integer l. That's fine, then I want to print out that whatever greeting we've built up so far is this money characters long, And in order to do that, I wanted to have double quotes in the output. A double quotes when I'm building up, my string would mean well, that's the end of my string, and so I'm using escape characters. I talked about these in an earlier module. Here they are again, but now we're escaping the double quotes. And because visual studio is a code aware text editor, it's actually doing some color coding for me. So if you look at the first thing I pass to see out, it's actually three strings being added together. The first string contains an escaped double quote and both the escape and the double quarter shown in this kind of purple e color and then there, surrounded by beginning and end double quote that are red, and I add greeting to that. And then I add, and this is all surrounded in red double quotes and escape. Double quote a space. The word is an another space. All of that gets sent to see out. Then l get sent to see out, and then space characters long dot gets sent to see out and then a new line character. So here you're seeing both the use of the member function length and the use of escape. Double quotes in the output. Now remember the greeting that was built? It was hello comma space and then the name and then possibly the extra. I know you exclamation Mark. So this code is calling a function and passing the result of that immediately to another function. And this is a very c++ thing to do, and I wanted to show it to you sooner rather than later. You kind of read from the inside. So here I'm taking greeting and I'm calling find and in passing in a space. So it's looking for the first place in the whole string where there's a space and we know that greeting is going to start Hello, comma space. So that's where it's going to find its first space. It take that result and I add one to it. So now that means the character after the space. Well, when we built greeting, it was hello comma space and then the names. So the character after the space should be the start of the name. That number, whatever it is, is gonna get past two greeting dot substance. And there's a version of substrate that only takes one number and you get from there to the end of the string. Now if I run this and I say that my name is someone, greeting will be Hello, Someone and this process will end up extracting from the sub string someone. So the next if says, well, if beginning is equal to name. Yep, that's what we expect. But remember when I say Kate, then when we go from that first space to the end, we won't just get Kate will also get the I know you part and we won't get this thing that says expected result. I'm gonna build this and then run it. First time I'll say someone. It says Hello, someone. That's what it used to say. You see the double quotes in the output. That's because there were escaped double quotes in what I passed. To see out is 14 characters long you can count on confirm that's true. And then you just see someone, which is the sub string result, and that's the expected result. But if I do it again and this time I get my special treatment, it doesn't say expected result because the sub string comes out as Kate I know you. And that doesn't match Kate. Look at the code again who were comparing this beginning to name. And Kate, I know you doesn't magic eight. So it just didn't print expected result. This particular logic may not be super useful. It doesn't start to feel like a game or anything the way guess my number might have. But it does show you how to use these three member functions that I chose to teach you length, find and sub string. And you can practice whatever you would like to dio variants on this program to see how to work with these three functions. And if you're feeling brave with some of the other member functions of string before I move on, I do want to show you that the D ______ understand strings as well as it understands integers. So I'm going to run through this one time in the d ______ to show you that. So I'm just going to step repeatedly and you can watch the yellow arrow moved down. We're gonna put who are you on the screen and then ask for input. Don't put Kate and I can look at name and see that it has the value. Kate and I can also see that down here. If I step over now, you can see that greeting is Hello, Kate. We go into the If you can see the yellow arrow moving, so greeting is gonna get longer and you see here that greeting has got longer printed on the screen. Calculate the length you can see. Here it's 24. We do that output statement, I'll just show you it. And then we calculate beginning, which is, kid, I know you. We print that on the screen. We do this if, where we're gonna compare Kate. I know you too, Kate. That does not evaluate to true. So we skipped the rest of the braces and then we were finished. Your D ______ may work a slightly different way, but that same power to be able tow watch it executed to able to look at the values of both your strings and your integers as you go through. That's how you come to understand the way that applications work.


Now it's time for you to write some code. I want you to write a program that asks for two words. And then if the first one's longer, it says something like the first word is longer. If the words of the same length it says the words of the same length. And if the first one's shorter, it says the 1st 1 is shorter. You probably going to want to start with your guests, my numbers solution. And if you're guest, my number runs over and over again. You can let it keep running over and over again if you want, or you could have it just run once it's up to you. But instead of comparing the value of the numbers as you did with guess my number comparing the guests to the secret number, you're going to be comparing the lengths of each string. It shouldn't take you a terribly long time to write, experiment with it, get it working, and then remember how when guests my number was working, I showed that if you typed in things that weren't just simple integers, weird stuff happened. I want you to experience some of that so once it's working, and it can figure out whether cat is longer than turtle or not. See what happens if you actually enter multiple words. Instead of just writing cat, you write cat space turtle space stock. After I show you my solution, I'll show you why it behaves oddly when you give it phrases instead of words. It is an important thing to learn. Don't try to fix it. For now, you're just writing a program that takes a word and then takes another word. But I will show you how to cope with people entering phrases when you were expecting words as part of my solution. I hope you have working code. You hit pause, you got it going. That's fantastic. Let me show you. My solution should be starting to be familiar by now that we start with including Io stream and using see out and see in and including string and using string. And I declared two variables called word one and word too prompt. You enter a word. Put that in word one, and I promise you enter another word, put it in words to, and I just have three. If statements and for each one and comparing word one dot length and word to dot length Your ifs could be in another order. That would be fine. I'm first checking to see if they're the same. I checked to see if word one is longer. I checked to see if Ward one ish short her. You could have done this the other way around, right? Could safe word to length is greater than word one length. I see a lot of benefit in when I have multiple comparisons like this of keeping the variables in the same order. So it's always word one dot length before the operator and word to dot length after the operator. If you kind of mix and match them, then the operators will have the opposite meanings. Someone could get confused when they're reading, but if yours works, that's important. Is working. So if I run this application, it's a cat turtle. The second word is longer and I don't have a loop that says, Do you want to do another? It's not wrong. If you did, that's fantastic. I'm just gonna run it a bunch of times. A lot of G's only one A. The first word is longer. That's right now. I asked you to see what would happen if you entered a phrase and the second prompt appears. But immediately the output appears. And this is not the same kind of error as when you were asked for integer and you typed in something that wasn't