 You find yourself surrounded with strange and potentially weird terms and fancy jargon. In this movie I review those terms as well as present an overview of the entire programming process. While I'm certain that you're eager to get started with writing code, and you may have already viewed a later movie in this course, it's important to know a few key terms and programming concepts. Programming is where you create software. Software controls hardware, which is the physical part of an electronic device, such as a computer, phone, tablet, gaming console, microcontroller, or some other gizmo. Those instructions take the form of a programming language. For this course, that language is the C programming language, which was developed back in the early 1970s. That's pretty old. And in fact, over time, the C programming language has been considered the Latin of programming languages. Unlike Latin, C isn't dead. Lots of C programming still goes on despite newer and fancier programming languages coming along. But like Latin, C is the foundation upon which many other programming languages are built. If you know C, you can more easily learn those other languages. In a later movie, I'll talk about the programming language's syntax and other rules. But for now, know that the code you write is called source code. It's a plain text file that contains the programming language, all formatted and pretty and written properly. The file is saved with the .c file name extension. To create source code, you use a text editor. Any text editor can do, although some editors offer helpful features like color coding, line numbers, syntax checking, and other tools. The source code is then compiled into object code. The program that creates the object code is called a compiler. The traditional name of the C language compiler is CC, which stands for C compiler. The compiler reads the source code file and generates an object code file. Object code files have a .o file name extension, and they use the same file name as the original source code file. The next step is called linking. It's often forgotten because modern compilers both compile and link, but linking is really a separate step. The linker takes the object code file and combines it with C language libraries. The libraries are the workhorse of the language. They contain routines or functions that control whatever device you're programming. If all goes well, the end result is a program file. You can then test run the program to make sure that it works the way you want it to. And if not, you start the cycle all over again. Edit, compile and link, test run. All of these tools, the editor, compiler and linker, originated at the command prompt or terminal. You can still find them there too. I do a lot of coding at the command prompt because it's quick. More common, however, is to use an IDE or integrated development environment. An IDE combines the tools for editing, compiling, linking and running. It also adds tools for debugging, creating complex programs, graphical tools and other features. Beneath it all, however, is the humble command line compiler and linker. And the process is the same. Edit, compile and link, run. Although in practice, you're going to do a lot of repeating and reworking before you get things just right. The good news is that all the tools you need to begin your programming journey are found free on the Internet. The bad news being that you have to find the right tools and install them properly. This is not an issue for you here because in this movie, I'll show you how it's done. You'll see how to find a good IDE or integrated development environment, a C-language compiler and get everything set up and configured for using this course. You'll find a horde of IDEs on the Internet. Microsoft offers the Visual Studio as its IDE and Apple has Xcode. You're welcome to use those tools, especially if you're comfortable with them. But for this course, I've chosen the Code Blocks IDE. The thing I like about Code Blocks is that it comes with everything you need. Unlike other IDEs, you don't have to hunt for a this or that after the IDE is installed. You basically download, configure and you're ready to go. Obtain Code Blocks by visiting the developer's website, codeblocks.org. Point your favorite web browser or Internet Explorer to that website. On that page, look for the Downloads link. Remember, the page you see here may look different as web pages do change from time to time. Click the Downloads link. Choose to download the binary release. Click the link that represents your computer operating system. Windows, Linux, Mac OS X. For Windows, look for the Setup.exe file that includes the MinGW compiler. For example, on this screen, it says Code Blocks 1312 MinGW Setup. The numbers may change, but that's the link you need. For Linux, choose your 32-bit or 64-bit distro. Select a version of Code Blocks that isn't testing or debug info. Try to match your specific distro by choosing a link to download. And for the Mac, only one option is shown. Click the link to the right of your choice. I'll use Source Forge. The download starts immediately. Wait until it's complete. The next step is to find the downloaded file and install Code Blocks. Open the folder containing that file, which is usually the Downloads folder. You might also be able to access that folder from the web browser. In Windows, double-click the file to open it and begin installation. Work through the installation wizard. Don't worry about any of the options. They're all okay. Eventually, Code Blocks will be installed with a shortcut icon on the desktop. Click the Yes button to start Code Blocks, if you like, although it's not necessary to do so to complete this movie. On the Mac and Linux, you need to unpack the archive you downloaded. Double-click the icon in a folder window to unpack the archive. On the Mac, you'll end up with a Code Blocks app file, which is secretly a folder. I recommend moving that icon to the Applications folder. With Linux, double-click to open the archive. At that point, you'll have to run the install program, depending on how your distro deals with whatever's in the archive. For example, if it's an RPM file, open it to begin package installation. After Code Blocks is installed, you need to get it configured. That topic is covered in another movie. After you've obtained the compiler and IDE, the next step in your programming journey is to ensure that everything is working right and that you're ready to start coding in this course. In this movie, I'll show you around the Code Blocks IDE. You'll also see how to incorporate the exercise files for using Code Blocks throughout this course, and perhaps do some configuring. I assume that you already have Code Blocks installed on your computer, although you may not have run it. If you don't yet have Code Blocks, please refer to the earlier movie on obtaining an IDE. Open and Run Code Blocks. If this is the first time you've run Code Blocks, you may see a prompt reminding you that you've downloaded Code Blocks from the internet. Click the Open or OK button. This program is safe to use. On the Macintosh and Linux, you may be prompted to choose a default compiler. If it's available, I recommend that you select the LLVM Clang compiler as the default compiler. Otherwise, the GNU GCC compiler is fine. The main Code Blocks window looks like this. It's known as the workspace. To the left is the Management panel. This lists projects. The center is where you'll find the editor, where you'll write the code. At the bottom, you see a host of tabs. These can display messages or other useful information. You should take a moment now to configure a few Code Block settings that will help you use the IDE in this course. First, some editor settings. Choose Settings Editor. Ensure that there is a check mark by the options Show Line Numbers. All the other options shown here should be set, which is the default. Click the Choose button in the Font area to set the font. I recommend using a monospaced font, and I set my editor to a 12-point font which shows up better on my screen. Here I'm going to choose 18 points so that you can better see the messages on this screen. Click OK to close the General Settings window. Second, adjust the Build Messages text size. Choose Settings Environment. Click the View icon. Set the Message Logs Font Size value to 10 or 12, which is better to see. Here I'm going to set it to 16 or 18, which is going to show up really well on this screen. Click OK. Code Blocks is now configured for this course. You can quit Code Blocks now if you like. When you quit, you may be notified that the perspective has changed. Go ahead and save the perspective and click in the little box so that you're not bothered with the message again. The next step is to set up the project files. Click the Exercise Files button on this page right up top to download the archive. Before expanding the archive, I recommend placing the exercise files into a specific location on your local storage system. Open a folder management window on your computer. Ensure that you're viewing your own personal folder, which is known as the Home folder in Unix, or the User Profile folder in Windows. If you have a library folder system in Windows, instead, click the address bar to visit your account's folder. If you have a C programming folder, navigate to it. Otherwise, create a new folder named C or C programming. Expand the archive into this folder, or you can expand the archive in the Downloads folder and then move the resulting folder into the C programming folder. I've already downloaded the files into the Exercise Files folder. Let's move them over to the Programming folder. And there are all the files. Now you can delete the archive file you downloaded. There's no need to retain it. We're just going to work with the files here in the C programming folder. Programming involves writing source code, compiling, and linking, which creates the program. You then test run the program to see how it works, or if it works. In this movie, I'll demonstrate that process in code blocks. You'll see how to set up and run a sample project. I'll also show you how to understand and fix problems by using the code blocks IDE. Startup code blocks if you haven't already. You need to see the start page, and if you don't see it, choose View Start Page. Most of the work you do in code blocks is project oriented. Projects can be anything from a small program to a massive online game. For this course, you'll be using the pre-written exercise files. But normally, in code blocks, you create a project, typically by clicking the Create a New Project link. This step isn't needed in this course, because, like I said, I've pre-written all the exercise files for you. But if you wanted to create a new project in code blocks, specifically one of the console applications demonstrated in this course, choose Console Application when starting a new project. Select the C language. Type in a name for the project and choose a folder, such as the exercise folder created in an earlier movie. On the Mac, ensure that the names don't have any spaces or the program can't be run from within code blocks. Choose Release Only, and click Finish. Open the main C source file to begin editing, although this is a complete program. It's presented as a skeleton. Otherwise, that's all you need to know about the code block start page. Dismiss this project by right-clicking on it and choosing Close Project. In this course, you'll be incorporating pre-written source code files for use in the IDE. This saves you typing time, but it also saves you editing time from creating a new project and then editing that code block's pre-written source code skeleton. To open one of this course's exercise files and code blocks, click the Open button on the toolbar. Browse to the folder containing the exercise files, such as the C programming folder. Choose the exercise file 0104 Welcome. Open that file. There you see the source code. C code does not include line numbers, but the editor shows line numbers in this column. These are handy for reference in this course, but also for tracking down errors. And the source code itself appears here. The text is color-coded, which helps you recognize different parts of C, as well as spot errors when things aren't colored correctly. The next step after writing the source code is to compile and link. In code blocks, that step is combined into a single action called Build. To build your project, click the Build icon here. The action takes place at the bottom of the screen in the Build Log and then Build Messages tab. Yes, these errors are on purpose. I want you to see how the errors appear. Click the Build Log tab to review the specific messages. You see what's wrong, which may not make sense to you right now, but it will in the future. More importantly, you see a line number, Line 5. In this case, Line 5 is missing a double quote. In the editor, click here to add a double quote character. If you've done it correctly, then only the text in double quotes is colored blue, not the parentheses or semicolon at the end of the line. Save the file. Click the Build button again. And there's still an error. Click the message to locate the error in the code, or click the Build Log to see more specifics. Some compilers, such as Clang, are more specific about warnings and errors. At the end of Line 6, type a semicolon. Save the file. Build. And no warnings, no errors. That's good. It's what you want to see. Now on the Macintosh, you may see a warning about option S. That's a linker error, and you can ignore it. Click the Run button to witness the program's brilliance. In Windows, the program runs in a command prompt window. On the Mac and Linux, a terminal window appears. In that window, you may also see any startup scripts you've written. Ignore that part of the output. Otherwise, what you see is the program's output, shown here as Welcome to the C language. Close the output window and return to code blocks. In Windows, press the Enter key. If the terminal window doesn't close in Unix, type the exit command and then press the Enter key. I recommend you do this. Otherwise, those terminal windows will stack up. You're now ready to move on to the next project. If you shut down code blocks, you may be asked whether or not you want to save the perspective. Click Yes. C is a language. Like all languages, it has its parts of speech, structure, and syntax. All this stuff is what makes a source code file so delightfully cryptic. But once you understand what's going on and why things are presented the way they are, it begins to make sense. In this movie, I introduce you to the C programming language. You'll understand the structure, what the main function does, and get to know C language keywords, functions, operators, variables, and values. In code blocks, click the New button and choose Empty File. You're now going to type source code. It's only one line. So type main, an empty set of parentheses, a space, a set of empty curly brackets or braces, and press the Enter key to end the line. Save the source code file. Click the Save button. If you need to choose your C programming folder, type the file name dummy.C. The source code file is created and saved. Click the Build button. The code does compile. What you see is the absolute minimum C program known as the dummy. All C source code must have the main function. This is where the program execution starts, and the contents of the main function are enclosed in curly brackets. Here, everything is empty, which is okay, although you might see a compiler warning which isn't critical. A program was created. Click the Run button to run the dummy program. And there's no output. That's predictable because the code does nothing. Like any language, the C programming language has several parts. Keywords, functions, operators, values and variables, and structure. The keywords are the language part of the C language. They accomplish very basic tasks. The good news is that, unlike English, which has tens of thousands of words, there are only 44 words in the C language. Don't freak out. In practice, you may only use about half of these keywords. The real workhorses of the C language are functions. What the keywords do is really basic. To do more in C, you rely upon a function. The functions are held in libraries. The linker's job is to combine the library with your program's object code, knitting the two together to make a program. To use a function in a program, you must incorporate a header file, which defines the function. You'll see how that's done later in this movie. Operators are symbols used to manipulate data in the program. These include the traditional math operators, as well as a host of other special symbols. Values and variables are similar. Values include characters and numeric values. The numeric values are divided between integers or whole numbers, including point values, which contain a decimal part or fraction, or which can be very, very large values, or very, very small values. A variable, on the other hand, is a container for a value. Its contents can change or vary, which is why they're called variables. The values that go into variables are the same types of values you use directly in a program. All these pieces of the language must be used in a specific manner or order. That's the C language structure. The C language uses preprocessor directives to help control program flow. The main function is the first function executed in all C programs. It's required, as you saw earlier in the dummy example. Curly brackets are used to enclose a function's contents. Statements are like sentences in the C language. They can include C language keywords, functions, math, logical comparisons, and so on. Finally, comments or notes to yourself or other programmers, reminders, general information, or other items that are part of the source code but not compiled. Now that you know a bit of the background, let me help you put it to use by completing the dummy program. Return to the dummy source code in the IDE's editor. The main function is defined as an integer function. That means it returns an integer value to the operating system. Therefore, some editing is necessary. In your editor, type the C language keyword int before the word main. Ensure that a space separates both. Now I'm going to clean up the curly brackets, which I prefer to put each on the line by itself. Now I'm going to add a statement to the main function. See how the editor automatically indents the line? That's the traditional way C code is formatted. Type the word return and a number. I'll let you pick any number, although it must be an integer. All type 3. You can type the number in parentheses, as I've done here, or you can just specify the value. If so, you need to put a space between return and the value. Type a semicolon to end the statement. Save. Build. As long as your code looks like mine, no errors or warnings appear. Run. On the Mac or Linux, you may see no output other than the build log, and it says the program terminated with status zero. On the PC, the terminal window shows you the return value. I'm going to fix the font to make it a little more readable. Here you see the process returned 3, which is the integer value I specified in the return statement. To add output to the dummy program, you need to use an output function. C language keywords don't output anything. They're just basic vocabulary, words like return and int. As an example of an output function, you can use puts, which sends text to the standard output device. In this case, it's the terminal window. Program code in the C language is read top-down. Because the return statement ends the main function, I'll add the puts function at line 3 by inserting a new line into the editor. In the puts functions parentheses, you place a string of text, which consists of characters snuggled between double quotes. I'll type, I am no longer a dummy. Save the source code. Build. I forgot the semicolon. That happens, so get used to it. Add the semicolon to the end of the puts function at line 3. Save. Build. And you may see a warning, even if you don't, you need to know that the puts function requires a definition before it can be used. Otherwise, the compiler becomes confused. The definition is held in the standard IO header file. You must include that header file in your source code by using the include preprocessor directive. Insert a line at the top of the source code. Type hash, include, angle bracket, STDIO.H, angle bracket, and add another line for readability. This preprocessor directive includes the definition for the puts function. Save. This time, click the build and run icon, which is two steps in one. No warnings, no errors, good. And there's the output. If this is your first C program, then congratulations. The best way to get started on your programming journey is to write some simple programs that are easy to understand and change. To handle that task, it helps to know the basics of input and output or IO. In this movie, I introduce you to the concept of IO and how that plays into programming. You'll get to explore some basic IO functions and use one of those functions to create tiny programs that output interesting text. A program has to do something. That something involves taking input and generating output. This is how a typical C program works. It's a machine that does something to input and then generates output. If the program doesn't do anything, then it's basically plumbing what comes in goes out. The C library offers a host of output functions. Of the lot, these three are the most popular. They are pronounced print F, put car and puts. Each function is designed to send one or more characters to the standard output device, which is the screen or terminal window. The puts function puts or sends a string of text to standard output. Puts is put string, and a string is a collection of characters enclosed in double quotes. This function is defined in the STD IO header file, which is included at line one. In the exercise source code, I've specified the puts function but omitted the string. Your job is to type the string, so click the mouse amidst the parentheses and type the string argument for the puts function. Type a double quote. The editor automatically supplies the closing quote. Type some text. If the editor doesn't supply the closing quote, you must type it. Otherwise, the compiler doesn't see the end of the string and an ugly error is generated. You can also type the quote even if it's supplied and the editor is smart enough not to double up. The string is highlighted in blue. Save, build and run. There's the output, exactly as you typed. Your challenge is to add another puts function to the existing source code. Have that function output a line of text before line five. What the text says is up to you. This should take you about three minutes to complete. Welcome back. I'm going to show you how I would solve this puzzle, which is one way of doing it. I'm going to add my puts function here. There's no need to add a second STD IO header file for the second puts function. One is all you need for all the functions defining there. And you can type a single quote within a pair of double quotes. That's not a problem. Remember to end the statement with a semicolon. Save, build and run. Note the order. The program runs top down. The two puts statements execute in sequence. The program ends with a return statement which returns control back to the operating system. The closing curly bracket merely marks the end of the main function. I'd like to add a comment to the source code. This is text that doesn't compile. Instead, it's intended as a note for the programmer, a reminder or just general information. Insert a new line at the top of your source code file. Type slash asterisk. Traditional C comments start with the slash asterisk character combination and end with the asterisk slash characters. The editor highlights all the text in the code, which is now effectively one long comment because no ending comment characters have been written. Type your name and the date. Type asterisk slash to end the comment. Comments aren't compiled and you can prove it. Save the changes. Build and run. And the output is the same. A second type of comment uses two slashes at the start of a line. You can use this comment to disable a statement in the code which happens a lot when you're hunting down bugs or trying to fix something. I'll comment out line six, the first put statement. Save, build and run. See how the output doesn't appear? That's because the compiler treated it like a comment. If you'd like to restore the line, remove the double slash comment, then save, build and run again. Before closing this movie, I want you to view the files created when you build a program in C. Open a folder window to view the contents of your exercise folder. For each source code file, you find an object code file. It has the same name as the source code file, but with a .o file name extension. That's the file created by the compiler. The object code file contains both the compiled source code as well as information from the header file. The linker takes that object code file and mixes in the C library file. The result is a program file which also has the same name as the source code file. In Windows, you may see the file name extension EXE, which means executable. In other operating systems, no extension is necessary. The extension doesn't show up on this screen because Windows is configured not to show certain file name extensions. The program file might also be given the name A.exe or A.out. That's the linker's default name, although in code blocks, the program's name is the same as the source code file's name. Everyone's favorite C language output function seems to be printf. In most C courses, it's the first function you learn because it's included in the traditional Hello World program. But the function has far more power than just spewing out text. In this movie, I introduce you to the printf function. It's another text output function, but one with far more power than puts. I'll also show you how to incorporate escape sequences into strings. In its most basic form, the printf function sends a string of characters to standard output. That means it displays text on the screen. The printf function is defined in the STDIO header file. The printf function is used twice in this code in lines 5 and 6. In this mode, printf works a lot like the puts function. The argument for printf is a single string held between the function's parentheses. The string is enclosed in double quotes. The program doesn't air. The output is as it should be. Unlike puts, however, the printf function doesn't add a new line character at the end of the string. Yes, even though two statements are used on two lines of code, the output is one long string. To add the new line, which is like pressing the Enter key at the end of a line, you must specify an escape character. Edit line 5 to insert a backslash and a little n before the ending double quote. In some editors, the backslash n appears in a different color, showing that it's special. Save the changes, build and run. Now you see two lines output. Your challenge is to add the new line escape character at the end of the printf function in line 6. This should take you less than three minutes. And here's the solution. There's the new line escape character at the end of the statement. Save, build and run, and the output looks a lot better. Some characters you just can't put into a string. To sneak around this limitation, you use escape characters. In the C language, a string is a bunch of characters held between two double quotes. Everything between the double quotes counts, but sometimes you can't type a character such as the Enter key. For example, if you wanted to put a new line of text, the result would be two lines in the editor, not the output. The solution is to use the new line character in the string. It's an escape character, which means it starts with a backslash. That's followed by n for new line. Together, the backslash n is interpreted as one character, a new line, and it's generated when the string is output. The C language uses about a dozen escape characters, also known as escape sequences. The most common are new line, tab, single quote, double quote, and if you really need to display a backslash character, you must escape it as well. As a challenge exercise, I want you to create a new source code file saved under the name blorf.c. Use a single printf statement to generate the output you see here. Hello? On a line by itself, and then another line that says my name is blorf with the word blorf and the period enclosed in double quotes. Pause this movie and attempt this exercise. It should take you about three minutes. I'm going to create exerciseblorf.c myself so you can compare what you've come up with with what I did. Be aware that your code may not match up exactly with mine. Create a new empty file in code blocks and type in a basic skeleton. You see as I type, the text isn't color coded. You have to save the file before the editor recognizes how to color the text. I'll save here, and then go back and rewrite the specific printf function. And there's the color. So at line 5 I'm going to type in the printf function. Hello? And a new line my name is and escape the double quote blorf period, escape the double quote type a semicolon to make it a statement. Add a blank line for readability, save build and run. There's the output as requested. A single printf function that output two lines of text. And if you thought to add another new line at the end of the string, you get bonus points. Because the output looks kind of scrunchy. By the way, if you don't want to use double quotes, you can use single quotes instead. In line 5, I'll add it to remove the double quotes and replace them with single quotes. Because single quotes in a string don't need to be escaped. Many programmers find this method easier to use. A value is typically numeric. Although it doesn't have to be. In your code, you can specify values such as 3, 5, or even 100 million. The printf function can be used to display those values, providing you know about something called a placeholder. In this movie, I continue exploration of the printf function. I show you how placeholders can be used to display values, not only numbers, but strings and individual characters as well. To view values in action, you can use the printf function, but you have to take that function up a notch. The printf statement at line 5 generates outputs that would have you believe the number 27 was a value. But it's not. It's part of a string, just the characters 2 and 7. To specify a value, you need to do two things. First, you must place a value into the code, in this case the number 27. Second, you must direct the printf function to display that value. At line 5, to replace the characters 2 and 7 with %d. In some editors, you may see the %d highlighted. That's because it's a special symbol for the printf function. It's a placeholder. In this case, a placeholder for an integer value, a whole number. Place a comma after the string and add a second argument to the printf function, the value 27. Note how the value is shown in its own color. The printf function now has two arguments. The first is called the formatting string. It contains one placeholder, %d. Matching that placeholder is the second argument. The integer value, 27. Save, build and run. In this output, the 27 represents the value 27. Its output is text, of course, but inside the program, it's a number and not text. Copy line 5 and paste it in as line 6. Change the value to 29. Save, build and run. Two lines are output. The same placeholder is used in both printf functions. But because a different value is specified, that new value is output for the second statement. The %d placeholder is just that. It holds the place of another argument. In fact, you can specify multiple placeholders providing that you have arguments to match. Type a new line 7. That reads printf and here are the values %d, %d, and %d new line. Close quote, comma, 51, 52, 53. Remember the semicolon to end the statement. Save this modification, build and run. You can even do math in a printf function, although it's the C language that does the math, not the printf function. Open exercise file value 2. Here you see an immediate value specified in the printf statement, but math isn't always going to be that simple. Replace the 4 with the equation 2 plus 2. Save, build and run. The program makes the calculation for you. If it adds 2 and 2, the result is fetched from the %d placeholder in the printf statement. Now replace the equation in line 5 with this. 278 times 956. On a computer, the asterisk is used as the multiplication operator. I'll officially introduce that as well as other math concepts in a later movie. Change the format string as well, replacing 2 plus 2 with 8 times 956. And who knows what that value is? Well, save, build and run. And apparently the result is 265,768. Neato. The printf statement employs a swath of placeholders, each for a specific type of value. Here is a partial list showing some of the more common placeholders. It helps to know about the different types of placeholders used in the C language before you can use each of these, as well as understand the whole lot of them that aren't shown. Also, even then, the placeholders have options that I'll get into in a later movie. The %s placeholder is used to display strings, and it may look a little odd, but it does come in handy. Open exercise file value 3C. In this code, the %s placeholder is a programmer, which is the second argument of the printf function. Build and run this code. And indeed, you are a programmer, but what kind of programmer? Modify line 5 in the code to add another placeholder and another argument to the printf function. Place %c before %s and squeeze a space in between the two. Now you have to add an argument for the %c, so after the comma and then another single quote and a comma. Many editors will assign the single character value to its own color, as shown here. In the C language, single characters are specified with single quotes. If you use double quotes, you create a one character string. That's not what you need to match the %c placeholder. Save, build and run. And indeed, you are a C programmer. One final thing, because the % character is used as a placeholder, you must specify two of them when you use a % symbol in the printf statement's formatting string. Open exercise file value 4. Read the printf statement. The %d placeholder should match up with the second argument, 98. It's followed by a percent sign which indicates % not a placeholder, right? Build this code. Now, if you don't see any warnings, that's okay, the output will look weird. In some compilers, you will see warnings indicating trouble. The compiler believes that a second placeholder is desired, and it doesn't understand the placeholder as presented. Plus, it can't find a matching argument. If you don't see the warnings, try to run the code and see what happens. Weird, huh? The solution is to edit line 5 and stick in a second % sign. That looks odd, and it's cryptic. It's the cryptic side language, in fact, that enthralls so many of the nerds, but it's going to work. Save the changes. Build and run. And now the output looks more sensible. And I hope you do get 98% or more on your next C exam. Programs work fine with immediate values, but oftentimes you don't know what a value is. Say, the value comes from input. A user types it, or it's read from a file or the internet. To store such values, you need a specific cubbyhole or container. In programming, that container is known as a variable. In this movie, I introduce you to the concept of the variable. It's a container into which you can store values, values that are unknown or values that can change. You'll see how to declare a variable in the C language and how the variable is used in the code. A variable is a container for a value because C deals with different types of values, a variable must be compared as a specific type. And it's given a name, a name that's used in the code. In C, the variable type matches the variable's content. The type of value being stored. Integer variables can hold only integer values, or whole numbers. Float variables hold floating point values, which are very large numbers, very small numbers, are numbers with a fractional part, like 2.1. Character variables hold single values, such as the letter X. The C language lacks a string variable type. Instead, a character array is used. I'll explain how that works in a later movie. Int, float, and car are all C language keywords. Additional keywords are also used to declare variables. These include double, long, short, signed, and unsigned. These are all C language keywords, and they're used to declare types of variables. This code declares an integer variable at line 5. First comes the keyword int, which is used to declare an integer variable. Next comes the variable name, age, as this is a statement, it ends with a semicolon. Variable names can include numbers, letters, and some symbols. They must begin with a letter, or an underline used. The name must be unique, with no two variables having the same name, nor should variables be the same name as functions or C language keywords. At line 7, the variable age is assigned the value 30. In C, values or equations go on the right side of the assignment operator, the equal sign. The value or results of the equation is then assigned to the variable on the left, because 30 is an integer value, it fits nicely into the integer variable age. Finally, the statement at line 9 displays the variable's value by using the printf function. The %d placeholder is used, and the variable age is specified as the second argument. Build and run this code. The whole idea behind a variable is that its value can change. Edit the source code so that the value of the age variable is changed to 34. Make this modification at line 7. Save the modified code. Build and run. The program's output reflects the new value. Assign a new value to the variable in the code by adding two lines after line 8. First, assign the value 50 to the age variable. Age equals 50, semicolon. Second, type another printf function. This course's author is over placeholder integer years old newline, age, semicolon. Save this change. Build and run. See how the age variable is used twice to hold two different integer values. On your own, you can change this code once more. This time you can assign your own age variable. And simply add a printf statement to say how old you are. You can do this on your own later. Math can also be performed using variables. Open exercise variable 2. In line 7, the value 32 is assigned to the integer variable age. Edit the value to reflect your own age in years. The printf function at line 8 uses two statements, a string and an integer variable. The string is an immediate value. Change the name dan to your own name unless your name is also dan. You don't need to guess how many months you have because that value is calculated as the argument in the printf function at line 9. Save, build and run. Of course, the month's value displayed is an approximation unless today is your birthday. In that case, happy birthday. The int is really one variable type. Another common type is the car or character variable. Open exercise variable 3. Here three character variables are declared. X, Y and Z. You can declare multiple variables of the same type on a single line. Each variable name must be separated by a comma. Line 7 through 9 assign the variables characters. Single quotes are used. Then the values are displayed with the printf function at line 11. Build this code to run the program. Just as you can change integer variables, you can change character variables. You can even do math. Edit line 8 to read Y equals X plus 1 and line 9 to read Z equals Y plus 1. Save build and run. The output is the same. Instead of assigning immediate values to variables Y and Z, you did a little character math. Adding 1 to the value of character A gives you a B and 1 to B gives you a C. The final variable type I'd like to introduce is the float. It holds very large values, very small values, or any value with a fractional part. Open exercise variable 4C. The float variable pi is declared at line 5. At line 7, a calculation is made and the result is assigned to variable pi. The calculation uses floating point values by adding a dot 0 to 22 line 7. The compiler assumes that you need floating point values and treats them as such. Otherwise integers would be used and the result would be wrong. So, when you use a floating point whole number, remember to add the dot 0. Line 8 sends the result to standard output. The percent F placeholder is used to represent floating point values in a print F statement. Build and run the code. The value generated for pi is down to the hundreds place, which is OK for quite a few things in antiquity, but not acceptable for modern calculations. Programs are known for both input and output. Output goes to the standard output device which is usually the screen or a terminal window. Input comes from the standard input device which is normally the keyboard. In this movie I explore input and output concepts. These involve character I.O. which is the reading of single characters as well as the output of a single character. I'll also touch upon the concept of stream input and output. The two most common C-language character I.O. functions are getCar and putCar. That's how I pronounce them. GetCar fetches a character from standard input. PutCar sends a character to standard output. Both of these functions require the inclusion of the standard I.O. header file STD I.O. dot H for their prototypes and such. Although they are character functions, they work with integer values. Yes, that's weird but so are so many things in the C-language. In fact you may find yourself frequently using Car variables with these functions. When you do the compiler may gently warn you about the mistake. Finally these functions are stream oriented which is something I'll explain later in the movie. Integer variable C is declared at line 5. It's used with the getCar function at line 8, storing a single character from the input stream. In this example, that would be a character typed at the keyboard. The character is displayed at line 9. The int variable C is used but the character placeholder percent C is specified. This ensures that the character is displayed, not its code value. Build and run the code. Note that the prompt keeps the cursor on the same line and I added a space to make it more readable. Type a letter such as a big Z and press enter. Ta-da! Modify the code so that the putCar function outputs the character you typed. To do that, you need to split the printf function in two. So I'm going to go ahead and edit it to where it says you typed and notice I'll keep that single quote right there. Close the string and make it a statement with a semicolon. Then I'll add putCar on the following line and then display the rest of the string by using printf. But the argument C is no longer needed. Instead it appears up here in the putCar function where it's output directly. Save the source code file. This solution provides for the putCar function to generate output, but it also makes the code longer and less readable. That's actually okay in C and you'll discover that the output is unchanged. Build and run. This time I'm going to type an X and the output looks the same. You can also use the putCar function with immediate values. At this point in the code, the statement of line 11 really just outputs three characters. The single quote, period, and a new line. I could change line 11 to read putCar putCar, parent single quote, backslash single quote, another single quote. That looks odd, but you have to escape the single quote character or the compiler becomes confused. Escape characters are covered in an earlier movie. A second putCar function would display the period. The final putCar function would display the escape sequence which is specified in the original printf function as a new line. Oops, I fixed that. I'm going to get in trouble and use single quotes. So we have three putCar functions instead of a single printf function that displayed a three character string. Save these changes, build and run. And the output is the same. Open exercise file cario2. Here, two getCar functions fetch two characters. These characters are then displayed by using a sequence of printf putCar functions. Build and run the code. I'm going to type an M and an N and press enter. The two characters are stored in in variables A and B and then displayed. You'll note that the getCar functions do not pause and wait for input. They simply look for all input coming from the standard input device like a stream of characters flowing out of a hose. To demonstrate this phenomenon, just type Z and press enter. The weird output you see is the code displaying the new line character which was stored in variable B. Run the code again. This time, type several letters and then press the enter key. A, B, C, D, E. The entire stream of characters A through E on my screen were fed into the program via standard input. This is only the first two but my input persisted until I pressed the enter key. The stream input could also be demonstrated by examining exercise CARIO3. Here, it looks like one character is fetched by getCar then immediately displayed by putCar. That's logical because C programs run top-down and they do and that's exactly what happens in this program but it's not what you see when the code runs. Press A, B, C or any other three letters and press the enter key. The output happens all at once because of the stream. The characters you type are actually sent to output as you type them which is how the code runs. But, stream output is buffered. That means that the computer waits until the buffer is full or flushed before sending out the characters. In this case, the buffer is flushed once the program is finished. I'll explore stream input and remember that the standard C IO library functions are stream oriented. A character is a single letter or symbol. Put two characters together and you have a string. But strings are funky things in the C language. They're not a variable type, just a clutch or array of characters all marching together in a line. In this movie, I introduce you to the string. You'll see how strings are created in C, how they can be filled by using functions. You'll also meet the scanf function, which is used to pull in all sorts of input. Line 5 probably looks a little odd to you. It's a variable declaration. A care variable named password is created. The string spatula is assigned to the password variable. This is known as an immediate assignment, which is possible with other variables as well, but necessary when declaring a string. By the way, this is an array declaration, which is a topic for a later movie. The square brackets indicate that more than one care variable is present. How many? The compiler figures that out based on the size of the string. Otherwise, the value would appear between the brackets. In line 7, a printf function displays the string's value. The percent s placeholder is used. It's difficult to see because of the escaped double quotes and the new line. Let's build and run this code. The output properly shows the contents of the string. Change the word spatula in your editor to the words fuzzy-wuzzy. Put a space in there as spaces are valid password characters on some systems. Save the changes, build and run to see the string displayed. Remember that some characters must be escaped in a string. These include the double quotes, new line, tab, and so on. And there's the predictable, but ugly output. To fetch a string from standard input or to fetch any specific value, use the scanf function. As an input function, scanf is declared in the stdio header file, which you must include in your code lest the compiler become confused. Scanf uses the standard input function. The standard input function is called scanf. Scanf uses printf's placeholders to read a specific value into a variable. And that variable is often prefixed with the ampersand. Here's the format for the scanf function. It includes two arguments, a formatted string and a variable. The formatted string directs scanf to look for a specific type of value. To accomplish this, you specify the same placeholders used with the printf function inside the formatting string. So, %d for an integer, %c for a character, and so on, the formatting string is almost always composed of these placeholders and nothing else. To assign a value, specify the variable that's already been declared in the code. The variable type must match the placeholder. You need to prefix an ampersand operator to the variable name, which is something you must remember to do. You do not need to prefix the ampersand to a string or array, which is something you'll forget to do. The ampersand used here is the memory location operator, which is covered in a later movie. This code demonstrates how to read an integer value from standard input. The scanf function at line 8 uses the %d placeholder to fetch the integer value. It's assigned to variable x. See the ampersand. Don't forget it. Build and run this code. Type an integer which is any whole number. The program assigns that value to variable x and then displays the result. Now if you were to modify this code to read in a floating point value, you would have to make some changes. Try to think of the changes on your own as I make them in the code. First, of course, would be to change the variable type at line 5 to a floating point value. Simply change int to float and suddenly variable x becomes a floating point value. In line 7, obviously, we need to change the word integer. Line 8, change %d to %f for a floating point value. And finally, at line 9, change the word integer. And change the placeholder as well. Save, build and run. Type a real number such as 45.6. And the value is read and displayed. Don't freak if you see a value that's not exactly 45.6. What you see here is called a precision error. Computers approximate real numbers, which is acceptable. In a later movie, I'll show you how to fix the output to make it look more agreeable. You could also modify the code so that it reads in a single character value. The changes are the same. Try it along with me if you can. First, you change the variable type from float to a single character variable. And then here, change the prompt so that it says character and change the %placeholder in the scanf function to AC from an f to read in a single character value. Change the prompt here and the placeholder. With variable x being a character variable, you need the %c placeholders to read in the proper values. Save the changes, and run. And I'm going to type the mysterious character x. You can also use the scanf function to read in strings, but you'll find some peculiarities in this operation. Open exercise file scanf2. On line 5, the name variable is created. It has room to store 14 characters plus one additional character for the null at the end of the string. The scanf function at line 8 uses the %s placeholder to read in a string. The variable name is used without the ampersand. That's because name is a character array, and arrays do not require the ampersand operator. Build and run this code. Type your name and press enter. The string is read and displayed. And now for the peculiarities. Run the program again. This time, assume that your name is JerryBob, which is two words. The scanf function stops reading text at the first white space character. That's a space, tab, or new line, and there's no way you can force scanf to read in those characters. It's just the way it works. So scanf is really a string input function where strings are just one word long. A better function to use for reading strings is fgets, which is a file input function, but it can be used to read standard input. Open the exercise file fgets1. A variable input is created at line 5. It has room for 63 characters plus 1 for the null character terminating the end of the string. The fgets function at line 8 reads standard input. The first argument is the variable into which input is stored. This location is also called a buffer, which is just nerd jargon for storage. The second argument indicates the size of the buffer, and again 64 is used. That's 63 characters plus the null character. The final argument is stdin, which is standard input. The puts function at line 10 reads the stored text and sends it to standard output. Build and run this code. Type your instructions. Press enter, and there's your string, spaces, and everything. The important thing to remember when it comes to math and programming is that the computer does the work. You just have to copy the equation down properly. To do so, you need to know a few math operators plus some other C language rules and procedures. In this movie, I review the basic math operators and how they're used. Also explored are the increment and decrement operators plus a few notes on the order of precedence, which determines that the part of an equation is evaluated first. The C language uses four basic symbols for the four basic math operators. Addition, subtraction, multiplication, and division. These should be familiar to you, especially if you've used a spreadsheet. The asterisk is used for multiplication. That's because the multiplication symbol isn't available on the keyboard and please don't use the letter X. The division symbol isn't found on the standard computer keyboard, so a slash is used instead. Two additional operators are increment and decrement. These are single operators despite using two characters. These operators serve a useful purpose when dealing with loops, which is a topic covered in a later movie. And in C, the calculation goes on the right. The result is then assigned to a variable on the left. The result could be used immediately as in the printf function shown here. Two variables are declared. A and B. In line 6, I've preset the value of variable B to 5. The scanf function at line 9 reads in an integer value storing it in variable A. Then the printf function displays both values A and B as well as their sum. The math equation is the third argument in the printf function. Build and run. You can see the sum of that value in 5. To change addition to subtraction you need to make only one modification. Look at the code for a second and see if you can spot the place where that modification would take place. Here's where it would, right here. This is the equation. To change addition to subtraction simply change the operator. And change it here in the display string just so that it makes sense when you run the code. Build and run. You'll notice that negative values are calculated as well. If you wanted to try multiplication again you need to only change the operator. Look at the code and figure out on your own where that change would take place. Again, it takes place in the printf statement at line 10. Change the minus operator to multiplication. And in the display string as well. Save. Build and run. What you've probably guessed is division. But division can be tricky especially with integer values. Let me show you. I'll change the print statement to reflect division. It's the only change I'm going to make. And I type in a value such as 9. The result displayed is 1 which is dubious. To do division properly you need to use floating point values. Open exercise file math 2. This is basically a modification code switching int values to floats as well as the associated placeholders. Also the value 5.0 is assigned to variable b in line 6. Remember floating points have a decimal part so that when you're writing a whole number you need to specify dot 0. Build and run. Try the value 9 again. The result is more palatable but ugly. Your movie describes how to clean up the output of floating point values. Open exercise file math 3. Math is present at line 8. It adds 1 to the value of variable x. This equation may look funky to you but it's how it works. The compiler calculates the right side of the equation first. So 1 is added to the value of variable x. That result is then stored into variable x. To prove how it works build and run the code. The original value is 10 and the modified value is 11. You can manipulate any single variable in this manner. The most common manipulation is to add or subtract 1 from a variable's value. For example if you wanted to increment the value of variable x by 1 you use the increment operator which is 2 plus signs in a row. You can create in the code to read simply x plus plus. That's a statement by itself. It's a mathematical operation. Save, build and run. The decrement operator is 2 minus signs. Edit the code again to replace the increment operator with the decrement operator. Minus minus. Save, build and run. All the output is 10, 9. The final math goodie I want to show you deals with something called the order of precedence. It involves math equations that have multiple operators. Load up exercise math 4. Can you guess the value of variable a by looking at line 7? Run the code to see what the computer thinks. The computer thinks the answer is 13. That's because multiplication have precedence over addition and subtraction. The equation is also read left to right. So 25 divided by 5 is 5 times 2 is 10 plus 3 is 13. You can change that order by using parentheses. For example, I'm going to enclose 2 plus 3 in parentheses which means that part of the equation is evaluated first. Save, build and run. Now the answer is 25. 2 plus 3 is 5. 25 divided by 5 is 5 times 5 is 25. Now I'll add more parentheses. Remember to match them up. Save, build and run. Now the answer is 1. That's because 2 plus 3 is 5. 5 times 5 is 25. And 25 divided by 25 is 1. Remember in C equations are evaluated multiplication and division first then addition and subtraction unless you use parentheses to modify the order. When you can't find an operator to do your math you need to turn to the C library. There you'll find fund and friendly functions to set your mathematical whims. In this movie I cover two of the typical C language math library functions. The square root function and the power function. It also introduced the random number generating function which isn't really a math function but it's something you may find quite handy. To generate the square root of a value you use the sqrt function. It reads like squirt but it's really square root. The square root function is shown at line 8. It requires the math.h header file which is included line 2. The function swallows a floating point value specified as 2.0 It returns the square root as a floating point value which is saved in the float variable r. The printf function in line 10 displays the results. Build and run the code. And now you know the square root of 2 or any other value you specify in the code. Another math function worthy of note is the pow function which is short for power. The C language lacks a power operator which is common in other programming languages but the pow function is far more versatile. Open the pow file. The pow function appears at line 8. It also requires the math.h header file as shown in line 2. The pow function uses two arguments both floating point values. The first is the base. The second is the exponent. So here 2 to the 8th power. The result is saved in floating point variable p. And then it's printed in line 10. Build and run. 2 to the 8th power is 256. Generally speaking, all C language math functions require the inclusion of the math.h header file. They all work with real numbers. I use float in my examples but officially they should be double type double carries twice the precision of a float. That means it's more accurate but it should really be used only when a greater degree of precision is required. Another popular number function although it's not a true math function is RAND. It generates pseudo-random numbers. They're pseudo-random because they can be predicted but they're still good enough to be random in a general sense. The RAND function requires the standard library header file for its definition. This is the second most common header file after STDIO. The function itself requires no arguments. It simply generates a random integer value. That value here is stored in variable R. The printf function in line 10 displays the result. Build and run. On my screen I see 41 is the random number. Let's begin. And it's the same number. This isn't a bug. It's predictable. For the RAND function to work best you must seed the randomizer. That's a software machine that helps generate random numbers. The random seeding function is called SRAND which is also defined in the STD-LIB header file. In the code insert the SRAND function in the line above RAND. The SRAND function requires a positive integer argument to seed the randomizer. Here I'm using the value 66 which I just pulled out of my head. Save the changes. Build and run. This time a new random number appears but the same number appears when you run the code again. Let's find out. Yep. You have several tools available to reseed the randomizer. One is that you could ask the user and that's kind of lame. What most programmers do is to borrow the current tick-tock value from the computer's internal time clock. I cover time functions in a later movie. For now we need to change line 8 in the code to replace the value 66 with a time function. You need to type in parentheses the word unsigned then the time function time and in its parentheses you need to put the word null in all caps. Then make sure all the parentheses match up. They're highlighted on the screen. Good. Yes, this looks odd but it's important that the parentheses match one set around unsigned one set around null and then one set around the entire thing which is the SRAND function. What this function does is to fetch the current tick-tock value from the computer's clock. The number that's constantly changing save the code build and run and you see a new value let's run it again to check a new value and it's another value. It's close because again it's based on the tick-tock value which is incrementing throughout the day. Why are random numbers so important? Because random numbers are the key to making all computer games interesting. Generally speaking a program executes statements as they appear in the source code one line after another. To change that order is to alter the program's flow. One of the most common flow control words in the C language is IF which is similar to its human language counterpart also called IF. In this movie I introduce you to the IF keyword. You'll also discover how comparisons are made in the C language as well as how to handle multiple decisions. Before you can use the IF keyword you must understand how comparisons work in C. Two values or expressions are evaluated. To make that evaluation you use one of the C languages comparison operators. Here are the most common comparison operators is equal to which you'll notice two equal signs one equal sign is the assignment operator this is why I say is equal to for the operator's name instead of is equal or equals less than and greater than you're probably familiar with. Then there's less than an equal to and greater than an equal to. Finally the not equal to or does not equal operator. The exclamation point in the C language is often pronounced not which is how you remember this one. The user is prompted to type an integer value the value is displayed in line 9. In line 10 an IF statement evaluates that value if it's greater than 10 line 11 is executed otherwise line 11 is skipped build and run. Let's type in 50. You typed in 50, 50 is greater than 10 it worked. I'm going to experiment a few times as you should with other values to see how it works. 7 Type 7 and of course there's no other output and 10 but values greater than 10 will display that string. An IF statement is traditionally formatted differently from other statements. It's split between two or more lines. The first line sets the IF condition in parentheses. If that condition is evaluated true the next line is executed. Actually it's just one statement split between two lines. See how the semicolon is at the end of line 11 and not line 10. You could also write it as a single line but that's uncommon. More common is to enclose the statements belonging to IF in curly brackets like this. This format is actually required when more than one statement is executed based on the IF condition. For example let's move line 9 down to line 12. Save build and run. You type in 25 and because the value is greater than 10 both lines were displayed. Open exercise file IF2 This code shows two IF comparisons in a row each of which has its own set of curly brackets. Two conditions are evaluated. Greater than in line 10 and less than at line 14. Build and run. You see the appropriate output for values less than 10. Run again. You see appropriate output for values greater than 10. And run again. Not output for 10 itself. Edit line 14 so that less than or equal to is used as the operator. You can remember the order of how the symbols go if you say less than or equal to or greater than or equal to. Edit line 16 to reflect the same results. Save build and run. Another way to handle an either or decision is to use the keyword else. Load exercise file if else. This code is a rewrite of exercise IF2 but it uses the else keyword. The if condition at line 10 makes an evaluation. Its statements are executed when that condition is true. When the condition is false, the statements belonging to else are executed instead. Build and run this code. Let's try it with 10. That's true. Run it again. That's true. Note that else doesn't have a semicolon. Instead it has curly brackets. Or it could be written without brackets because it's only followed by one statement. When three or more conditions are present you can evaluate them by using an else IF structure. Open exercise if else if else to see what that looks like. This structure starts with an if statement here at line 10. When that condition is true those statements are executed when that condition is true those statements belonging to that condition are executed and the rest is skipped over. Otherwise a second condition else if is examined at line 14 if that condition is true its statements are executed and the rest of the structure is skipped. At the end of the structure is an else all by itself. Its statements are executed when the preceding conditions aren't met. Build and run the code. The results are similar to previous examples. 15 is greater than 10. Run again. 10 is 10. Again. 5 is less than 10. You can have as many else if statements stacked up as you like which helps evaluate complex situations. Finally a reminder the if else if and else keywords are generally not immediately followed by a semicolon. In the C language a semicolon by itself is a statement. When one lingers after an if evaluation the compiler believes that the semicolon is the statement and that not anything follows it. This is a common mistake. Load exercise if 3. Build and run. Well obviously negative 5 is not a positive number. Now if you're using the clang compiler you can click on the build log tab and review a specific error message other compilers may not be as smart. To fix the problem simply remove the semicolon dangling at the end of line 7. Save. Build and run. No output means that the negative 5 fails the condition. Remember the semicolon goes after the statement not the parentheses that hold ifs condition. The C language lets you handle complex decisions by stacking a bunch of if else conditions. Sometimes that structure can get a bit unwieldly. As an alternative you can employ the switch case structure which is yet another decision making tool in the C language. In this movie I introduce the switch case structure. You'll see how it's constructed, how it can handle multiple decisions plus I'll demonstrate a few tricks. The bulk of this code is switch case structure. It starts with the switch at line 10. This is followed by a series of case statements. Each of which has its own statements. The final piece is default. It's followed by its own statement as well and then a closing curly bracket. These are the elements of the switch case structure. The switch case structure also makes use of the break keyword. So all told this structure contains four C language keywords switch case default and break. Build and run the code to see what it does. I'll type one. Excellent choice. Run it a few times to try out various options. The code accepts character input although it could have easily accepted integers. Here's how the structure works. Switch handles a single value, not a comparison. It can be a mathematical equation but the result must be a single value. That value specified by switch is then compared with the values for each case statement. If the comparison is true then the statements belonging to the case statement are executed. If not, they're skipped. So at line 12 if the character one is typed then the puts statement at line 3 is executed. The break at line 14 ends the switch case evaluation returning control to the line after the switch structure's final curly bracket which is at line 23. Otherwise, if a match isn't made execution falls to the next case statement. And then the next. Finally, the default condition is executed when none of the case conditions match. The break statement as it's the end of the structure. Modify the code by commenting out all the break statements. Insert double slashes at line 14 line 17 and line 20. Save the changes build and run the code. If you type a character other than one, two or three you see the invalid choice message displayed. But type a one you see all the messages displayed. That's because execution falls through to each case statement. Open exercise switch to. Here's another switch case structure one that evaluates input as a menu system. Build and run the code. I'm going to type a. The problem with these options is that you may have typed a little a instead of a big a. In that case, the program doesn't seem to behave properly. Address the issue by adjusting the case statements to account for both upper and lower case input. Edit the source code to add duplicate case statements for the lower case letters. Save the changes build and run. Now the evaluation should work for both upper and lower case letters. You could also address this problem by using C language functions that modify character case. That topic is covered in another movie. Another way that program flow can be altered is when one or more statements are repeated over and over. This process is referred to as a loop. The C language offers several ways of looping. In this movie, I present the while type of loop. You'll learn how to set up the loop determine when to stop looping and how to break out of a loop before it's done. A loop is a repetitive way to control program execution. You must specify a condition that makes the loop repeat, a set of statements that repeat, and a way for the loop to stop. In this code, a while loop counts from 1 to 10. The looping condition is specified on line 8. It reads that while the value of variable X is less than or equal to 10, as long as that condition is true, the statements in the loop between the curly brackets at line 9 and 12 will repeat. The value of X is initialized at line 7. At line 11, the value of variable X is incremented. So as long as X keeps inching up, the loop repeats until X is greater than 10. Build and run this code. And you see the values from 1 displayed. Say you wanted to count to 20. Can you just off the top of your head imagine where you would make that change? It's simple. Change the condition in the while loop to 20 instead of 10. Save that change. Build and run. And now values 1 through 20 are displayed. Now suppose instead of going by 1, you wanted to display only the even numbers from 2 to 20. This requires a little bit more thought because it changes two things. The initialization and how the value of variable X increases. The first change is to initialize variable X to 2 at line 7. You're going to be counting by 2's start at 2. Then modify line 11 so that the value of X is incremented by 2, which is not really an increment. It's a mathematical function. So X equals the value of X plus 2. Save. Build and run. And there you see even numbers between 2 and 20. Finally, it's possible for loops to count backwards. If you were going to count backwards by 1, can you think of how you would modify the code so that that would happen? Obviously, there's a few changes that would need to be made. If you're going to start at 10, you need to change the initial value to 10. Then the condition needs to change as well because already the loop wouldn't repeat. Value of X is less than or equal to 20. So the condition should be, while X is greater than 0, then the statement at line 11 needs to be changed as well. The value of X should be decremented each time the loop spins. There's the decrement operator. Save. Build and run. And there the loop counts from 10 down to 1. Open exercise file while 2. This code uses the SRAND and RAND functions introduced in an earlier movie. These functions generate random numbers. In this case, a while loop displays 10 random numbers. Build and run the code. Impressive. But let me show you a couple of tricks to clean up the numbers. The first is the modulus operator, which is a percent sign. Modulus calculates the remainder of a value, like leftovers. In fact, open up the exercise file while mod to see a demonstration. Here I'm using a C program to teach you C. A while loop marches through the values 7 through 30. It shows you how the modulus operator affects each of those values. Build and run the code. The modulus operator gives you a remainder. So for example 10 mod 7 yields 3. That's because 7 goes into 10 once, but with 3 and you can see how the value is always going to be between 0 and 6 for mod 7, no matter what initial value is used. Return back to the while2 source code. Edit line 15 so that the printf function displays the value of r mod 100. This change limits the output to values between 0 and 99. Save, build and run. You may see some single digits in there. Let me run it again to get some single digits. There they are. The single digits don't really look properly formatted. To line up the numbers, you can edit the printf statement again. This time, insert a 2 in the %d placeholder. The 2 sets the width of integer output to 2 characters wide, right justified. Save, build and run. Here you see a single digit, but it's lined up on the right, which looks more pleasing. Another type of loop is the dowhile loop. It's kind of an upside down while loop, but it has the guarantee that the loop always executes at least once. Open exercise file dowhile. The dowhile loop starts at line 9 with a do statement. It has no condition. Its statements are executed one after the other. The while condition appears at line 14. The loop relies on variable ch as its condition. That variable is initialized in line 7, and then manipulated in line 12. Build and run. The z isn't printed because it's an exit condition. If you want to see the z, you need to save the exit condition to z plus 1. Save, build and run. Open exercise file whileindless. This code demonstrates an endless loop. There is no exit condition because the while loop's evaluation is always 1. Build and run the code. Press ctrl c to cancel the program and stop the madness. Now, endless loops do have their place, but most of them are unintentional. You can, however, fix the loop by using the break statement. Insert line 8 which simply says break and then a semicolon. Save, build and run. The loop spins only once because the break statement busts out of it. You can even use the break to bust out of a loop prematurely. Load exercise file while endless break. The while loop's condition is infinite and it cannot change, but variable a is used to monitor the loop's iterations. And once a is greater than 10, the loop is busted. Build and run the code. Of course, a better solution would be to evaluate variable a at the while loop's parentheses. That's something I hope you try on your own. The four keyword is used for creating loops in your c code. Unlike a while loop, the for loop is set up on a single line which makes it more cryptic, but it remains popular and perhaps more traditional type of loop. In this movie I present the for loop. You'll see how to set up the loop and understand its parts. A for loop is presented at line 7. The loop's statement contains three parts, each separated by a semicolon. First comes the initialization. The statement is x equals 0, which is an assignment. It's made at the start of the loop. Second comes the looping condition. The loop repeats as long as this condition is true, x is less than 10. Finally, the iteration statement. Each time the loop repeats, this statement is executed. Here, the value of x is incremented. The semicolon doesn't follow the four statements parentheses. Instead the semicolon follows a single looping statement as shown here at line 8, or a series of statements are enclosed in curly brackets. Build and run this code. The values 0 through 9 are output. This is actually typical for a C loop. In C programming, you start counting at 0, not 1. Humans start counting at 1. So to fix the loop for the human's eyes change the printf statement to read x plus 1. This modification doesn't change the value of x, only the output. Save, build and run. Now that you've seen the basics of the loop, you need to practice some of your skills. You need to practice three challenges. You need to modify this code so that the loop displays values 1 through 20. The other one is to display even numbers from 2 to 20. And finally to display values from 10 down to 1. That's three challenges in one. Your first challenge is to modify the code for 4, 1, as shown in the earlier movie, so that it outputs values 1 through 20. Then create a new program that outputs even values 2 through 20. And finally create another program that outputs values 10 through 1. This exercise should take you about 10 minutes to complete. Here are the solutions to the three challenges. The first was to modify the code so that values 1 through 20 were output and the change is really simple. You just set the 10 to a 20. Save that change, build and run. And there's the numbers 1 through 20. The second challenge was to modify the code so that even values 2 through 20 are output. Unlike a while loop, which was shown in an earlier movie, only one line needs to be changed. Initialization needs to change so that x equals 1 and then x equals x plus 2. Save, build and run. And there are the even numbers. Of course, to make it more readable I'd probably have done this change where x equals 2 while x is less than or equal to 20 and then change the printf statement so that x is output itself. That's just more readable than doing it the other way. The final challenge was to modify the code to display values 10, 9, 8 all the way down to 1. Here's how that change would be made. First, x must be initialized to 10. And then the loop must spin while x is greater than 0. And the value of x each time must be decremented. Save, build and run. One thing you can do with a for loop that's a lot easier than using a while loop is the concept of the nested loop. In this movie I'll show you how to create a nested loop and how to avoid endless loops in common loopy mistakes. This code sends 10 random numbers to output. Build and run to see what it does. You see a neat row of 10 random values. The spacing is produced by the tab character shown on line 14 as backslash t is the tab character. To make a grid of 100 random values you need to add 9 more rows The way most C programmers accomplish this task is to create a nested loop or a second for loop that handles repeating the current output 10 times, or 9 times actually plus the current one. Open exercise nested for 1. This code is a modification to the previous exercise. It includes an extra loop. The old loop, the common loop, is now listed inside the row loop. The indentation keeps the code readable. It also helps match up the statements in curly brackets. Build and run this code. And you see 100 random numbers. Open exercise file nested for 2. This nested loop might be a bit easier for you to read. The outside alpha loop goes from the letters A through J. K is the limit. The inside loop which doesn't need curly brackets because it holds only one statement, loops from 0 to 9. The current loop variable values are then output in line 11. Build and run the code. In the output you can better see how the nested loops run. First comes loop A, the outer loop, and then the inner loop displays values 0 through 9. Then comes loop B, 0 through 9, C, 0 through 9, and so on. Open exercise file for 3. This is only half the code required for this exercise. Input is prompted and then the alphabet is displayed. What I'd like you to think about doing is how would you have the loop stop when the letter input is equal to variable T in the loop. You don't need to change the FORE statement to make that happen. Instead you need to put statements within the loop that will bust out of the loop when the character is input. The key is to use an IF test and follow that with a BREAK statement. Here's the solution. Above line 13 add IF T is equals 2 equal signs variable CH. Break. If you don't put the 2 equal signs in there what you get is an assignment. And in C assignments always evaluate true. And don't forget the semicolon after the BREAK statement. Save. Build and run. And the alphabet only displays to letter M. I'm going to run it a few more times so you can see what it does. We'll do X. And now we'll do something early like D. One more thing. Remember to check 2 items in a FORE statement. The looping condition and the iteration. If either is off the loop will go on forever. The compiler doesn't check for flaws in logic. That's your job. My tip is to read the FORE loop statement. Set T equal to character A. While T is less than or equal to character Z increment T. If you changed the condition to just T equals Z for example it would evaluate true and the loop would run forever. So watch your conditions and your iterations. The C library is brimming with functions. These functions do a lot of things but perhaps not everything you need for your programs. Therefore when necessary you can concoct your own C language functions. In fact most programs have dozens if not hundreds of their own functions. In this movie I introduce you to the function. You'll see how to set up and prototype a function, how to call or access the function, and how to bail out of a function early. Like everything in the C language the function has a certain style and various etiquettes must be followed to add a function to your code. A function has a type, a name and arguments in parentheses. The type is a value returned by the function, its output. The name is a unique name that identifies the function. The arguments are 0, 1 or more values passed to the function, its input. Here the alpha function has no input or output in the C language. Therefore it's a void function. Void is a variable type which means I have no variable type. Function count is an integer function. It generates or returns integer values. It requires no input and therefore has no arguments. Function hang up returns no value so it's a void function. It does however accept a single character as input. The character is an argument and it's referenced as a variable ch. Before you can use a function it must be introduced to the compiler. That way the compiler can check its arguments to ensure that it's being used properly. Functions are called by their name and then parentheses. When a function is called, control passes to the function's statements. Then when the function is over, flow continues with the statement after the function call. This code contains two functions. The main function is required in every C program. You also see the blurf function. Line 3 prototypes the blurf function. This informs the compiler of the function type and arguments. The compiler can confirm that the function is being used properly by checking the prototype. Also the prototype is a statement. It ends in a semicolon. Line 8 calls the function. It has no arguments so the parentheses are empty. The function itself is found at line 14. This is effectively a repeat of the prototype minus the semicolon. The statements belonging to the function are enclosed in curly brackets. Build and run the code. To call the function again, you simply specify it again. Duplicate line 8 to line 9. Save Build and run and the output appears twice. The prototype works like a definition for the function, describing how to use it when the code appears in the code. You can avoid specifying a prototype but only when you write the function before it's used. To see an example open exercise file function 2. The soup function appears above the main function. That's okay because the compiler still sees a main function in there somewhere and it's always the first function run in the program. What's missing here is the prototype for the soup function. Build and run. And the code outputs text as expected. But try this. Move the soup function after the main function. Save. Just build. On my screen, I see one warning. Your compiler may report the misdeeds in a different manner. Either way, it's not good. You have to add the prototype. So I'm going to insert a line above the main function. Void and a semicolon. Save. Now build and run. No errors and the output is the same as it originally was. Open exercise function 3. In this code, the cheers function contains its own variable. X at line 18. This variable is used only in the function here to repeat the string three times. Build and run the code. You cannot reference variable X outside of its function. To prove it, insert a line above line 11 that displays its value. Save the change and build. Don't even bother trying to run it because you won't. The compiler is basically saying, what the heck is X? Try to define X and set its value inside the main function. Save. Build and run. The value of X in the main function is unaffected by the X variable in the cheers function. They are two different variables. Here's another thing to remember. A function ends its run when its last statement is executed. In the cheers function, that's a put care at line 26. You can bail out of a function early by using the return keyword. Type return semicolon at line 26. You don't need to specify a value here because the cheers function is a void function. It doesn't return anything. In the main function, return must specify a value as it does at line 17 because main is an int function. Save the changes. Build and run. The output is messy because the put care statement is skipped. That code is never executed because of the return statement right above it. More often you'll see a function return early based on a condition which usually involves an if statement or a loop. Otherwise, anywhere the return is found marks the spot where the function bails out and control returns to the calling function. Or in the case of the main function control is returned back to the operating system. A function has got defunct. It's that IO thing again. Sure, a void function is necessary and obviously valid, but most functions chew on input and do something based on that input. In this movie, I explore how functions can deal with arguments or values passed to the function. You'll see how to declare such a function, how it deals with values, and how to pass more than a single value to a function. This code contains the repeat function which accepts one argument an integer. Within the function, the integer variable is named count. The function is called at lines 8 and 10 each time with a different argument. Inside the function, a local variable x is declared. It's used in the for statement along with the count variable. Build and run this code. The function can also accept integer variables as arguments. Make these modifications to the code. In the main function, declare integer variables a and b. Run to a and 5 to b. Use a and b in the two repeat functions. Save the changes. Build and run. And the output is the same. Open exercise file argument 2. In this code, you see a function that accepts three arguments. In this case, three floating point values. The scanf function at line 10 reads in the three values. This is possible providing you format input to match the format string. In the product function, the product of the three values is calculated and displayed. Build and run this code. I'm going to type 12 13 and 15. And there's the result. There is no limit to the number of arguments a function can accept. Although the more arguments, the more likely it will be to mess up the format. You don't necessarily need to eat all the same argument type, either. Open exercise file argument 3. The bar function accepts two arguments. A character and integer value. Build and run this code. The bar function uses both of its arguments to output a bar of a certain character across the display. Open exercise file argument 4. This file contains an empty function, evaluate. Your job is to complete the function. It should accept an integer value and display a message stating whether the value is less than, greater than or equal to 10. Your challenge is to create content for the evaluate function. Display whether the argument past is less than, greater than or equal to 10. This should take you about five minutes to complete. This is the solution. First, did you remember to prototype the function? I did not include it in a skeleton presented in a previous movie, so I was seeing whether you paid attention. Here is the prototype, which is simply a copy of the function's declaration at line 16. And here is the content I came up with. Your function could look like what you see here. You may have done things subtly different, but as long as the code works, then you succeeded. I'm using an if, else if, else structure. No curly brackets are required because each item has only one statement that follows it, going to build and run. Type in various values to see how it works. And it works. Hopefully, your solution works just as well. Most functions in the C library return a value. Even when that value isn't used, it's available. Returning a value allows functions to generate output. Most of the time, that output is based on the input or arguments past of the function. In this movie, I explain how functions return values. They can simply generate the information, or they can manipulate arguments to produce specific output. I'll also cover a few rules and regulations regarding functions in the C language. This code contains a function called gimme and a. It's a character function returning a car value. The function has no input according to its prototype at line 3. The function is called line 9, where its return value is assigned to the grade variable. Line 15 merely returns the single character a. Build and run this code. And I hope that's true. When a function returns a value, the value can be used immediately. You can edit the source code for this exercise so that the grade variable is removed. First, delete the assignment. And then replace the variable in printf with the gimme and a function. Save the changes. Build and run. Build and run. And you still get an a. Open exercise file return 2. You may recognize this exercise file from an earlier movie. In this code, the product function has been upgraded so that it returns the product of the values passed, which makes more sense. Build and run this code. Type 3 values, then press enter to view their product. The code can be cleaned up a bit. Variable p in the product function is not really needed. You can eliminate it to merely have the product returned. Save these changes. Build and run, and the results will be the same. Well, providing you type in the same numbers. A more realistic example is shown in exercise return 3. Max is kind of the stalwart of learning C. It's passed two values and returns the larger of the two. I also added the is larger function, which doesn't return anything, but I wanted to show how multiple functions can be declared within the code. Here is max, and there is is larger. Type 2 values, hopefully two different values separated by a space. The code displays the larger of the two values. And now, the limitations. In the C language, a function can return only one value. It cannot return multiple values, nor can I think of a reason why you would want to. You can return an array or a structure variable from a function. These variable types are covered in a later movie, but yet they remain single variables. And now I'd like to explain the main function. As you can see here in this source code, main is an integer function. The return statement is required, and an integer value must be specified. The parentheses for the main function are empty. This is a shortcut, a cheat. The compiler knows the arguments for the main function. Two of them exist, but you don't need to specify them if they don't get used. So the parentheses remain empty in the main function. This is not something, however, you can get away with other functions you declare and use. So much goes on with characters that the C library offers a host of character manipulation functions. In this movie, I introduce a few of those functions and show you how to use them in your code. As a bonus, I offer an introduction to logical expressions, which can also come into play when working with characters. In your C code, characters appear either individually or marching along in an array called a string. So you can manipulate characters one at a time or, more commonly, in the string. This code includes a C type header file that supports the character testing and manipulation functions. At lines eight and nine, you see the two upper and two lower functions. The two upper function generates the uppercase version of a letter. Two lower generates the lower case. The results are used immediately in the printf functions. Note that these functions require integer values, not characters. So you can display the result by using %C in the printf function even though they are integer variables. Build and run the code. Big A little A, but begins with A. As you can see by the output of the final printf statement in line ten, the two upper and two lower functions did not affect the variable ch. They merely generate an upper or lower case equivalent. You can use these functions on a string as well. To do that, you must dissect the string in a loop. Open exercise C type two. Again, an integer variable is used in the two upper function. Input is processed and converted to uppercase at line eleven. Then output. You won't see the output until you press the enter key because the C language is stream oriented. Build and run the code. Type some text. Press the enter key. The output is all caps, but note how the punctuation symbols and spaces are unaffected by the two upper function. Most of the functions defined in the C type header file are testing functions. They're used to evaluate the type of character, such as whether it's a letter, number, space or upper or lower case. These functions return true and false values which you can use in your code to see what's been typed. As an example, exercise C type three uses the isAlpha function to determine whether a character is a letter of the alphabet or some other character. The function returns true if it is false otherwise. In the doWhile loop input is received and checked. The if statement at line eleven returns true if the character is a letter of the alphabet. If so, it's displayed. Build and run. Type a bunch of text including symbols and numbers. Press the enter key and only the alphabet characters, upper and lower case, are output. You can modify the source code for this exercise to try out many of the character manipulation functions. For example, change isAlpha in line eleven to isUpper. Now, only upper case letters are output. Save, build and run to test the change. Other functions defined in the C type header file include isLower to detect only lower case letters, isNumber which returns true for any number character zero through nine, isBlank for any white space character, the space, tab or new line. You can also craft your own character manipulation functions, but it helps to know about C logical operators. The C languages logical operators are used to compare two or more expressions. The operators determine whether the result is true or false. Three operators are available to use logical and, logical or and logical not. These are often written in all caps so that they're not confused with the regular words. For an and operation to be true, both conditions must be true. This and that. For an or operator, either of the conditions must be true. This or that. And for the not operator, the condition must be false, which is backwards, but that's how not works. Not this. As an example, the and operator evaluates two conditions. Here, both conditions are true. Therefore, the if statement is executed. Here, one of the conditions is false. Therefore, the if statements are skipped. In the logical or operator, only one of the conditions needs to be true. Here, the if statement would be executed. When both conditions are false, the if statement won't be executed. And in the case of not, it negates the condition. Here, the condition is false. Variable A equals C, but the not operator turns that around and makes it true. Finally, in the C language, all values are considered true except zero, which is false. Typically, the value one is used for true, but it could also be negative one or any nonzero value. As an example of constructing your own character test, open exercise C type four. This code is a rewrite of exercise C type three, where I've substituted the is caps function for is upper. A logical comparison is made at line 22. To understand how it works, read the condition. If the value of variable C, H is less than A, or the value of variable C, H is greater than Z. So when either of those conditions is false, meaning the character is not uppercase, the function returns false. Otherwise, the function returns true. Suppose you wanted to change the is caps function to is lowercase, and have it return true or false based on that condition. How would you go about doing it? Well, the first thing to do is to change the name of the function to something more accurate. There in the prototype, in here as well, and also in the call. Change the big A to little A, and big Z to little Z. Save, build and run. Only the lowercase letters appear. You can create just about any character test by using logical operators. You'll see additional examples of using logical operators in other movies in this course. A string is a funny thing. It's not really a C language variable, but it's used that way. And when it comes to manipulating strings in your code, you have to be really careful due to their unusual nature. This movie discusses working with strings. If you want to know how to gather information about a string, stick strings together, compare strings, and find one string inside another. These tasks represent the more popular string manipulation functions in the C language. A string is declared at line 6. It's a character array, so the car variable type is specified, and the variable name is string, followed by empty brackets. The string length function, n, appears at line 9. I pronounce it string-len, because it means string length. It returns the number of characters in a string, which here is stored in the len variable. Build and run this code. The string is 19 characters long. You can also count the characters in the source code, but you won't always have the luxury of knowing the exact amount. For example, what if the user types in a string? Open Exercise String Manipulation 2. This source code file is based on an exercise from an earlier movie. Input is fetched by using the f-gets function. And then it's stored in an input buffer. Afterwards, the string-len function fetches the length of the string. The next statement displays the results. Build and run. I'll type. And apparently that string is 20 characters long. Keep in mind that strings in C end with a null character. Storage must be allocated for that extra character. The program generates the character, but you must provide room for it in the input buffer. And the string-length function does not count that character when it measures the string's length. Open Exercise File String Manipulation 3. This is only partial code. You and I are going to figure out how to stick these two strings, first and second, together to make another new string. In many programming languages, the addition operator does the trick. For example, would that work? Save. And then click the build button to find out. Well, that's a no. You could display both strings back to back, but that's not the solution I'm looking for. What you need to do is to stick the strings together. Now, rather than say, stick the strings together, see programmers say concatenate, which comes from the Latin word for sticking two strings together. But before then, fix up the code first, create a storage location or a buffer for the resulting two strings. I'm just guessing at 64. I could count each string and see how exactly big they both are, then add one for the null character and set the value that way. But 64 is a holy computer number. So I'm using it instead. So the first thing I'm going to do is to copy the string first into that storage container. The strcpy or string copy function copies one string into another. Here, the string first is duplicated into the storage buffer. And I need to prototype that function. All string functions are declared inside the string.h header file. The next thing to do is to stick the string second onto the end of the storage buffer. This statement tax the string second onto the end of whatever's in the storage buffer. Concatenation. And then finally, display the results. Save it. Build and run. And it worked. Concatenation. Another popular string function compares two strings. This code uses the strcmp or string compare function to compare two strings. The value returned is zero when both strings are the same. That's one of those weird times where zero actually means true. Values less than are greater than zero indicate incorrect matches. Here, you'll also notice that the scanf function limits input to only eight characters. The input matches the eight character limitation on the buffer. The buffer is nine characters to account for the null character at the end of the string. Build and run the code. Now try a few passwords before you type the real one which is secret. By the way, this code doesn't need the compare variable. You can remove it. Delete it thrice from the code and replace it with a function directly. Place the string compare function inside of the if statement. Save the changes. Build and run. The final string function I'd like to show is called string string. It's used to find one string inside of another open exercise file string manipulation five. This code uses the string string function which I call string string. It's a little weird because you really need to know more about pointers to effectively use this function. That knowledge is gleaned in a later movie. For now the string string function is included as part of the if statement at line nine. It returns a pointer or the location of the string find me in the string source string. If no match is made, then the value null is returned. Again, null is a pointer thing. Build and run the code. And the string is found. You can alter the text for the string find me to prove that the function actually works. And it does. Until you breach the rocky shoals of the pointer land, that's about the best that can be done with the string string function. Occasionally when learning something new, you need to pause and reflect. That's the topic of this movie. Pausing and reflecting. Specifically with regards to variables and values. It's time for me to go back and get you caught up on some things that might have already been seen in an earlier movie, but you have questions about. Plus, I'll introduce a few new concepts. Things I feel it's about time you knew, especially if you are new to learning the C programming language. In this movie I cover creating and using constants. Plus, I offer additional detail on how to use some of the printf functions placeholders. A constant in the C language is different from an immediate value and a variable. It's more like a universal value that doesn't change throughout the code. Constants or values used consistently throughout your source code. They're things that don't change. They're created by the preprocessor define directive. Normally the constant is written in all caps, letters and underlines only. Now when the compiler encounters a constant, it expands it out to its assigned value. In this example the constant version is created and it's assigned to the value 3. The compiler converts the word version into the immediate value 3 throughout the code. And remember that preprocessor directives are not C language statements. Don't put a semicolon after the assignment unless you need the semicolon to be a part of whatever's being defined. That hardly ever happens so just don't add a semicolon. Here is a string constant defined as author. The string must be enclosed in double quotes. This is an example of one constant that uses two other constants to calculate value. So here the constant gain grid would equal 120 unless either the rows or columns constants are changed. They wouldn't be changed in the code, they would be changed in the define statement that you see here. This code is based on an exercise presented in an earlier movie. I've cleaned it up a bit but now I'm going to set some constants. I'll insert two defined directives to set the numbers of rows and columns in the grid. Now I'll change the value 10 used as an immediate value in the loops to reflect the constants. Save the changes, build and run. The program still outputs 100 random numbers in 10 rows and 10 columns but now I can easily change that to say 20 rows of 7 columns. All I have to do to make that change is to change the constants. I don't have to hunt through the code to find those proper values. That's how constants can save you time. Save, build and run. And now you see 7 columns 20 rows. Another example of using constants can be seen by opening exercise constant 2. This code is an update to an exercise from an earlier movie. The number of characters to be input is set by the input max constant defined at line 3. The constant is then used to set the exercise at line 7 and again with the fgets function at line 10. The advantage here is that you can change both values at once simply by modifying the input max constant. You don't have to hunt through the code. Load up exercise placeholder 1. This is a modification to an earlier exercise shown in another movie. Build and run the code to help you remember what the problem was. I'll type 9 and press enter. Well, and there's the ugly output. You can fix this problem by adjusting the placeholders in the print f statement. Modify each percent f placeholder at line 10 by inserting period 1 inside each one so that they read percent period 1 f. Save the changes. Build and run. The point 1 format limits floating point output to only one digit after the decimal point. Edit again and type period 3 for the format in the print f statement. Save, build and run. And now 3 digits appear after the decimal point. Return to exercise constant 1. In the print f statement at line 17 you see a 2 between the percent and d. What the 2 does is set an output width to 2 characters minimum so when single digits appear in the output, they're right aligned. Build and run this code. See how single digits are lined up in the output. Now edit the code again and remove the 2. Save, build and run. Now the single digits don't look right. No one expects them to line up in the tens column. The placeholders have lots of options. These can be sandwiched between the percent sign and the letter. I could make dozens of movies to describe them all but another one to look at is percent s found in the placeholder 2 source code. The 2 strings right and left are displayed by using percent s placeholders. But there are extra characters between the percent and the s. The 20 specifies an output width in percent d. In line 8 the percent 20 s right justifies the output adjusting the string's location based on its length inside that width. In line 9 the negative sign before the 20 left justifies the string which is how text is normally output. Build and run this code to see how it works. The width argument in the percent s placeholder sets the width to 20 characters. Right justified left justified. This placeholder is ideal for displaying lists and tables. Many more placeholder width, precision padding and other options are available. The documentation for the printf function lists the variety plus a few examples. An array is simply a collection of more than one of the same type of variable. For example, a list of high scores is a type of as would be how many miles you run every day even if that list contains lots of zeros. And of course strings in the C language are an array of single character variables. In this movie I introduce the concept of the array. You'll see how to create an array how to fill it with data how to access that data. And I'll also divulge some secrets about character arrays as strings. Here you see the way not to do multiple values in your code. Four separate float variables are created and filled with data. They're then displayed using four separate printf statements. Each variable requires its own repetitive statement. You can build and run this code but why bother? Instead I'll show you a better way to deal with multiple variables of the same type that way is the array. Open exercise array2. This is the array version of what you saw in the previous exercise. The array temps is created at line five. It contains four elements and each element is assigned in the brackets that follow. The loop at line nine displays all four elements values by using a single printf function. An array is simply a collection of multiple variables all of the same type. It has a declaration similar to any other variable but with square brackets after the variable name. The brackets hold the number of elements in the array or they can be blank if the elements are specified when the array is declared. Here the integer array deliveries has room for 15 elements. Integer array totals has three elements which are assigned in curly brackets. The final element does not have a comma. If you put a comma there, the compiler believes that you've forgotten something. You can also list array elements on a line by themselves. Don't forget the commas except after the final element and remember to close the curly bracket and add a semicolon. Each element in the array is its own variable. You specify the element between the square brackets. The first element is element 0. You can also use an integer variable to specify array elements. Here variable n represents a specific element in the totals array. The element is used like any other variable. It can find itself inside of a printf function or it can be used with an assignment operator as shown here. Finally, you cannot change the number of elements in an array after the array has been declared. Some tricks exist to work around this limitation but for now just accept it as a rule. Also don't forget that the first element in an array is 0 not 1. Humans start counting at 1. The C language starts counting at 0. An integer array calories is declared at line 7. It has meals element and the meals constant is set to 3 at line 3. A for loop at line 12 reads in 3 values. See how the for loop starts at 0? That comes in handy when working with arrays as the first element is 0. In line 14 however 1 is added to the looping variable x which makes the numbers more accommodating to humans running the program. The scanf statement at line 15 reads the values into each array element. An array element is an individual variable so the ampersand is required. At line 16 the value input is added to the total variable. Build and run the code. I'm going to type some easy numbers so I can confirm the computer's math. Yep it works. You'll see the variable total is initialized at line 10. That's required. Otherwise the variable may contain garbage. In C tables are not initialized until they're assigned a value. Comment out line 10 to prove this. Save. Build and run to see if it has any effect. And of course the number is off because the total variable was not properly initialized. There's an off chance that it may be correct because a random number could be 0 in which case 600 would show up. But here you see that the total variable was somehow containing the value 52. Strings are character arrays. Normally they're declared by using double quotes. Open exercise array 4. The character array text is declared at line 5. This is really simple and it's one of the best ways to declare a string or character array. Open exercise array 5. This code works the same as the previous exercise but the character array is declared character by character which is a phenomenal waste of time. Build and run the code. It works but it's just too much effort. The code does however point out that the final character in all C language strings which must be specified is the null character. It's shown here as the escape sequence backslash 0. Now when you use double quotes to declare a string the compiler automatically adds the null for you. But when you specify one character at a time you must remember to add the null. The null comes in handy when you display a string one character at a time. Open array 6. This code displays the string in the hello array one character at a time. The while loop marches through the string until the null character is encountered. It spits out single characters by incrementing variable n as it progresses. Build and run this code. Because the null character evaluates to the false condition in the C language you can shorten the while decision to this. Make that change in your code. Save, build and run. The same output is generated although the source code is a tad less readable to a beginning programmer. The typical array in the C language is simply a series of variables all of the same type marching off together. But not the type of data is a single line. Sometimes you have to deal with a grid. In that case you enter into the realm of the multi-dimensional array. This movie uncovers the mystery of the multi-dimensional array. You'll learn how to configure such an array and access its values. You'll also see how multi-dimensional arrays apply to strings. To visualize a multi-dimensional array think of a grid. You have rows and columns. The array is declared at line 8. Two sets of square brackets are used. One for each dimension in the array. So grid is an integer array. It's effectively a two-dimensional array. Lines 12 through 14 use a nested loop to fill each array element with the value 0 initializing the array. In line 14 you see that individual array elements require two square brackets as reference. Again think of each as rows and columns. Then the nested loops starting at line 17 print the array in rows and columns. Build and run the code. The output shows each array element as it would be referenced. So the first one is element 00. That's the first element in both directions. As a thought experiment, how would you modify the code to set the value of the third element in both dimensions to the value 1? Would you change it here or here? I hope you remember that arrays start with element 0. So the third element is actually referenced as grid 2, 2. I'm going to add a line that reads grid 2, 2 equals 1. Save that change build and run. This is how the value looks with the value 1 at grid 2.2. If you put a 1 here, you're actually using the fourth element in both dimensions. That's wrong because you have to remember that all arrays start with element 0, not element 1. Even the pros forget that from time to time and when you're dealing with two dimensions it gets even worse. You can also conjure up a two-dimensional character array as is shown in exercise multi 2. A two-dimensional character array is simply a collection of strings but with one important caveat. The array must be dimensioned to handle the largest string. Remember a two-dimensional array is a grid. Here the longest string is six letters long plus one element for the null character. That makes seven elements for each string. And when printing strings from a two-dimensional character array you need only specify the first dimension which is done on line 14. The C language also offers three-dimensional arrays and even more dimensions than that. When you create such an array you need one set of brackets for each dimension and things can get pretty complex in a hurry. For now concentrate on playing with two-dimensional arrays. As a thought whether you believe it or not if you've been taking this course from the beginning you have everything you need to know to program a rudimentary tic-tac-toe computer game give it a try. Here's your challenge. You need to modify the code from the previous movie multi two and add a string to the array. Add another string in this case. The string should contain the word Pinocchio. P-I-N-O-C-C-H-I-O. This should take you about five minutes to complete. Here's how I'd make the change first. Add the string after Pluto. So add a comma and type Pinocchio. No comma after Pinocchio. Plus you have to redimension the array. It now has five strings five elements in the first direction and Pinocchio itself is nine characters long so you're going to need ten characters in the grid to handle that null character at the end of the string. So that's the new dimensions. Five ten Pinocchio, add it at the bottom and remember to modify the for loop so that it loops five times instead of four save build and run. Another variable type in the C language is the structure. It's actually a combination of existing variable types all tied together into a single unit. A structure variable simply has many parts like a record in a database. This movie presents the concept of the structure. You'll see how to set up a structure create structure variables and how to access structure members. I'll demonstrate how to fill data into a structure as well as the interesting idea of placing one structure inside another. This isn't complete code of course but it shows you how a structure can be created in the C language. The keyword struct is followed by the name of the structure. In this case the name is record. The structure members are contained in curly brackets each ending with a semicolon because the whole deal is a statement. The structure members are variable declarations. Inside this structure you'll find an int and a float member. The int member is named account. The float member is named balance. By itself the structure declaration merely creates a type of structure like a new type of variable in the code to use the structure you need to declare a variable of the structure type. So on line 9 I'm going to type struct record my bank. This statement creates a variable named my bank of the record structure type. To access the structure's members you need to reference both the variable name as well as the member name. I'm going to add two new lines. The structure variable name comes first then a dot then the member name. They must be assigned values equal to the variable type in this case an integer and a floating point value. Save these changes build and run. And there's the output from each of the variables inside the structure. To create another record structure variable called your bank you simply have to echo the existing statements. You can also fill the members in that structure simply by copying these statements and replacing my bank with your bank. You could also preset the information inside a structure. Open exercise file structure 2. In this code a structure named person is declared. A variable of the person type is declared at line 9. It's named president. The president structure variable is immediately assigned values. The values match the structure member types and are enclosed in curly brackets. Run this code to ensure that it works. One thing to note in a structure is how you assign a string to a structure member. Open exercise file structure 3. If you can see what's wrong great otherwise build the code and then check the build log to see the specific error. Incompatible. That's enough. You cannot use the assignment operator with a string. That's because strings are not variables they're arrays. Here's how to solve it. And remember to add the string header file. Save the changes. Build and run. Now it works. You can insert any variable type into a C language structure. Even another structure. Open file structure 4. In this code we have definitions for two structures. The first, date is defined at line 6. It holds members year, month and day. The second structure person is declared at line 11. It contains a name array but also the date structure in the form of a birthday variable. A person structure variable friend is declared at line 15. Line 17 through 20 fill the friend variable. The second copy is used to assign the string. For the structure member birthday, note how two dots are used to fill in the substructure members in lines 18, 19 and 20. That's how it works. That's how structures within structures are referenced. Build and run the code. By the way, most programmers will declare a structure and then create a structure variable in the same statement. You can do that here on line 14. Specify the variable name friend the end of line 14 then remove line 15. Save the changes. Build and run. The output is the same. I prefer not to use this shortcut in my own code in that I find it less readable but you're free to use it and you'll see it quite frequently in other C code. I've yet to encounter a programmable device that didn't have some sort of internal clock. The computer has a clock and thanks to the internet, modern computers keep accurate track of the time. When your code needs to access that information, you dip into the C language library's assortment of time functions. In this movie, you'll see how time functions work in the C language. You'll learn how to check the time, read time values and how to gather information about the current date. This code uses the direct value generated by the time function as shown by the second argument in the printf function at line 6. You'll see that the placeholder is LD which is a long integer value or a very large integer. That's the type of value returned from the time function. The time function itself requires an argument. Here I'm using the null pointer constant to keep the function happy. Also keeping the compiler happy is the inclusion of the time header file at line 2. Build and run this code. So this value is the current time. It's actually what's referred to as the unix epic time or the number of seconds that have elapsed since January 1st 1970. To be relevant to a human being, the number is going to need some work. Oh, and by the way, this value has been used in previous movies as the seed number for the srand function. It's the same deal. In fact if you run the program again, you'll see a different value generated. Normally the value returned from the time function is saved. It's a long integer value but the variable type is known as time t which is spelled time underscore t. Insert a new line in the code to declare variable now as a time t type. To assign a value to the now variable, you must specify it as an argument in the time function. Yes, that's backwards but several functions operate that way including scanf and like scanf you must prefix the variable with an ampersand and change the printf statement so that the variable now appears as the second argument. Save these changes build and run and the time is still shown as a big number but it also shows that you have time left to complete this movie so moving along the C library comes with a function that translates time t values into strings. It's called the C time function. Edit the printf function in this code so that the second argument is now C time ampersand now closing parent. Change the LD placeholder to percent s that's because the C time function generates a string save build and run what you see is the current date and time and unless you're doing this movie right now you'll see a different time if you want to fetch specific time values then you need to use the local time function this function returns the address of a structure that holds individual time values such as the day, month, week, hour, day of the year and other information. Open exercise file time 2 the local time function at line 10 fills a structure with interesting info about the current time the structure is declared at line 7 it's a pointer variable which you'll learn about in a later movie the local function uses the current time value obtained at line 9 this fills the structure right now which is the name of the structure some of that information available in the structure is displayed in the printf statement starting at line 11 I've split up the arguments on separate lines to make them more readable but all this stuff is really a single statement the C language doesn't let any extra spaces in here bother it 4 values are accessed from the right now structure the month the day of the month the hour and minutes these are all members of the right now structure you see that the period structure member operator isn't used here this is the member operator used for structure pointer variables build and run the code now you may notice that the month value is off that's because C starts counting at 0 and the first month of the year January is month 0 you can fix this code by adding one to the value return from the right now structure other adjustments can be made as well for example if the current time is less than 10 minutes after the hour then it appears as a single digit fix that by adding 0 to the 100% D placeholder this argument increases the output width of the integer to two places plus it'll prefix a 0 when the output is only one digit long save this change build and run of course the current time doesn't show that because it's 18 minutes after the hour but if it was 8 the time would show up as 11 0 8 and the month is displayed correctly a variable is a container some type of data in the C language that container holds an integer floating point character or other value but philosophically speaking what actually is a variable in this movie I help you explore the concept of the variable you'll see various ways of variable is described how to determine its size and its storage location in the typical C language variable declaration you learn two tidbits about the variable its type and its name here you see an integer variable declared it's an integer variable int and its name is a the variable is uninitialized or never assigned value even so you can use it in the code as is shown in line 7 build and run the program on my screen the value of a is equal to C you might see the value 0 although that's just random unlike other programming languages C does not initialize variables as they're declared internally the program allocates a chunk of memory to store the variables information that chunk isn't initialized it's not set to 0 it's just some location in memory and whatever value is already there is immediately absorbed by your variable as shown in the output here the moral of the story is to always initialize variables before you use them you can make a fix in this code by adding a line save that change then build and run now the output is predictable you also know something else about the variable it's value two additional tidbits about the variable can be obtained by using special C language operators the first is the size of operator size of is a keyword but it's considered an operator what it does is to return how many bytes of storage are used by a specific variable that information may seem trivial but it does come into play often in the C language open exercise file var 2 variable A is not initialized here but that's not an issue because it's not used the size of operator is used in the printf state the size of operator simply evaluates variable A as an int variable to return the storage space it occupies the size of operator returns a long unsigned integer value the placeholder required for that value is %lu build and run on this system an integer occupies 4 bytes of storage but 20 years ago an integer used only 2 bytes of storage change int to car in the code both at line 5 and in line 7 in the printf function save build and run a character occupies only 1 byte of storage now change to float to see how big that variable type is save build and run on this system a floating point variable occupies 4 bytes of storage a long integer or long int value is designed to store really huge integers to see how big it is change float to long in the code save build and run on this system a long integer occupies 4 bytes of storage which is the same as for a regular integer but on some systems you may actually see 8 bytes of storage used for a long integer value likewise a double value has twice the precision of a float change long to double in the code save build and run here you see the double does indeed occupy 8 bits of storage by the way you don't need to change the placeholder for any of these redeclarations that's because the size of operator turns the long unsigned integer value not the variable itself other information you can gather about a variable includes its memory location that tells you specifically where the variables data that 1, 4 or 8 bytes of storage where that data is located to fetch a variables memory location use the ampersand operator you've already seen this operator used in the scanf and timef functions if you've watched earlier movies open exercise file var 3 3 variables are declared in this code an integer a character and a floating point value these variables are not initialized because they're not used but the program does allocate space for them at various locations in memory to access those locations the ampersand is prefixed to the variable name to display the address placeholder in the printf statement as shown at lines 10 11 and 12 build and run this code the address values output will differ from machine to machine and even their format will appear differently on different computers and different operating systems here you see the memory locations for those 3 variables at this point the information may seem trivial but it does play a major role when it comes to pointers which are perhaps the scariest most dreaded thing in all of the C language I know many C programmers who spend their careers artfully avoiding pointers which is possible but not smart pointers are puzzling yet I hope this movie clears the air for you I'll explain what a pointer is how it's used I promise to move nice slow because this topic is a very important part of learning the C language the worst thing about pointers is their name pointers it's descriptive but a poor choice because you end up explaining a pointer by saying a pointer points that's pointless but I can't change the name so allow me to explain a pointer by giving you this definition a pointer is a variable that holds a memory location an address it's not just any address you can't say for example let's see what's at memory location 96 pointers don't work that way the address must be the location of another variable pointer variables are declared similarly to other variables although the variable name is prefixed by the pointer operator the asterisk you'll see an example in a moment the pointer variable type matches the type of variable it references for example an int variable requires an int pointer finally pointer variables must be initialized before they're used this is true of all variables in the C language but especially so for pointers lots of weird airs happen when a pointer isn't initialized I can't repeat it enough pointers must be initialized before they're used this code is similar to an exercise from an earlier movie the ampersand operator fetches the address of the variable pokey the %p placeholder displays that address add an integer pointer variable p remember a pointer is a variable that holds a memory address to get that address to use the ampersand operator that's already being used in this code so you could be able to figure this out on your own but just in case I'll initialize the variable p equals ampere pokey this statement assigns the address a variable pokey to the p pointer variable at this point you might be puzzled you might say where's the asterisk in front of the p I'll answer that question in a moment remember that a pointer is a variable that holds a memory location and here that memory location is of the pokey variable it's being saved into pointer variable p now duplicate the printf statement this time replace ampersand pokey with pointer variable p save these changes build and run both lines output the same address one is the address of variable pokey obtained with the ampersand the other is the value saved in pointer variable p which is that address while the pointer variable is declared by using an asterisk it's not always used that way without the asterisk the pointer variable represents a memory location with the asterisk the pointer represents the value at that location this is the dual nature of the pointer variable and it's something that can be endlessly confusing this code is similar to the previous exercise but I've initialized the pokey variable to the value 987 two sets of printf statements display the address and value of the pokey variable the first set uses pokey directly the second set uses pointer variable p in line 14 p is used without the asterisk so it's a memory location in line 15 p is used with the asterisk so it peaks at the contents of that memory location build and run this code and the pointer variable p dutifully reports the correct values the address and the contents a logical question I want to ask at this point is why bother? I'm serious at this level using a pointer is pretty pointless you can do many things in C without bothering with pointers but they do have their purpose and many functions expect you to understand and know how pointers work later movies in this course also drive home win and how to use pointers so don't give up on them yet in this challenge you're to take the code from pointer 2 and modify it suppose that pointer variable pokey is a character variable how would you make necessary changes to the code including assigning a character to the variable convert character pokey to a car variable and alter the rest of the code to reflect this change this challenge should take you about 10 minutes I hope you found the challenge rather easy the 10 minute thing was just as scary you really have to change both variable types to care a pointer variable must match the type of variable it references so not only is line 5 changed but line 6 needs to be changed as well the value is assigned to pokey at line 8 you don't need to change line 9 again because both these variable types match the other changes take place at lines 12 and 15 where you need to specify %C placeholder instead of %D save these changes build and run and it works where pointers really come into play is when dealing with arrays after all there is no such thing as an array in the C language all arrays are simply shorthand for pointers to prove it in this movie I dissect the common C language I'll show you how pointers can be used to manipulate an array providing flexibility and power other programming languages can only dream about the code here is pretty basic an array is declared and it's values assigned a for loop marches through each element displaying that element's value cinchy it's so easy I'm not even going to run it open exercise file array pointer 2 pretty much the same code but a pointer is used to display the array's values the A pointer variable is declared at line 7 it's initialized at line 9 an ampersand isn't needed here because as I said in an earlier movie arrays are all shorthand for pointers so the array name is really a memory location in the for loop APTR variable is used with the asterisk so that the value at the memory location is fetched during the loops first iteration the value is the same as the 0th element in the array and look at line 14 the APTR pointer variable is incremented in this format the pointer variable is a memory location so the memory location is incremented but by how much because APTR is an integer pointer the memory address it holds is incremented by the size of an integer variable the storage space that variable uses in memory conveniently that happens to be the location of the next element in the array build and run the code and it works the output is the same as it would have been for the previous exercise had you bother to build and run that code the pointer variable is used to march through the array the advantage here is that pointers can be used to manipulate array data and pointers are variables go back to the first source code file array pointer 1 add a new line below 9.6 to create the pointer variable and initialize the variable as was done in the other exercise now the tricky statement is to assign value for the third element to 0 by using the pointer variable the pointer variable is already referencing the first element in line 9 to reference the third element you need to add 2 to its value and to assign that memory location the value 0 you use the asterisk operator the rest of the code can remain the same save build and run and the third element is now 0 it has been manipulated by using a pointer most C language programmers will combine the statements at line 10 and 11 into a single line it looks like this you need to use parentheses because the pointer location math must happen before the asterisk references the value save the changes build and run and the output is the same you'll see this type of shorthand notation used a lot the main reason is that it doesn't affect the value of the APTR pointer variable which still references the base address of the array perhaps the best way to demonstrate pointer and array manipulation is to use strings instead of numeric arrays open exercise array pointer 3 in addition to declaring a string as a character array you can also declare a string as a car pointer variable the compiler makes the assignment but the variable created is a pointer in this code the pointer variable is used just like an array name here in the puts function build and run to confirm that this approach is not crazy now this begs the question that if you're afraid of pointers how would you display this string open exercise array pointer 4 yes this is the chicken way to do it and it works because array notation is simply shorthand for pointers in fact many C programmers would do exactly as you see here which is to use array notation to display the string build and run it works but this approach is not why you're taking this course I'm going to replace the array notation with pointers all you need is only one pointer which I'll call PTR and you don't need an X no ampersand is needed here because string is already a pointer it holds a memory location to examine a character at a memory location the asterisk operator is used so the while loops condition becomes that's it ditto for the put care function and then you increment the memory location which is so these two represent characters and this represents a memory location marching through the string save the changes build and run and the output is still the same now you could go one step further if you like and not even use the PTR variable I'll make the necessary modifications in the code save build and run the issue here is that once you change the string variable you lose its base location in memory for this code that's not an issue but for other situations it could present a problem one of the places you'll see pointers use the most and something you truly can't avoid in the C language is where a function requires or returns a pointer happens a lot this movie helps you deal with pointer functions even create your own you'll see how pointers are used in functions how to pass a pointer to a function and how to return a pointer from a function you've already seen pointers used in functions in this course you probably just didn't recognize that's what was happening the scanf function uses pointer values specifically memory locations of the variables it reads and in line 8 reads the address of variable 8 and sends that address to the scanf function and you know scanf's return value isn't used in the function instead the function simply uses a pointer to assign the value to the variable x directly clever huh in exercise scanf2 which I have on the screen here the ampersand is not required for the name variable as name is an array and arrays are pretty much pointers in disguise the ampersand isn't needed you can concoct your own functions that use pointers you need to specify a pointer as an argument or as the return value open exercise file pfunction1 the function minus 10 is prototyped at line 3 it accepts a pointer variable as its argument the pointer variable is a memory location so it accepts the address of a variable as the argument the address of variable value is passed to the function at line 10 the ampersand operator is what fetches the address in the function the asterisk operator is used to change the value of the variable passed nothing needs to be returned to be accessed in memory build and run the code the variables value is affected by the function even though only its address was passed to the function and the function didn't return anything open exercise pfunction2 in this code a pointer function is declared longer returns a character pointer or the address of the start of a string in memory the function starting at line 18 compares two strings by length the longer string is returned or I should say its address is returned the string itself never really makes it to the function only its address the address returned by the longer function is stored in the result pointer its then output at line 13 build and run this code and the longer string is displayed you can also manipulate strings in functions again you're not passing the string itself merely its starting point in memory open exercise file pfunction3 this code is another example of string manipulation by using pointers where the function doesn't really need to return any value the shouting function at line 19 takes a string and munches through it one character at a time is run through the two upper function which converts lower case letters to uppercase build and run the code type something like I'm not shouting and enter and it worked all without returning anything from the function open exercise pfunction4 in this code a string is returned from the encrypt function a string is accepted by the function then a new string is returned which keeps the original string intact but will it work build and run now you may see a compiler warning and it's a serious warning which explains why the output is unpredictable well unless these are really secret instructions the problem here has nothing to do with pointers it's an old situation I explained in an earlier movie on functions that is all variables used inside a function are local when the function is done its variables are tossed aside this holds true for the encrypt function with the output array to fix the problem you need to use the static keyword insert the word static before the variable declaration on line 17 the program now retains the content of the array the string when the function is done it stays static which means unchanging save build and run only the address of the string is returned by the encrypt function the rest of the characters exist in memory and are accessed by the printf function but it works only when you remember to make the string returned static this rule doesn't apply to single values functions are designed to return individual values which include pointers but for strings or other arrays or any other variable used inside a function it must be declared as static or the value doesn't keep when the function is done a pointer is a variable a variable that holds a memory location as a variable it's possible although terrifying to some to place pointers into an array why and how you would want to do such a thing is this movie's topic here I'll show you how to set up an array of pointers to keep things simple I'll use strings for the example you'll see how to access strings evaluate the strings and convert them from array notation into pointer notation a pointer array is simply a collection of memory addresses so how do you get to the situation where you need an array of addresses one of the best examples is to use an array of strings here you see a pointer array it contains room for 5 memory locations those locations are preset to the strings listed in effect the declaration is for an array of strings although that's not technically correct the strings are displayed by using a for loop at line 14 build and run this code and each string is displayed to prove that the array is a clutch of memory locations modify the code in line 15 change the %s to %p remember that %p is the memory location or address placeholder save the change build and run and now you see a series of memory locations because the compiler allocated space for the strings and stuck null characters on the end the memory location does reference a string by the way this method of storing multiple strings is far more efficient than declaring a two-dimensional array in that case you must declare the array so that each string occupies as many characters of storage as the longest string here in this pointer array declaration that's not an issue open exercise %p array 2 this code is the version of the previous exercise here the for loop moves through each pointer in the array for each iteration the pointer variable cptr is assigned to the base address of each string a while loop then turns through the strings one character at a time build and run this code the output is the same although the method of printing each string was different it's actually kind of crazy pointer variable cptr is used to display each character by walking through the memory locations where the characters are stored now something bothers me about this code line 17 if you haven't picked it up already it uses array notation that was very cowardly of me to do so a better solution would be to convert this heinous notation into pointer notation to do so make this change to the code this notation uses the memory addresses stored in the gang variable which you saw displayed in an earlier exercise so the memory locations are used not the string then the value x is added to each and each time the loop references the next array element which is the base address of a string it has to be enclosed in parentheses because the memory location is manipulated first and then the contents of that location the asterisk fetches the string is referenced later save this change build and run the output is the same more can be done with pointers here and I could broach upon the topic of pointers to pointers and all that double asterisk notation but that's more of a topic for an advanced course in fact here's a tip when you see the dreaded double asterisk pointer notation it's almost always a sign that you're dealing with an array of strings or specifically an array of memory locations for each of those strings when a program needs storage you allocated in the code by setting aside space for a variable when you need more than one variable you create an array and when you don't know how much space you need you guess but there's a better way in this movie I cover the topic of allocating storage in your code you'll see how to properly ask for storage determine that it's available and then access that storage in your code storage is divvied up by the operating system your program asks for space as it needs it this request is made in one of two ways is to declare a variable storage for the variable is set aside and made available for use and for a specific purpose in the code this code declares several variable types including an empty character buffer the size of operator is then used to calculate how much storage is set aside build and run this code on my computer it shows that 141 bytes of storage were set aside even though the storage is never used save for the total variable it's still set aside your computer may show a different total depending on how memory is allocated by the operating system when you don't know how much storage you need then you can allocate it on the fly the function that does that is called malloc which sounds like a bad guy name but it's really short for memory allocation open exercise file allocate to the malloc function appears at line 10 it requires the std-lib header file which is included at line 2 the format is to allocate a chunk of memory but you need to know how much so you take the variable type which is car here and you get the size of that variable type then you multiply it by how much storage you need here the size constant is used the malloc function then returns a memory location a pointer where the storage has been allocated in memory here that location is saved in pointer variable std it must also be the same type of variable as for the chunk of memory allocated one more piece is needed you must typecast the memory location return to match the pointer variable type on the other side of the assignment operator a typecast is forcing one type of variable to masquerade as another and doing so avoid some compiler warnings before the malloc function you need to type car this typecast ensures that the compiler understands a character pointer is being assigned that's car which is the variable type and the pointer operator which ensures that it's a memory location save this change build and run and 1024 bytes of storage are allocated at a given memory location if they weren't allocated then the malloc function has assigned a null pointer value to variable std that condition is checked for in line 11 always check for this condition you can use the null constant you don't want a program to use memory that's not available here is your challenge take the code for allocate to modify it so that input is accepted and assigned to the storage allocated the 1024 characters then display the text you stored this challenge should take you about 10 minutes to complete here are my changes to the allocate to source code which allow for the 1024 characters of storage to be used in the else group of statements I'm going to add printf type something and I'm going to fetch input which has been done in earlier programs storage location amount of characters and standard input and then display and then display it using the buffer that's it save the changes build and run now type something interesting press enter there it is the text is stored in a memory buffer allocated while the program was running when your program needs memory you can allocate it on the fly that includes memory for any variable type array or even a structure in this movie I demonstrate how structures can be created using pointers with their memory allocated as the program runs in this code storage for a structure is allocated the structure has to be defined first which happens at line 6 remember that a structure itself isn't a variable it's simply a declaration of what the contents of a structure would be in this case the members are month, day and year at line 11 a pointer variable for that kind of structure is created the pointer is a memory location it's not the structure storage for the structure is allocated at line 13 courtesy of the malloc function see how the size of operator is used to allocate enough storage for the structure itself and the structure's name is used not the structure pointer variable assuming that the structure is created lines 20 through 25 fill the structure and because the structure is referenced by a pointer the structure pointer member operator is used it's a dash greater than operator even so the variable being referenced by this operator isn't a pointer so the ampersand is required inside the scanf function the printf statement at line 27 displays the results build and run the code I'll type in my own birthday info and there it is this type of memory allocation for a structure plays a key role in linked lists which is a topic for a later movie linked lists are considered an advanced C language topic that's because the linked list construction uses pointers and memory allocation it's also a bit crazy to describe so I will be patient in this movie you'll see how a linked list is set up and configured I'll demonstrate how it's used and how to access its members all this will be shown one step at a time so hang on in this code that's structure is defined a pointer to that structure is declared at line 10 memory is allocated for the structure at line 14 the structure is filled on lines 22 through 24 finally the printf statement starting at line 27 displays the structure's values build and run this code I'll type in a pitiful amount and it works say you wanted to create more of these structures by allocating additional chunks of memory you could put them into an array an array of structures is something that's completely possible in the C language but how big would you make the array if you run a bank and you need this code to keep track of the accounts you obviously don't want to keep paying a programmer to continuously make the array larger instead you can dynamically increase the number of structures by allocating space for new structures the problem is how to keep track of the structures here's the secret open exercise file linked list 2 in this code another member is added to the stats structure it's a pointer to another stats structure shown in line 9 that pointer is assigned a memory location for another structure at line 26 the other structure isn't created in this code but there's room for it and it could be filled in with information but not yet build and run this code it runs no differently from the preceding example but memory has been allocated for a new structure the problem that you run into at this point is repetitive code lines 15 through 20 and lines 26 through 31 when you see that type of thing it's begging for a function open exercise file linked list 3 the first thing I did with this code is to make the declaration of the stats structure a global variable a global variable is a variable that can be accessed in any function for a linked list the structure pretty much has to be global because all the functions in the code need to know the structure's definition you can make any variable a global variable simply by defining it outside of any other function usually at the top of the code before the main function do however avoid the temptation to make all the codes variables global that works in the programming practice now I've written the create function which allocates storage for one stats structure it's found at line 25 the memory is allocated and its location is returned from the function if not the program quits the exit function at line 34 causes the program to immediately stop control returns to the operating system this function is prototyped in the stdlib header file and it carries an argument that's passed to the operating system similar to the return statement in the main function back in the main function three structure pointer variables are declared each of which is used in the linked list but not currently in this code first always holds the address of the first structure in the list it's the base of the linked list current is the structure currently being manipulated the new is used when new structures are created now the word new is a keyword in the c++ language which is why it's highlighted here it's not a keyword in the c language now if it is highlighted in the editor and people tell you not to use it they're wrong as long as you compile in c code you're okay if you're gonna go back and forth you'll probably need a new name for that variable the code does a little bit more than simply allocate space for a structure it doesn't generate any output you could build it and run it but instead open exercise file linked list 4 the addition here is the fill structure function starting at line 29 it fetches information for a newly created structure for the next pointer null is assigned that's okay in fact later you'll see how null marks the end of the linked list in line 23 how this function is called with the current pointer as an argument that variable references the current record in the linked list for the first record current and first are the same as shown in line 21 for now build and run this code one record is input nothing is output that's not a linked list so more modifications are needed open exercise file linked list 5 5 structures are built in the linked list that value is set by the 4 statement at line 24 line 26 checks for the first iteration of the loop if so the first pointer is set up that's the location where the linked list starts otherwise a new structure is fetched at line 34 line 35 references the new structure from the current structure this is the link part of the linked list then line 36 sets the current structure to point at the new structure which moves forward in the list that structure is then filled with data and the loop repeats that's the current next assignment at line 35 that's what builds the list one more thing you need to add you need to mark the end of the linked list insert a line 40 the null pointer is the end of list flag it's not used yet for now build and run the code fill in the 5 account values the next step is to write a function that displays the contents of the linked list open exercise linked list 6 here are the modifications from the previous exercise at line 42 the linked list structures are displayed this starts by setting the current pointer back to the first pointer which is the start of the linked list a while loop then goes through each structure in the list displaying the information the loops condition is the current pointer which means the loop will repeat until that pointer's value is null coincidentally null marks the end of the list the loop advances because of the statement at line 48 the current pointer is updated to point at the next structure in the list I confess it's all complex but each structure in the linked list points to the following structure that's why it's called a linked list build and run the code and the values are displayed you can modify this code further if you like you can add a menu that lets you choose whether to add a structure, list structures even remove structures as long as you keep each structure in the list linked to the following structure it works