Hey, what's going on everybody? In this video, I'm going to teach you everything you need to know to start coding in C. This video contains 12 hands-on projects, and for our final project, we will code a working clock. If that sounds good to you, I encourage you to sit back, relax, and enjoy the show. I don't like boring introductions, so we're just going to jump right in. To start coding in C, you'll need two things. An IDE, that's an integrated development environment. It's a workspace in which we can write code. The other thing we'll need is a C compiler. It converts our written code into machine code so a computer can understand it. In this next section, we're going to install an IDE. In this next section, we're going to download Visual Studio Code. It's a place in which we can write code. You can head to this URL code.visisualstudio.com. Once you're here, go to this blue download button in the corner and then select the correct download for your operating system. I'm running Windows. I will download the Windows version. And our download should start automatically. Now that our download is complete, we're going to open this executable. Read the license agreement. Yes, I did read it that fast. I accept the agreement. Next, you can select a destination folder. I'll keep it the same. Next. Next. You can create a desktop icon if you would like. I think I'll do so. Next. And install. And then just give it a moment. We might as well launch Visual Studio Code right away. I'll keep that checked and finish. Here we are within Visual Studio Code. We're going to create a new project folder. We can close out of this menu. Go to the left toolbar. Go to the explore tab. And we will open a folder and or create a new one. Pick a place in which you would like to create a new folder. I'll do so on my desktop. I'm going to rightclick, go to new folder. I'll call this folder coding, but feel free to pick something else if you would like. Click on your folder, then click this button of select folder. Now, we're going to create a new C file. Within your folder, we're going to go to new file. A common naming convention for a C file is main because it holds the main body of your code. main C. Enter. We're within an empty C file. There's a few extensions I would recommend. Let's go to the left toolbar. Go to extensions. And we are going to look up the C/ C++ extension. C/ C++ extension pack. This will give us some quality of life improvements for C programming. So, be sure to download this extension. Once this extension is downloaded, the next extension is the CodeRunner extension. So, look up CodeRunner and install. Okay, we can close out of this extensions menu and go back to the Explorer window. For the CodeRunner extension, there's two settings I recommend enabling before we continue. Let's go to file, preferences, settings. We're going to look up code runner. Check this check box of clear previous output. That'll clear the output before we run each program. And then scroll down, check save file before run. So you don't have to manually save each time we want to run a program. And those are the two settings I would recommend for the CodeRunner extension. Next on our to-do list is to check to see if we have a C compiler already installed. To do that in VS Code, you can go to the terminal tab. Go to new terminal. Now, the instructions are going to vary based on your operating system. Currently, I'm running Windows. To check to see if you have a C compiler using Windows, you'll type GCC- version. If you don't have one installed and set up, you'll see an error message like this. The term GCC is not recognized. But if you're on Windows and you do have one installed, you'll see something like this. GCC- version. And here's my compiler, gcc.exe. And then I have a version number and some other copyright stuff. Let's clear this terminal. If you need to set up the C compiler for Windows, it's actually really complicated. Look in the description of this video for any timestamps and you can skip ahead. If you're a Mac user, you're going to type C lang dash version. This is how to check to see if you have a C compiler using a Mac. But since I'm on Windows, this term isn't recognized. To install the C compiler on Mac, it's actually pretty simple. type xc code dash select dash install. This will install the C compiler and some dev tools. But again, I'm on Windows. These terms aren't recognized. If you're a Linux user, to check to see if you have a C compiler, you'll type GCC-V. If you're on Linux and you don't have a C compiler set up, you'll type pseudoapp-get update. This will refresh the package list. Hit enter. Then to install the C compiler, you'll type if you're on Linux pseudoapp-get install build essential gdb. This will install the compiler, make, and debugger. Again, this is if you're a Linux user. So, if you're on Windows, we need to set up the Windows installation. Our next step is that we have to download a compiler. It will translate our written code into machine code. To make this as easy as possible, I recommend going to this website, mcs2.org. MSYS 2 is a collection of tools and libraries for building, installing, and running native Windows software. We can really just follow the installation instructions. The compiler is going to be provided with this. We'll download the installer. Then we just have to wait for it. Also, please note to run the installer, this requires 64bit Windows 10 or newer. Once the download is complete, we'll open this executable. Click next. Select a destination folder. I'll keep it as is within my C drive. Next. You can create a start menu shortcut. I'll just press next. And we are installing. We'll run MSYS 2 now. Keep this box checked and finish. We'll use this piece of software MS 2 to download the C compiler. Here's how. Now according to our instructions, the next step is that we have to type this command. Honestly, we can just copy this. Copy and paste. Pac-Man means package manager, not the arcade game. Dash capital S for sync. And here's the name of the package. It's really long. Then I'll hit enter to submit it. proceed with the installation. Capital Y for yes. And this will take a moment. We're downloading all the packages we'll need. Let's ensure that our compiler downloaded successfully. You can type gcc- version. It should display the current version of the C compiler that we're using. All right, we can close out of this window. And now we need to set the variable path. Let's locate that folder. It's within my C drive, MS64. We need to find the C compiler. It should be underneath this folder of UCRT64. Go to bin and we are looking for this file. We're going to copy the file location. I'll right click, go to properties, and copy this location. What we got to do next is set the path variable. We have to let our operating system know where it can find the C compiler that GCC file. We're going to do a search for environment variables. Edit the system environment variables. Click environment variables. Select path. Edit. New. Then paste that path and it should be to that GCC file. Press okay. Then okay. Okay. And that's it. We have downloaded and set up the C compiler from Windows. All right. We're ready to write our first C program within our C file. The first thing we're going to write is this statement. pound sign include then within angle brackets std io.h. This statement is a pre-processor directive. We're telling the compiler to include the standard input output library. It contains a lot of useful functions for output and input. We need this header file in order to display text to the screen. Later on in this program, we need a main function in order for this program to well function. Here's how to create the main function. You'll type int, meaning integer. The entry point for a program is the main function. Main. Add a set of parenthesis, then a set of curly braces. Your program is not going to run without the main function. We can even try it. I'm going to cut it temporarily. To run your C program, go to this arrow and select run code. There's also a shortcut if you would like to use that, too. Well, without the main function, we get this error message. Returned one exit status. I'll paste the main function back in. Now, we don't get that error message. And we do have an executable within our coding folder. Our program is running successfully, but it doesn't do anything. So, you need the main function in order for your program to well function. It's the entry point of your program. What you'll commonly see at the end of the main function is this statement. Return zero semicolon. In the C programming language, the main function is expected to return an integer. It returns it to the operating system. This integer serves as an exit code. Zero indicates that the program ran successfully. A nonzero value typically indicates an error, an error or problem of some kind. In older versions of C such as C89 or C90, omitting this statement will lead to undefined behavior. But in later standards, you can omit the statement. But it's considered good practice to include this return statement just for backwards compatibility. We have a program, but it doesn't do anything. So let's print some text. The main function is the entry point of our program. Within the set of curly braces, we'll write some code that we want to print. To print some code, you can use the print f statement. print f ( (en)), then a semicolon at the end. We end all of our statements with a semicolon. It's kind of like the period at the end of a sentence in the English language. Whatever you would like to print to the screen, you're going to do so within quotes, double quotes. Think of a food you like. My first statement will be I like pizza exclamation point. And now if we were to run this program, we can print this text. So let's run this code. And the output is I like pizza. Let's add a second print f statement. Print f. Let's say it's really good. Then be sure to include that semicolon at the end. Now we should have two lines of output. I like pizza. It's really good. One issue that we're running into is that we're displaying all of the text in one line. To move down to the next line, you can add a new line character, which is a forward slash and an N. That's a new line character. Now, our next line of output should be on the next line. I like pizza. It's really good. To print some text to the screen, you just type print f, then within quotes, add some text. Now we're going to discuss comments. To write a comment in C, you use two forward slashes. Then you can write some text. For example, let's say this is my first program. Comments won't display as output. And you can see that the text color is green. But that's a feature of VS Code. If I were to run this program, we don't see this comment. We still have our output. I like pizza. It's really good. Comments are useful as notes for yourself or for other developers. You can also write a multi-line comment. To start a multi-line comment, use a forward slash, then an asterisk. You'll have an asterisk, then a forward slash again, wherever the comment ends. We could say something like, "This is also a comment." This won't display as output either. We still have I like pizza. It's really good. Throughout the series, I'll be writing a lot of comments. And that's your first lesson in C. Now, you have a homework assignment. In the comment section down below, you have to write two comments and two print f statements. If you don't do your homework, I'm going to call the police and they're going to come to your house and arrest you. And well, everybody, that is your first lesson in C programming. All right, everybody. In this video, I'm going to explain variables in the C programming language. You're probably used to variables back in middle school. A variable represents some value. Well, in programming, we have something similar. A variable is a reusable container for a value. The variable behaves as if it were the value it contains. But we do have the capability of storing more than just numbers. There's different data types. Let's begin with the data type of int, meaning integer. To create an integer variable, we will say int, meaning integer. Then we need a unique name for this variable. Let's say we're working with ages. Let's say int age. We'll assign this variable a value using equals. So let's say that I'm 25. In the C programming language, we have to end each statement with a semicolon. So we can use this variable age and it will behave as if it was the number 25. To display this variable, we can use that within a print statement. So print f. In the C programming language, to display a variable, we'll have to use a format specifier. Let's say we have a string of text such as you are, our variable age, years old. To insert a variable, I'm going to use a percent sign for a format specifier. To display an int, an integer, we'll use d meaning decimal, years old. Following the string of text, I will add a comma, then the variable I would like to insert, my variable age. Let's give it a test run. You are my variable age which is 25 years old. So an int is a whole number, a whole integer. If I were to say 25.5, you know, like it's my half birthday, well, we end up truncating that decimal portion because integers can't store decimals. To store a whole number, you can use an integer. Let's create another variable. Repetition is going to help us remember these steps. Another example of an integer could be a year. int year. What year is it? I will say 2025. Then I'll create another print f statement. Print f. Let's say the year is wherever I would like to insert a variable. I will use a format specifier that percent sign then use d for decimal comma then my variable of year the year is oh and then let's be sure to add a new line character cuz I forgot to add that new line new line that's better you are 25 years old the year is 2025 let's create another. What's another good example of an integer? Perhaps a quantity. Maybe I'm buying just one product. You wouldn't have, you know, half a product, right? Quantities would be whole numbers typically speaking. So, let's say print f. You have ordered. We're inserting a variable. We'll need that format specifier percent D. You have ordered our variable X items. We will insert our variable of quantity. Let's give it a test run. Oh, then a new line character. Okay, here's our variables. You are 25 years old. The year is 2025. You have ordered one x item or items. And then we can change these values too. Maybe I would like to buy two items for the quantity. You have ordered two x items. All right. So those are integers. They're just whole numbers. They don't have the capability of storing decimal portions. That's where the next data type is going to come in. To store a decimal portion, you can use a float, meaning floating point number. What's a good example of a number that contains a decimal? Perhaps a GPA, a grade point average float GPA. I will set this to 2.5. Hey, C's get degrees, right? Then to output this, I would use print F. Let's think of a sentence. Your GPA is use a format specifier. Then for a floatingoint number, we're going to type F for floatingoint number. I'll add a new line character because I'm probably going to forget to do that later. And then I will display my variable of GPA. Your GPA is 2.5 and then a bunch of zeros after. C has a default behavior of displaying six digits after the decimal when working with floatingoint numbers. We do have the capability of changing that, but that's going to be a future video. You could add dot and then a number to display a given amount of digits after your GPA is 2.5, but that's a whole another topic. We'll cover that in a future video. Another good example of a float could be a price. Float price equals 19.99 like $19.99. We will use print f. The price is I'll pick a unit of currency. I'll pick American dollars, but pick whatever you would like to insert a variable. We'll use that format specifier, the percent sign. Then f for a floatingoint number. Then I'll add a new line character because I'm probably going to forget if I don't. The price is we will insert our price variable. Let's see what we have. We have our GPA 2.5. The price is $19.99. To display two digits after the decimal, you can use 02. More on that in a future video. A temperature could be a floating point number. Float temperature 10.1. It's really cold outside. We'll use print f. Let's say the temperature is add a placeholder F for floating point number. Then I'll add a new line character. Then display our temperature variable. The temperature is -10.1. This can be Celsius or F. Let's add that in. To add a degree symbol on Windows, hold Alt, then type 0176. I'll say F4 for Fahrenheit. The temperature is -10.1° F. Then you can set the precision if you would like, but we're not at that point yet. All right. So, those are floatingoint numbers. They're numbers including a decimal portion. We only have the capability of storing six to seven digits after the decimal. If you need more precision, such as if you're working with pi, you can use a different data type known as a double. So let's say double pi equals 3.14159. Then I don't know the rest, so I have to look them up. So with doubles, you can store 15 to 16 digits after the decimal. And then to display a double we'll use print f. Let's just say the value of pi is use a format specifier then type lf meaning long float. Then we will display our variable pi. Now again the default behavior of c is to display six digits after the decimal. you'd have to use point followed by the amount of digits you would want to display. Uh let's say 15. Another example could be euler's number. This I got to look up. I'll just copy this. The value of E is our variable E. Oh, then add a new line character. The value of pi is 3.14 and some change. The value of e is 2.7 and some change. If you have a decimal number that needs high precision, you can use a double. In this series, we'll probably not be working with doubles too often. We'll stick with floats. But at this level, you should still be aware of the existence of doubles. With variables, you can store more than just numbers. You can store characters. Another data type is char, meaning character. Let's say we have a letter grade like what grade did you get on the exam. When working with characters, you need to use a set of single quotes. Let's say we got an A, an A on the exam. That's our grade. Then to display this let's use print f your grade is format specifier then c meaning character then I'll add a new line let's display our grade your grade is a or if I failed this could be an f your grade is f let's think of another example perhaps a symbol char symbol equals then within quotes pick a symbol I will pick uh let's say exclamation point that's the first thing that came to mind let's print our symbol what can we say um I can't really think of anything so let's say your favorite symbol is percent C followed by our symbol. Your favorite symbol is an exclamation point. What about currency? Char currency equals pick unit of currency. I'll pick American dollars. Print F. The currency is percent C to display a character. Then we will display our currency variable. The currency is dollars, American dollars. All right, those are chars. They store a single character. If you've programmed in a different language before, you're probably familiar with strings. Well, in C, we don't have strings. In other languages, a string is a series of characters such as a name. In the C programming language, we use an array of characters to represent a string. So to store more than one character, we can use char again cuz we're working with characters. Think of a variable name such as name. Then add a set of straight brackets. This is an array. An array can store more than one value so to say. We will set this equal to then use a set of double quotes. So now we can store more than one character. Why don't you type in your name? I'll use my YouTube channel name. All right. Then to print our string well our array of characters technically we'll say hello format specifier then s meaning string new line we will display our name hello whatever your name is whatever you typed here with our array of characters also known as a string in other languages you can store it more than one character. And again, they do have to be within double quotes. So, what's another example of an array of characters? Perhaps a food, the name of a food. So, char food straight brackets. Think of a food you like. I'll say pizza. Print f. Let's say your favorite food is format specifier s because we're displaying a string food and I'm forgetting that new line. Hello bro code. Your favorite food is pizza. What about an email? char email straight brackets equals then within double quotes I'm going to say fake. Now with strings you can include numbers but they're treated as characters rather than numeric values. So we can't use them with any sort of math in the future. We have a character representation of the numbers 1 2 3. Then I'll add an extension of
[email protected]. I don't want to give you guys my real email because some of you guys are weird. No offense. Your email is percent s. I'll add a new line email. Hello bro code. Your favorite food is pizza. Your email is
[email protected]. One last data type we're going to cover is bool, meaning boolean. Booleans are either true or false. But to work with booleans, we have to include this header file. At the top, we'll include std b.h meaning standard boolean. And this is a header file. To create a boolean variable, we'll type bool. Bulls are binary. They're either true or false. True means one. False means zero. There's only two possible values. This could be good if determining if somebody is online, for example. We'll create a variable of is online. They're either online or they're offline. So let's say that this is true. So true also corresponds to the number one. That's also valid. Or somebody was offline. this could be false. This also corresponds to the number zero. We tend to use booleans more internally within a program, such as when working with if statements, but you should still be familiar with them at this level. If I was to display a boolean variable, this is what it would look like. So, I'm just going to use a format specifier percent d. We will display online. This would give me the number one. One also means true. If somebody were offline, let's set that to be false. This would be zero. With booleans, we tend to not display them directly using print. You would more likely see them be used internally within a program, such as within an if statement. If statements are a future topic, but I just want to give you a quick demonstration. You would type if a set of parenthesis a set of curly braces. If is online if this value is true or one or do something such as you are online or we can do something else using an else statement. print f you are offline. Let's give it a test run. Our boolean of is online is true. Since this is true, we would print you are online. The number one can also represent true. You are online. Or if this were false, well then we would execute this code. You are offline. False also corresponds with zero. You are offline. However, as humans, using true or false is more understandable to us. By looking at this code, we may not know what one means, but true or false makes more sense. Okay, let's do another example. Let's say is student. I will set that to be true. If is student, if that's true, you are a student. else. You are not a student. Maybe you're alumni. Forgetting that semicolon. You are a student. If this were false, then you're not a student. One last example. Bool for sale. Is something for sale? I'll set that to be false. If for sale, that item is for sale. Else that item is not for sale. That item is not for sale. If it were true, then the item is for sale. So, booleans are either true or false. True also means one. False also means zero, but that's less readable to a human. So to work with booleans, just include this header file. All right, everybody. So in summary, variables are reusable containers for a value. A variable behaves as if it were the value it contains. Integers store whole numbers that tend to be four bytes, at least in modern systems. Floating point numbers are single precision decimal numbers. They take up four bytes. A double has double the precision of a float. They use eight bytes. A char is a single character. They use up one bite. Now, an array of characters, also known as a string, you can store words or whole sentences. The size varies because the strings can vary in length. And then a bool, meaning boolean, stores either true or false. They use up one bite, but they require the standard boolean header file. We'll have a lot more practice with variables. Now, your assignment is to post an integer, float, char, an array of characters, and a boolean in the comment section below. That's your homework. And if you don't do your homework, I'm going to call the police. And well, everybody, those are variables in C. Yo. Hey everybody. In this video, I got to cover format specifiers in the C programming language. Format specifiers are special tokens that begin with a percent symbol followed by a character that specifies the data type as well as optional modifiers such as a width, precision, and flags. Basically speaking, it's a combination of a percent sign, a character, and optional modifiers to format the output. By using format specifiers, we can control how data is displayed or interpreted. Let me give you a demonstration. We've covered a little bit of format specifiers on the previous topic on variables. Let's say we have an integer variable of age. Set that equal to some age. Then we will have a float. This will be a price. Think of a price $19.99. Let's say we have a double of pi. A double is also a floatingoint number, but it has double the precision. However, it takes up more memory. Let's set this equal to the first few digits of pi to keep it simple. 3.14159 26535. Then a char currency. Pick unit of currency. This has to be within single quotes. I'll pick American dollars. And an array of characters, also known as a string, maybe name. Type in your name within double quotes. To display these variables using print f, we'll want to use a format specifier that percent symbol. We'll display the age first. print f within double quotes. We will use the percent sign for format specifier. Then d for decimal, comma, our variable age. So d means decimal. This will output 25. For a float, the corresponding letter for the format specifier is f. Print f percent f. We will display our price. Oh, and then we need a new line character. I tend to forget. You probably will, too. 25 and 19.99 and a bunch of zeros afterwards. All right. All right. Now for a double you have two options. We can either use F or LF meaning long floatingoint number print f percent either f or lf. Then that new line character we will display pi our variable pi. F also works. You may see people use one or the other. However, when we reach the topic on accepting user input, we can use a function known as scanf where you'll want to use lf if we're accepting user input for a double that is. So, just to be consistent for doubles, I like to use lf for both output and input. It helps with consistency and readability. By looking at this variable, I know that this is a double, but for output purposes, f does work, too. You can use either. You do you. Now for a char that's a single character we'll use percent C I will display currency that's the name of the variable there's our symbol and then for an array of characters also known as a string you'll use s print f percent s new line name that's the name of our variable And here's our name. Depending on what you want to display, the percent sign is going to be followed by a given character depending on the data type of what you want to display. And here's a few of the more common data types for beginners. Integers, floats, doubles, chars, and an array of characters, also known as a string. Now, we do have a few optional modifiers. So between the percent sign and the corresponding letter of the data type, there's special characters we can add to format the output. Here's an example. Here's how we can set the width when we display our output. This time we'll have three numbers, three integers. int num 1 equals the number 1. Int num 2 equals 10. int num 3 equals 100. We'll use a few print f statements. We're displaying integers. We need to use percent d as the format specifier. I'll add a new line followed by num one. Then let's copy this print f statement and do the same thing for num two and num three. We're displaying three integers. Now between the percent and the letter, we can type in a number. The number that we place between these two characters will set the width. For example, three. The width specifies the minimum number of characters to print. So now we're printing at least three characters. 1 2 3 including any spaces. So my second number of 10 has one space before it. And with 100, well, it does take up three spaces. If I were to change this to four, let's take a look and see what happens. Now we're printing at least four spaces. 1 2 3 4. You can left justify these values by adding a negative sign before the number. Now these numbers are left justified and we have all the space after. You can also add leading zeros by preceding the number with a zero. Rather than having spaces before each value, we'll have zeros. Maybe num three is negative. Let's reset these. Before the letter that corresponds to the data type, if you add a plus sign, if the number is positive, you'll have a plus sign. If it's negative, you'll have a negative sign. This could be good for accounting. Now, we'll get to precision. We'll need some floatingoint numbers. Let's say we have the following prices. Price 1 equals 19.99. Float price 2 equals 1.50. and price 3 equals -100. 0. To display some floatingoint numbers, we'll use the format specifier of f for floatingoint number followed by a new line character. Let's display price one, then two, then three. Here are the floatingoint numbers, our prices. The default behavior of C is to display six digits after the decimal. When displaying a floatingoint number before the corresponding letter for the data type, you can add dot or period, then the amount of digits to display after the decimal. If we're working with prices, two would be good to display two digits after the decimal. for example, dollars and cents. So, let's do 0.2 for each of these. That looks a lot better. We have 19.99, 1.50, and -100. 0. If this were 0.1, we would display one digit after the decimal. Do keep in mind that the output will be rounded if we were to display it. So 19.99 becomes 20.0. All right. So that's how to set the precision. Add a dot followed by an amount of digits to display it. And with what we've learned, you can combine width, precision, and flags together. Along with our precision of 02, I will also set the minimum amount of characters to display. For the minimum width to display, I'll set that to be seven. And then I'll add a plus sign. So any positive numbers will have that plus sign preceding the number. So with format specifiers along with the corresponding data type, you can set the width, precision, and flags. We'll have more practice with this in the future. And well everybody, those are format specifiers in C. Yo. Hey everybody. In this video, we're going to cover some basic arithmetic in the C programming language because sometimes you got to math. Let's create a few integer variables. int x= 2 or pick a different number. Really doesn't matter. int= 3. Int z equals z. Z is going to store our result. We're going to perform various arithmetic operators on x and y and store the result within z. For basic addition, we can write something such as Z equ= X + Y. Since X is 2 and Y is 3, 2 + 3 is 5. And we're storing that within Z. Then let's print it just to test it. We'll use print F. We're displaying an integer. We need a format specifier of percent D. We will display Z and it should be the number five which it is. That's addition. Then we have subtraction. Z = X - Y. What do you think the results going to be? -1. We have multiplication. You use an asterisk for multiplication. Z = X * Y. 2 * 3 is 6. Then division. Division is going to be a little strange if we're working with integers. Let me show you what happens. Z= X. Then use a forward slash for division. Y. Normally 2 / 3. That should be 666 repeating, right? Well, we actually get zero. We're working with integers. Integers can't store decimal portions. If Z were a floatingoint number, we would also need to change the format specifier to an F. Let's see what happens now. Well, we get zero, but it is a floatingoint number. What we're doing is integer division. If we're dividing by an integer, we can't retain that decimal portion. So in this example, let's change y to be a floatingoint number. And now we get 0.6 repeating. We have that decimal portion. You do have to pay attention to that. If you're dividing by an integer, you won't retain that decimal portion. Then we have the modulus operator. That's going to give you the remainder of any division. Let's change x, y, and z all to be integers. I'll set x to be 10. We'll keep y as three. We'll set Z equal to be X modulus Y. The modulus operator gives you the remainder of any division. 10 / 3 doesn't divide evenly. There's a remainder of 1. Let's test that. We'll need to use the format specifier of D for decimal. 10 doesn't divide by 3 evenly. The modulus operator gives us a remainder of one. It's kind of like back in school how a teacher would say everybody get into groups of three and there's one kid remaining. That's Steve. Steve knows what he did. If y were two, well 10 divides by two evenly. It'd be like the teacher saying everybody in this class of 10 break up into groups of two. Then there's no remaining students left over. The remainder is zero. The modulus operator would be great if determining if a number is even or odd because you could just say modulus 2. If the number is even, it should divide by two evenly. The remainder of 10 / 2 gives us a remainder of zero. But if it were 11, well, there's a remainder of one. That's the modulus operator. Then we have the increment and decrement operator. Increment is represented by two pluses. X is currently 10. If I were to take X add plus, we would increment it by one. Let's display X. So we have 11. Or we can decrement with minus minus. X is now 9. You see increment and decrement operators a lot when working with loops. We would need some way to count the cycles. How many times has this loop cycled? So that's one place where you'll see them. Now with these arithmetic operators, there's also something called augmented assignment operators. These would apply if you're reassigning the same variable. Now let's say that x is 10. If I want to add a number to x and reassign it, for example, two, I could say x= x + 2, and that should give me 12. But there's a shortcut. We can say x + = 2. And that would do the same thing. This could even be a different number like 3. Now x is 13. Now if we're subtracting, we would just have to follow a similar pattern. x = x - 3. Or instead we could say x -= 3. So 10 - 3 is 7. Then we can do multiplication. X = X * 2. X is 10 * 2. That means X will be 20. Or we could say X * = 2. And that will still give us 20. Or division. X= X / 2. That's going to give us five. Or we could say x /als 2 and that also gives us five. These are augmented assignment operators. It's basically a shortcut if you're reassigning the same variable. All right everybody. So those are some basic arithmetic operators in C. All right everybody. In this video I'm going to show you how we can accept user input in C. Now, if you're using VS Code, there's a little bit of setup we have to do beforehand. If you're using a different IDE, you can look in the timestamps and skip ahead. If you've been following along and you're using VS Code, when we accept user input, we can't do so in the output tab. We have to do so in terminal. Here's how we can do that. Go to file, preferences, settings, look up the code runner extension, scroll down, then check this check box, run in terminal. Just for some cleanup and quality of life improvements, let's clear any previous output. And let's do a test. I'm just going to print the word hello. And that should run in my terminal and display the output. Now, the font size may be kind of small. And before displaying any output, you may have a message such as the following. Well, we can actually hide that. If you would like to do that, here's how. Let's go to file, preferences, settings. Again, we're going to look up CodeRunner. That's the extension we're using. We have to edit the JSON file. So, select edit and settings.json. You could increase the font size if you would like. I think normally it's kind of small. You can save all files before running. If this is false, I would change this to be true. within C, we can clear the terminal before displaying output by adding clear, then double and so add that before GCC and everything else that comes after. All right, let's save everything, close it, then do a test run. There we go. That looks pretty good. All right, now we're ready to begin. We're going to assign some variables, but we'll need some variables to work with. We'll have an int of age. Now, rather than assigning this a number right away, for example, 25, just temporarily, we're going to declare this variable, but not yet assign it. We'll have a floatingoint number of GPA. What's your grade point average of grade such as a letter grade, A, B, C, D, or F? And then a name. Our name will be an array of characters, also known as a string. with our string array of name since we're not going to be giving it a value such as you know type in your first name and last name we have to specify a size if we're not assigning it so let's say 30 meaning 30 bytes or think of it as 30 characters our name has a maximum size of 30 characters and I feel like that should be enough feel free to set this to a different number if you would like since we're not assigning these variables values right away. Whichever blocks of memory that these variables are using, it's possible that there's some values already there from when your computer used it previously. We can use some variables even though they're not assigned a value. Other programming languages such as Java would actually prevent this behavior. While C doesn't have those guard rails, if you were to use a variable and you don't assign a value, it can lead to undefined behavior. There may be some values left in there already from a different program on your computer. Just for demonstration purposes, I'm going to output these variables. So, I'm going to print our age variable. It's an integer. We need percent D. I'll display our age. Then, let's do this with GPA. That's a floatingoint number. Our grade, which is a char, that's C. And then our name. Our name is a string. So don't do this. But just for demonstration purposes, I'm going to display some variables that we haven't assigned yet. We've only declared them and allocated some space in memory to store some values. So here's what we got. We have undefined behavior. Oh, and then I need to add some new line characters because I forgot. All right, let's see what happens exactly. Well, we get undefined behavior. My age variable is 398. GPA is 0.0. If I were to run this again, we'll get more undefined behavior. Now, age is 688. And my GPA is like 3 billion. Imagine your GPA being 3 billion on a scale of 0 to four. It's perfectly fine to declare some variables but not assign them a value. Just be sure to not use them before assigning them a value, which is what I did here intentionally. So, what you could do, although it's not strictly necessary, when we declare these variables, we can assign them some values in case we accidentally use them before assigning them, it won't lead to undefined behavior. Just as a best practice, let's assign these to zero or some equivalent value. So, with our GPA, since it's a floating number, zero is fine. But just for clarity, I'm going to set this to be 0.0F. This tells you and other programmers that our GPA should be a floatingoint number and not simply an integer with our grade. What sort of character should we pick? If we're simply just trying to clear out our variable and it's a character, we can use a null terminator. Within single quotes, we will use forward slashzero. This is a null terminator character. Whatever value is already within our variable of grade, we'll set it to be a null terminator to effectively clear it out. With our array of characters of name, we can set this to be an empty string, but it'll still take up 30 characters, 30 bytes. Now, let's print these variables. And we no longer have that undefined behavior. Let me just do a couple test runs. Yeah, it all looks good. Although not strictly necessary, you may want to consider assigning your variables right away because if you access them before assigning them, it can lead to undefined behavior just because there may be some leftover values from a previous program. All right, we have our variables. Now, how do we put stuff within them? Here's how. Rather than using print f, we're going to use a function called scanf to get user input. Let's get our age first. We'll need percent d for decimal comma space. We'll use and then our variable age. And is the address of operator. Basically, we're saying at the address of our variable age, we're going to stick a value within here. So, let's do a test run. Within our terminal, there is no prompt. If a user is running this, they'll be able to type in something. Type in an age and we display our age. However, we should add a prompt to let the user know what they have to type in. If I'm looking at this, it's just a blank screen. I don't know that I need to type in something. Preceding our scanf function, we'll use a printf function. Then we will prompt the user to enter your age. Let's run this again. Enter your age. And then I can type in an age. And we get our output. My variable of age contains the number 25. We have successfully entered user input. Let's type in our GPA. This time we'll need a prompt. Print F. Let me scroll down a little bit. We will prompt the user to enter your GPA, your grade point average. To accept user input, we'll use scanf. We're accepting a floatingoint number. We'll need f percent f followed by the address of operator, our GPA variable. At the address of your GPA variable, stick in a value using scanf. Let's test it. We have our age. Let's say I'm 25. Enter your GPA. Let's enter in a solid 3.1. Okay, our age is 25. Our GPA is 3.1 and a bunch of zeros. And you can limit that by setting the precision when we display it. I'll do that now. 2F. Enter your age. Enter your GPA. All right. Here's our age. Here's our GPA. Now, let's set our grade. Again, we'll need a prompt. Print F. Enter your grade. Perhaps it's a grade on an exam or a test of some sort. Scan F. We're accepting a character. We need percent C for character. At the address of our grade variable, insert a character. and then we'll print it. Let's see what happens. 25 3.2. Okay, now check this out. I wasn't given an opportunity to type in a letter grade. My program spits out as output my age variable and my GPA. Here's the problem that we're encountering. After entering our GPA variable, there's a new line character within the input buffer. When we read that floatingoint number, that new line character is still within the input buffer. And then we're typing in a character for our letter grade. Our C program picked up that new line character and assigned it to the grade variable. We need to clear that input buffer before assigning our grade variable. A shortcut to clear that new line character is with scanf. When we read that character for our grade, add a space before the percent sign. This tells our C program to skip over that new line character. So that's a little shortcut that you can do. Let's test it out. Enter your age. Enter your GPA. Enter your grade. I'll say B. And here's our output. 25 3.2 and the character B. Now we have to assign our name. We could use scan F, but there is a better option. But let's try and use scan F first to see what happens exactly. We'll type in enter your first name, not your full name. We don't want any spaces. Scan F. We are accepting a string. We need a format specifier of S at the address of our name. Then we will print our name. Okay, let's see what happens. Enter your age. Enter your GPA. Enter your grade. Enter your first name. I'll just type in the first name of my YouTube channel. All right. 25 3.2 B. And then I get my first name. Let's change this around. Instead of entering your first name, enter your full name, including a space. Check this out. Enter your age, enter your GPA, enter your grade, enter your full name. Type in your first name and your last name. So, we only get our first name. That's because scan F can't read any white spaces. This is because scan F will stop reading after encountering any spaces. If you were to type in your full name, we only end up storing your first name. A solution to this is to use a different function named fgets. fgets means file get string. But within the set of parenthesis, we have to change a few things around. We'll enter in our variable of name. Then the size of the input. Our input for name is 30. and then type std in meaning standard input. Now if you were to change the size of name let's say we change it to 50. You would also have to do that here manually. A little trick that we can do is calculate it. We can call the size of function and then pass in our variable of name. So if the size is 50, we can calculate it. Then we don't have to type it in manually every time. Okay, let's see what we're working with. We should be able to type in a first name and a last name, including any spaces. Enter your age, enter your GPA, enter your grade. We're still encountering that problem where there's a new line character within the buffer. We need to clear out that new line character before typing in our name. Now, with the fgets function, we don't have the luxury of adding a space before that format specifier to skip over any white spaces. There is a separate function for that. We can call the get char function that can also clear the new line character within the input buffer. Let's try this again. Enter your age. Enter your GPA. Enter your grade. Enter your full name. This is good. We have our integer, our float, our char, and our string, including any white space. For the last part of this lesson, what if we were to move this print statement preceding the other print statements, we'll type in everything again. 25 3.2 B. Type in your full name. We have our full name. Then we have a new line character followed by the rest of our print statements. Why is this happening exactly? Why do we have a new line here? The f gets function reads a whole line of input. When you hit enter to submit that data, it includes that enter key. That's why there's a new line after we display our name. We would need some way to get rid of that new line character within our name variable. Here's one way to do that. This might be a little advanced, but in the future it's going to make more sense. We're going to need the help of a header file. We will include string.h. H this header file for strings. It provides a lot of useful functions related to working with strings. Following the fgets function, we're going to take our name variable, add a set of straight brackets. We need the length of our name. Using that string header file, there's a built-in function of str length, meaning string length. And this is a function. We'll pass in our name. This will return the length of our name minus one. We'll set the last character equal to a null terminator. And then that should work. Let's test this program one last time. 25 3.2 B. Type in your full name. And that new line character is removed. We have our full name, our age, our GPA, and our letter grade. All right, everybody. We have covered a lot of stuff today. If this is a little overwhelming, don't worry. We have a lot of practice projects coming up where we will review a lot of this. We'll take it step by step. And well everybody, that's how to accept user input in C. Hey, what's going on everybody? In this video, we're going to create a shopping cart program using the C programming language. A user can type in the name of an item, a price, and a quantity. This will calculate a total for you. Let's get started. Okay, let's get started everybody. Usually when creating a project, a good first step is to declare all the variables you'll need. We'll need to hold the name of an item. This can be an array of characters, otherwise known as a string. We will create an array of characters named item. What should be the maximum number of characters for our item? Let's say 50. That's a good number. What I like to do is initialize all my variables right away, even if it's to zero or some sort of empty value. I'll set my item to be an empty string. This is just so we avoid undefined behavior in case we use one of these variables before they're assigned. We'll need a price. Our price can be a floating point number. Float price. And I will set this to be 0.0F. If it were a double, you can omit the f, but this tells you and other developers that this should be a floating point number. Then a quantity. How many items are we buying? Int quantity. I will set that to be zero. and a currency. Our currency is a char, a character. Pick unit of currency. I'll pick American dollars. And then a total. That will be a floating point number. Float total equals 0.0F. All right, we have our variables. Now, we need some prompts. We're going to ask a user what kind of item they're buying. We'll need a print f statement. What item would you like to buy? Then another prompt for what is the price of each item. Between each print statement, we'll accept user input. I just want to get these prompts out of the way. What is the price for each item? Let's just say each. for each. Then we need a quantity. We'll ask the user how many they're buying. How many would you like? All right, we have our three prompts. Then we need to accept user input. So with our item, it's a string. We'll need to use fgets. Within the fgets function, we will place our item variable. We need the size of our array of characters 50. But it would be better if we were to use the size of function to calculate it. Return the size of item just in case this number changes. We don't have to manually change it. Then we have standard in std in. Then we need the price. The price is a floatingoint number. How do we get a floatingoint number from the user? We can use scanf. We need a format specifier for a float. That would be percent f. Then use the address of operator. Our price, our price variable. Then we need the quantity. How many are we buying? Quantity is an integer. We'll use scan f to get an integer. The format specifier is percent d for decimal at the address of quantity. Then we will assign it. Then we have a total. Our total is going to be total equals our price times our quantity. Price time quantity. Let's say I'm buying three pizzas and each pizza is $10. Well, 10 * 3 that should be 30. Let's do a test. I'm going to use print f. We'll display our total percent f for floating point number. We will display our total variable. What item would you like to buy? I would like to buy a pizza. I'm going to say $101 for testing purposes. How many would you like? Three pizzas. All right. Currently, our total is 30.03 03 00001. Well, we can set the precision of a floatingoint number. With the format specifier, let's add 02 to display two digits after the decimal so that the output is clearly cents. Let's try that again. I will buy a pizza. The price is $101 and I will buy three pizzas. 30.03. Now let's add our currency. So with our output, we'll add a format specifier for character percent C followed by the total. So we have our character of currency and our total. Do another test run. I would like to buy a pizza. Each pizza is $101 and I would like to buy three. My total is $30.3. And we do have that unit of currency beforehand. So when printing variables, you can list multiple format specifiers all in the same line if you need to, which is what we did here. We're displaying our currency and our total, our char, and our floatingoint number. Let's also print another statement. Let's print something such as I'm actually going to add a new line character. You have bought our quantity variable. The format specifier for an integer is percent d followed by our item name. That's a string. We're going to display our quantity and our item, the name of our item. Then I'm going to add a new line character. Okay, let's see what we got. I would like to buy a pizza. The price will be $12.99. I would like to buy five pizzas. It's for a party. You have bought five pizza. Then we have a space after and then our total of $64.95. Our item name has a new line character within the input buffer. We need to get rid of that. So when we accept our user input for our string using fgets, here's how we can remove that new line character. We'll take the name of our variable, our item. It's a string. Add a set of straight brackets. We need to get the length of our item. We'll need the help of a header file. Include string.h. This header file contains functions related to strings. What is the length of our string of item? This function will return that value. str meaning string length. What is the length of item? If it's pizza, well, pizza has five characters. Well, then if you include a new line character, it's six minus one to go to the end. We're going to set this last character equal to a null terminator character. And that should get rid of that new line character. Okay. What item would you like to buy? I would like to buy a pizza or pizzas. What is the price for each? $12.99. How many would you like? I would like eight pizzas. You have bought eight pizza or pizzas. The total is $13.92. And I'm just going to make one change. I'm going to add s to the end of my item when displaying it. I'll just add slash s just so grammatically it makes sense. I would like to buy a pizza. The price is $12.99. I would like 10 of them. You have bought 10 pizzas. The total is $129.90. You could even add the total is then our total two. If you would like pizza $12.99, I want 10 pizzas. You have bought 10 pizzas. The total is $129.90. All right everybody. So that is a shopping cart program that you can write for practice using the C programming language. Hey everybody. In this video we're going to create an interactive Mad Libs game using C. This topic serves as a practice project so we get used to accepting strings as user input. Let's get started. Before we begin, we'll need to include the string header file because we'll be working with strings. Include string.h. Mostly we just need to remove the new line character at the end of each string when we accept user input. We'll declare the different variables we'll need. The only type of variable we'll be working with in this topic are arrays of characters, also known as strings. Let's create a character array of noun. In the English language, a noun is a person, place, or thing. You're also going to get an English lesson here today, too. Then we'll specify a size. We'll say 50 for a maximum size of 50 characters. That should be more than enough. I'll set these to be empty strings right away. A noun is a person, place, or thing. Then a verb. A verb is an action like running. I will set that to be an empty string. We'll need a few adjectives. An adjective describes something such as fast, slow, loud, quiet. Adjective. I'll just set these all to be 50. We'll need a few adjectives. I'll say adjective one, then two, then three, and I'll just copy this. Then we have adjective 2, adjective 3. These are the variables we'll need. They're all arrays of characters, strings. A user is going to fill these in. We'll need some prompts. We'll use print f. The first prompt we'll ask for is for an adjective. An adjective describes something. Enter an adjective. I'll add a hint here, too. Let's say an adjective is a description. Let's create another prompt. The next prompt will be for a noun, a person, place, or thing. Enter a noun. And I'll add a hint that we are looking for an animal or a person. We'll need an adjective again. I'll copy this print statement and just paste it. Then a verb. A verb is an action such as running or jumping. Enter a verb. I want the verb to end in ing so that it's present tense. Someone or something is currently doing something. Verb ending with ing and then an adjective again. Again, an adjective is a description. We're describing something. Now, we need to accept user input. Since we're accepting strings, including white spaces, we'll use fget gets because scanf doesn't accept any white spaces. A user will enter in adjective one. That's the first argument. Then we need the size of adjective one. We could just say 50, but it's better to calculate it just in case we change it. We don't have to manually change it here too. Return the size of adjective 1. Then we need stdn for standard input. We'll have to do the same thing for noun. We'll do a lot of copying and pasting. f gets noun give me the size of my noun variable then adjective again this will be for adjective 2 then verb our verb variable f gets our verb variable return the size of our verb variable and adjective 3 temporarily. Let's display our variables using print f. We're displaying a string. We'll need a format specifier of percent s for string. Then a new line. We'll display noun, our verb, and our adjectives. adjective 1, two, and three. We just want to be sure that everything's working. Let's do a test run. An adjective describes something. I'll say fast. Enter a noun, an animal, or a person. I'll say sonic. Enter an adjective. Cool. Enter a verb ending with ing. Running. I forgot to add a colon and a space. I'll have to fix that. Enter an adjective. Funny. Here's our output. We have sonic, running, fast, cool, funny. So, there is a new line character within the input buffer. We'll have to remove that. But I also need to add a colon and a space after this print statement because I forgot to do that. Now we need to get rid of that new line character within the input buffer. So to do that, we'll take each variable. In this case, adjective one. We'll start here. Add a set of square brackets. Call the string length function. This will return the length of the string. Pass in our variable of adjective one minus one. set this equal to a null terminator character. Then we just have to repeat this process for the other variables. We'll replace adjective one with noun. Do this with adjective 2, adjective 2, adjective 2, then verb, verb, verb, then adjective three. All right, let's do our test run again. Enter an adjective. Fast. Enter a noun. Sonic. Enter an adjective. Cool. Enter a verb ending with ing. Running. Enter an adjective. Funny. Sonic is my noun. Running is my verb. Adjectives 1 through three are fast, cool, funny. Now we just have to work on our story. We can get rid of these print statements. We're going to write a story using print statements. Then we'll be inserting these variables at key locations. Feel free to write a different story if you would like, but here's one that I wrote. We're going to be visiting a zoo. I'll start with a new line character. Today I went to a We're going to insert adjective one here. We'll insert a string, then the word zoo. New line character. We'll be inserting adjective one at this location before zoo. We're describing our zoo. Is it expensive? Is it dirty? Is it clean? With our second sentence, we'll say in an exhibit I saw a here we'll insert our noun, our person, place or thing followed by a new line character. We'll insert our noun variable. Here print f. We'll insert our noun variable. We'll reuse it. Percent sess our person, place, or thing was insert an adjective and insert a verb. I'll add an exclamation point and a new line. Within this print statement, we have three variables to insert. Our noun, adjective to, and our verb. One more sentence. I was insert adjective three. New line. Adjective three. Let's see our story. Enter an adjective. I'm going to say sussy, like it's suspicious. Enter a noun. If you've been around my channel long enough, you know that I like to poke fun at Mark Zuckerberg. I'm going to type in Mark Zuckerberg. Enter an adjective. Sweaty. Enter a verb ending with ing. Screaming. Enter an adjective. Surprised. Here's my story. Today I went to a sussy zoo. in an exhibit. I saw a Mark Zuckerberg. Mark Zuckerberg was sweaty and screaming. I was surprised. All right, and that's our Mad Libs game. Everybody, do me a favor and post your story in the comments section down below cuz I would like to read them and I'm sure other people would too. And well everybody, that is a Mad Libs game written in C. Hello everybody. In this video, I'm going to cover some useful math functions that you should know in the C programming language. To work with these math functions, we'll need to include the following header file. We will include math.h. Let's say we have a variable an integer of x. I'll set x to be nine in the beginning and then at the end we'll display it. Print f x is an integer. We need a format specifier of d for decimal. And then we'll display x. I need the square root of x which is 9. So the square root is going to be three. I could type the following. I'll reassign x, use the square root function, which is sqrt, and then pass in a number or variable. I'll just pass in x. The square root function will return the square root of whatever x is. X is 9. The square root of 9 is going to be three. Let's test it. Yep, three. So, if I was missing this header file, this is what would happen. We have a warning. There's an incompatible implicit declaration of built-in function square root sqrt. So, that's why that header file is important. Let me comment this out. There's a power function to raise a base to a given power. I'll change x to be two. Let's say x equ= use the power function. We will pass in x to the power of two. We have a base raised to a given power. 2 ^ of 2 is 4. Let's raise x to the^ of 3 which would be 8. x to the^ of 4 would be 16. That's the power function meaning power. We can raise a base to a given power. Then we can round a number. Let's change X to be a floatingoint number. X will equal 3.14. Let's change our format specifier to be an F for floatingoint number. I'm going to take X and round it and reassign it. We'll use the round function. Pass in X. X rounded would give you 3.0. You can always round up by using the ceiling function. X equals seal meaning ceiling pass in X. 3.14 rounded up is going to be four. You can always round down. We'll change 3.14 to be 3.99. X equ= floor to always round down. Pass in X. 3.99 rounded down is 3.0. Let's change X to be -3. There's an absolute value function. X= ABS. Pass in our value or variable. And let's change X to be an integer this time. The absolute value function will give you the distance from 0 as a positive number. The absolute value of -3 is positive 3. If you need the natural logarithm of a value or variable, there's a log function x= log. Pass in x. Let's change x to be a floatingoint number. And I'm going to zoom out a little bit. All right. What's the natural logarithm of x when x is three? That would be 1.09. If you ever need to work with trigonometry, there's a few different trigonometry related functions. For example, we can find the sign of a value or variable by passing in a number of radians. Let's say x is 45. I'm just making up a number here. X will be in radians. By using the sign function, we'll be given the sign. This would be useful if you ever need trigonometry. We probably won't in this series, but it's there if you ever need it. So that's sign. We have cosine x= cos for cosine. Pass in an amount of radians. Again, x is 45 or some other number of your choosing. The cosine of 45 is 0.52. and then tan for tangent. x = tan. Pass in x. Again, x is 45. The tangent is 1.61. All right, everybody. Those are some useful math functions that you should know about in C. Hey, what's going on everybody? This video serves as a practice project. Given a radius, we'll calculate a circle's area, a sphere's surface area, and a sphere's volume. Once a user enters in a radius, let's get started. We'll need to include the following header file. Include math.h. This header file, it contains a lot of useful functions related to math. In this program, let's declare the different variables we'll need. Let's start with the radius. Our radius will be of the double data type. I'll go ahead and initialize this right away. 0.0. We'll need an area. Double area equals 0.0. We'll be working with pi. We can declare that double pi equ= 3.14159. That's good enough. If you have a variable and you don't want to be able to overwrite that variable, you can use the const keyword, meaning constant. Now, we can't accidentally change the value of pi. Oh, and then a good practice for constants is to make them all uppercase. That's a mini lesson for you today. Using the radius and pi, we can calculate the area. A user is going to type in the radius. We'll need a prompt. Print f. Enter the radius and then scan f to accept it. Scan f. We're accepting a double, not just a floatingoint number. We'll use LF at the address of our radius. We'll insert a value there. To calculate the area of a circle, here's the formula. Area equals pi. Now, we have to take radius* radius. Radius squared. Or we could utilize the power function from our math header file. Let's do that instead just so we have more practice with it. Using the power function, we can raise a base to a given power. We will raise radius to the power of two. And that will give us our area. Let's display it. I will use print f. Let's display the word area colon space. We'll need a format specifier. We're displaying a double. Let's use lf. Then we will display our area variable. Let's do a test run. Enter the radius. I'll say 10. The area is 314.159. You could set the precision if you would like. I'll add that here with our format specifier. Let's add 2 to display two digits after the decimal. If the radius is 10, the area is 314.16. Now I stop there. Now let's say we have a sphere. Let's calculate the surface area of a sphere. Let's add another variable. Double surface area. I'll initialize that to be zero. Given a radius, we can calculate the surface area of a sphere. We'll assign surface area. surface area equals now here's the formula 4 * * we'll use the power function raise radius to the power of two and then we'll display our surface area we'll use print f surface area our area is for a two-dimensional circle surface area will be for a three-dimensional sphere we'll use the format specifier 2 to display two digits after the decimal. LF for a double. Oh, then let's add a new line character too. Before I forget, we will display our surface area variable. Enter the radius 10. Our area is 314.16. That's if it's a two-dimensional circle. If our radius is for a three-dimensional sphere, the surface area is 1,256.64. All right, last one. Let's determine what the volume is going to be. Double volume equals 0.0. We have our radius. Then we just have to calculate the volume. Here's the formula. volume equals within parenthesis 4.0 divided by 3.0. I'm dividing by 3.0 so we avoid integer division. Time pi times our radius to the^ of 3. We'll use the power function radius to the power of 3. Then we'll display the volume. I'm feeling lazy. I'm just going to copy this print statement. Volume. Then display our volume variable. Enter the radius. I'll enter 10. Here's our area. Our surface area. Oh, I misspelled volume. Volume. That's not right. There we go. Let's try that again. There we go. Volume. 4,188.79. And if you would like, you can add centimeters or some other unit of measurement after, you know, centimeters, centimeters, centimeters. You could even make these squared and cubed if you would like, but that might be overkill for this lesson. All right, everybody. That is a practice project where we calculate the area of a circle as well as the surface area and the volume. Hey everybody. In this video, we're going to create a working compound interest calculator using C. Before beginning, we'll need to include the following header file. Include math.h. Let's declare the variables we'll need. We'll have double principal. Now, I sometimes get the spelling wrong. I'll type in principal. This is the person in charge of your school. With money and investments, the principal is what you're investing initially. your initial deposit so to say. I'll set that to be 0.0 then a rate and interest rate that will be 0.0 zero and int of years how long are we investing something I will set that to be zero initially then times compounded how often does interest acrew in most cases it's going to be one then a total I don't want to name this variable return because that's a keyword in C we'll say total equals 0.0 zero. Then we need some prompts. First, I'll create a title for our program. We'll say compound interest calculator. New line. Then we need the principal. How much is somebody investing? Print f. Enter the principal. Here's the formula to calculate compound interest. This will be the variable P. We'll use scan F to get user input. We're accepting a double. The format specifier is going to be percent LF. Then at the address of our variable principal, insert a value here. Then we need the interest rate. Enter the interest rate as a percent. If your percent sign is red and you're using VS Code, don't worry about it. VS Code thinks you're trying to insert a format specifier here, but rather we're trying to print a percent sign. You can just ignore that. In our equation, this would be R for the interest rate. Scan F. We're inserting a double. We'll use a format specifier of LF. Then at the address of our variable rate, somebody might type in five for 5%. Eventually, we'll turn that into 05 by dividing it by 100. Actually, let's do that now. Our rate will be rate divided by 100. If somebody were to type in 10, well, 10 divided by 100 would be 0.1. Then the number of years if we put money in the bank let's say how long is it going to be in there acrewing interest print f enter the number of years and this will be t in our equation scan f we need an integer the format specifier is percent d at the address of years. Then the number of times compounded per year. This variable in most cases it's probably going to be one. Print f enter number of times compounded per year. This will be variable n in our equation. Scan f. We're going to get an integer. The format specifier is percent d for decimal at the address of our variable times compounded. Let's make sure everything's working currently. Let's do a test run. Compound interest calculator. Enter the principal. I'll say $1,000 with an interest rate of 10%. Maybe we're putting it into the stock market. Enter the number of years for one year. Enter the number of times compounded per year. One. Okay, looks like everything's working. I just have to add a space right here after this question. Cuz I missed that. Now, here's the formula to calculate the total this variable. It's pretty complicated, but we'll take it step by step. We need to multiply our principle by we're going to use the power function from the math header file. We raise a base to a given power x to the power of y so to say. Now the base is going to be the following 1 plus our rate our interest rate divided by our variable times compounded. We're raising this to the power of y. Y is going to be times compounded times our variable years. That's the formula. If you need to pause the video and write this down. Once we have the amount, let's display it. Print f. We'll say the following. After the amount of years, we'll add a format specifier. Here we're displaying an integer. We'll use a format specifier of D for decimal. Years. The total will be pick a unit of currency. I'll pick American dollars. Then we'll insert the total here. We need a format specifier of LF to display a double. I'll set a precision of2 to display two digits after the decimal. We will insert two variables. The number of years, our variable years that is, and the total, what's the total amount? Okay, let's run this again. Let's say that we put $1,000 into the stock market. The stock market, in this case, will have an average interest rate of 10%. I'll set the time to be one for one year. How often does interest acrew per year? We'll say one. So, according to the math here, I should have $1,100. After one year, the total will be $1,100. But this time, I'll set years to be two. $1,000 with an interest rate of 10% after 2 years. And the number of times compounded per year will be one still. After 2 years, the total will be $1,210. I'll set years to be one, but the number of times compounded to be two. So 1,00 10% interest rate one year, but the number of times compounded per year will be two. After one year, the total will be $1,12.50. All right, everybody. That is a compound interest calculator that you can write using C. Yo, hey everybody. In this video, I got to explain if statements in C. If I could summarize if statements in one or two sentences, I would explain them as the following. With if statements, you do some code if a condition is true. If the condition is false, you don't do it. In programming, it allows for basic decision-making. Let me give you an example. Let's say we have an integer variable of age. Set it equal to some age. What I would like to do for this program is print something if age is 18 or greater. Well, we can use an if statement. If parenthesis curly braces within the set of parenthesis, we check a condition. Really, you can type in whatever you would like. What do you want to check? If our variable age is greater than or equal to 18. If this is true, then we can print the following. You are an adult. Let's test it. Age is 21. We end up printing you are an adult. Now, what if this condition was not true? What if it was false? Let's say age is 12. Well, then we don't do the code. We skip over it entirely as if it never existed. Only do this code if this condition is true. Otherwise, you can do something else by adding an else clause. So, if our age is less than 18, we can print the following. You are a child. Age is set to 12. We end up printing you are a child. So, with an if and else if statement, if this is true, do this. else do something else. It's basic decision- making in programming. Now, if there's any other conditions you want to check, we can check something else using else. If we can check more than one thing. If variable age is less than zero, we'll print something else. We'll print you haven't been born yet. I'll set age to be negative one. We end up printing you haven't been born yet. This condition was false. We skip over it and go to the next condition. Well, this one turned out to be true. So, we do this and skip over the rest. Now, you can add as many else if statements as you would like. Let's check else if variable age is equal to zero. Exactly. Double equals is the comparison operator. We're checking if two values are equal. If you were to use one equals, C thinks you're trying to assign age to be zero. That's the assignment operator. For a direct comparison, use two equals. If variable age is equal to zero. If that's the case, we'll print something else. You are a newborn. I'll set age to be zero. You are a newborn. That's because our variable of age is equal exactly to zero. Now pay attention to this. Let's add another else if statement. Else if variable age is greater than or equal to 65. If that's true, we'll print the following. you are a senior. I'll set age to be 70. So, this should be true. Technically, you would think that we would print you are a senior, but here's what actually happens. You are an adult. We ended up printing this statement rather than this one. Well, that's because this condition is technically true. We read these conditions from the top down. If age is 70, technically 70 is greater than or equal to 18. We would execute this code and skip over the rest. You do have to pay attention to the order of your conditions. In this example, we may want to move this statement first. So, let's switch these around. Let's change this to an if statement and then using else if, we'll check if age is greater than or equal to 18. If age is 70, then we should print you are a senior. If it were 50, well, technically this condition is false. We end up printing you are an adult. The order of your conditions does matter. Let's take this a step further. We'll accept user input this time. I'll set age to be zero. We'll create a prompt using print f. will print enter your age. We need scanf to accept an integer. The format specifier is percent d at the address of age. Insert a value. All right. Now, we should be able to enter in an age. I'll set my age to be1. You haven't been born yet. Let's test it again. What if I was zero? You are a newborn. Maybe I'm 13. You are a child. Perhaps I am 25. You are an adult. And what if I was 99? You are a senior. By using if statements, they allow for basic decisionm. Let's go over another example. In this next example, we'll be working with booleans. We'll need to include the boolean header file. std bool.h. A boolean is either true or false. Let's create a boolean variable of is student. If we're a student, this could be true. If we're not, this could be false. Let's set that to be true initially. Using an if statement, we can check a boolean value. If is student is equal to true, then we can print using print f you are a student. else will print you are not a student. Okay. Is student is set to true. We execute the if statement. You are a student. If this were false, then we print you are not a student. Now, when examining boolean variables, you don't necessarily need is equal to true. You can just check the variable itself because it's already true or false. If is student, if that's true, do this. So, this should work too. You are a student. If is student, if this were false, well then you are not a student. Using if statements with boolean variables is really simple. If this boolean variable contains true, do this. else do something else. One last example. This one involves strings. We'll need the help of the following header file. String.h. Let's say we have an array of characters named name. I'll set this to be 50. 50 characters long. And I'll initialize it to be an empty string. What if we want somebody to type in their name and they don't type in anything? Well, using an if statement, we can check that. First, we'll need a prompt. Enter your name. Using fget gets, we'll accept a line of text including any white spaces. We need the name of our variable followed by the size of our variable. In this case, 50. But it would be better to use size of to calculate it in case it changes. size of name and then standard input. We can check if a string is empty. Here's how. With our if statement with the condition, we'll use the following function. Strnen, meaning string length. If the length of our string name is directly equal to zero, that means a user didn't type in their name. If that's the case, we'll print you did not enter your name. Else, if the length of our name is not zero, that means they type something in. We'll print hello, insert a string, then display our name variable. Okay, let's see how this works. Enter your name. I'm just going to hit enter. Oh, and then we have to remove the new line character at the end. Take our name. Get the length of our name string length minus one to go to the end. set that last character equal to a null terminator forward slashzero. We're doing this because the new line character does count as a letter or a character. So that would technically be one. Okay, let's try it now. Enter your name. I'm just going to hit enter. You did not enter your name. Let's try it again. Type in your full name. Hello, whatever your name is. In my case, bro code. All right, everybody. So those are if statements. Basically speaking, if some condition is true, you do something. If it isn't true, you can do something else entirely. It allows for basic decision-m. And well everybody, those are if statements in C. Hey there again everybody. In this video, we're going to create a weight converter program using C. This is meant to serve as a practice project to help us get used to if statements. Let's begin. For this program, a user can either type in pounds or kilograms. We'll declare the following variables. We will create an integer of choice. I'll set that to be zero right away. For the choice variable, a user is going to pick one to convert from kilog to pound or two from pounds to kg. Let's create a floating point number for pounds. I'll set that to be 0.0F and then kilogram. float kilogram equals 0.0F. Let's print the following. Using print f, let's print weight conversion calculator. Then we'll give the user two options. One will be for kilograms to pounds. Two will be pounds to kilogram. Let's add some new line characters. Then we will create a prompt for enter your choice one or two. Then we need user input. We'll use scanf. We'll be accepting an integer for choice. The format specifier is percent d for decimal. at the address of choice. This is where we'll be storing the value, the user input. So, ideally, a user is going to type in one or two. We'll need some if statements. If our choice is equal to one, we will convert kilograms to pounds. I'll just add a note here for now. kilogram 2 pounds. Else if choice is equal to two, we will convert pounds to kilogram. If we reach an else statement, that means the user selected something that was invalid. We'll print a message to let the user know. invalid choice. Please enter one or two. Then I'll add a new line for choice one. Let's print the following for now before testing. Enter the weight in kilograms. Then if they pick choice two, enter the weight in pounds. Let's do a test run. Weight conversion calculator. Do we want choice one, kilogram to pound or pounds to kilogram? I'll select one. Enter the weight in kilogram. Let's run it again. Let's pick two. Enter the weight in pounds. This time I'll select 99. That's not a valid choice. Invalid choice. Please enter one or two. Okay, that's good. Now we have to accept user input. We'll use scanf to get user input. We're accepting a floatingoint number. We need a format specifier of percent f. Then at the address of our variable kilograms, we're inserting a value. Then we will assign pounds equals our variable of kilograms times the following. 2.2462. And then we'll output the following. Print f. Let's display kilograms. It's a floatingoint number. We need the format specifier of F. I will also set the precision to two decimal places after the decimal. We'll insert a variable there. Then add the word kilogram is equal to here. We'll insert pounds. We need percent f. I'll set the precision to two digits after the decimal. The word pounds. Then a new line. We're going to insert the variables of kilogram followed by pounds. So just to save a little bit of time, let's copy these three lines, then paste them within choice 2. Then we just have to change a few things around. With scan f, we're inserting a value at our variable of pounds. We will take pounds divided by 2.20462 20462 and assign the value to kilogram. We're going to print pounds is equal to kilogram and then switch these variables around. Okay. And that should be our program. Oh, and then I'm going to add colon space after each of these prompts. There we go. Now, let's test it. Weight conversion calculator. Do we want kg to pounds or pounds to kilogram? Let's start with 1 kg to pound. Enter the weight in kilog. I'll just pick a random number. 10.1. 10.1 kg is equal to 22.27 lb. Let's run this again, but we'll select two this time. Enter the weight in pounds. 22.7 lb. Well, 22.7 lb is equal to 10.3 kg. And then if we select something that's not valid, when we enter our choice, we get the following message. Invalid choice. Please enter one or two. All right everybody. So that is a weight converter program that you can write using C. Yo. In this video everybody, we're going to create a temperature conversion program using C. This program is going to be kind of similar to the weight conversion program that we did in the last video. We're going to create a different variation of it. Let's begin by creating some variables. This time we will create a char of choice. And I will set this to a null terminator character. In the last video, a user typed in one or two for their choice for the weight conversion. This time it'll be F for Fahrenheit or C for Celsius. Let's create a floatingoint number of Fahrenheit. And I can never spell Fahrenheit. Fahrenheit. I'll set that to be 0.0F. And then Celsius. This will also be a floatingoint number. Celsius equals 0.0F. 0 F. Those are the three variables we'll need. We'll need a few print statements. Print F. Let's add a title of some sort. Temperature conversion program. Then we'll need a prompt. We'll ask a user if they want to convert from Celsius to Fahrenheit or from Fahrenheit to Celsius. Let's say option C is for Celsius to Fahrenheit. And then option F is for Fahrenheit to Celsius, Fahrenheit to Celsius. And this is option F. Let's add a few new line characters. print f is the we'll say temp for short celsius I'll add a prompt of c or fahrenheit I don't want to type that out fahrenheit we want the user to type in c or f the user's typing in a choice a character c or f we'll use scan The format specifier is percent C for a character. Add the address of our variable choice. Insert a value there. Then we'll need some if statements. If the choice is equal to a character of C, that means the temperature is currently in Celsius and we have to convert it to Fahrenheit. Let's add a comment that this is C to F. Celsius to Fahrenheit. Else if our choice is equal to a character of F, we want to convert Fahrenheit to Celsius. Else the user didn't type in something that was valid. We'll print the following using print F. Invalid choice. Please select C or F. Within our if statement, let's ask for the temperature in Celsius. We'll use print F. Enter the temperature in Celsius. Then we'll do the same thing for Fahrenheit. Enter the temperature in Fahrenheit. Let's do a test run. Temperature conversion program. C will convert Celsius to Fahrenheit. F will convert Fahrenheit to Celsius. Is the temp in Celsius or Fahrenheit? The temperature will currently be in Celsius. Enter the temperature in Celsius. And then the program ends. But we didn't get that far yet. Let's test it again. The temperature is currently in Fahrenheit. enter the temperature in Fahrenheit and that will convert it to Celsius. If we type in something that's not valid, let's say we don't have Kelvin, then we get the following output. Invalid choice. Please select C or F. That works so far. Within our if statement, we need to use scan F to get some input. Scan F. We need a format specifier of percent f for a floatingoint number at the address of our variable Celsius. Then we have to convert it to Fahrenheit. We'll take our variable of Fahrenheit, set it equal to Now here's the formula within parenthesis. We're going to take Celsius * 9 / 5. then add outside of the parenthesis 32. This is to convert C to F, Celsius to Fahrenheit. Then we'll print the following using print F. I'll add a format specifier of F. We're displaying a floatingoint number. I'll set the precision to 0.1 so we display one digit after the decimal. Then the word Celsius is equal to add a format specifier of.1F then the word Fahrenheit which I can never spell so I just copy it and paste it new line then we'll insert our temperatures Celsius followed by Fahrenheit. Let's copy these three lines then make a few changes. So paste them within the LS if statement for the user input using scanf. We will insert a variable at the address of Fahrenheit. Now our Celsius temperature equals this formula. Celsius equals within parenthesis Fahrenheit minus 32 times 5 / 9. And then within our print statement, we'll switch some of these words around. Our temperature in Fahrenheit is equal to our temperature in Celsius. And then we do have to switch these variables around when we display them. We have Fahrenheit, then Celsius. And that should be everything. Let's run it. Temperature conversion program. Let's say the temperature is currently in Celsius. I'll type in C, capital C. Enter the temperature in Celsius. I'll say 30. 30° C is equal to 86° F. Let's test it again. The temperature will currently be in Fahrenheit. I'll type in capital F. Maybe the temperature is 90° F. 90° F is equal to 32.2°. Then I'll type in something that's not valid. Is the temp in Celsius or Fahrenheit? I'll type in P for pizza. Invalid choice. Please select C or F. All right, everybody. That is a temperature conversion program that you can write using C. Hey everybody. In this video, we're going to cover switches in C. A switch is an alternative to using many if and else if statements. It's actually more efficient when working with fixed integer values, and it also helps with readability. Let me give you a demonstration of why switches would be useful. Let's take this sample program. We have a day of the week. It's an integer 1 through 7. If day of the week equals 1, it is Monday. 2 is for Tuesday. 3 is for Wednesday. So on and so forth. Within an else statement, we have please enter a number 1 through 7. Well, currently my day of the week is 1. It is Monday. 2 means Tuesday. Seven is for Sunday. Then if we have something that's not valid, like zero, well, we print, please enter a number. If you use a lot of else if statements, it can be inefficient and it's hard to read. If you find that you're using a lot of else if statements, you can use a switch as an alternative. Here's an example. To create a switch, we'll type switch parenthesis curly braces. Within the parenthesis of the switch, we examine a value. These are good for examining integers and characters. We're going to examine our day of the week. It's an integer. We compare this value against any matching cases. We'll create a case of one colon. Any code underneath this case will execute if these two values match. Our day of the week and this case of one. If our day of the week is one, we'll do something. We'll print it is Monday. Then this is very important. Add break after to break out of the switch. Later on, I'll show you what happens if we're missing it. Case two means Tuesday. If our day of the week matches a case of two, then we'll print it is Tuesday and then we will break. Really, we just have to follow this pattern. And just to save a little bit of time, I'm going to do a lot of copying and pasting. We have case three for Wednesday. Case four for Thursday. Case five for Friday. K6 for Saturday. K7 for Sunday. All right. And that's our switch. You could add a default case, but we'll take care of that in a moment. Let's perform a test run. I'll set day of the week to be one. Well, we print it is Monday. If day of the week was two, then we print it is Tuesday. Three is for Wednesday. Let's skip to seven. 7 is Sunday. Let's temporarily remove these break statements and we'll see what happens exactly. Those break statements will break out of the switch. If we're missing them, then this happens. I'll set the day to be Thursday. That would be four. It is Thursday, it is Friday, it is Saturday, it is Sunday. Once we reach a matching case, in this example, day of the week is 4, we do this code. But if we're missing those break statements, we cascade to the next case and do this code too until we reach a break statement or escape the switch. So let's put those break statements back in. They're pretty important. You can add a default case, too, if there's no matches. Default colon. Let's do the following. If there's no matching cases, please only enter a number one through 7. I'll set day of the week to be -1. Well, we get the default case. Please only enter a number 1 through 7. Or maybe day of the week is 99. Again, please only enter a number 1 through 7. Let's take this a step further. Let's accept user input. I'll set day of the week to be zero. We'll need a prompt. Print f. Enter a day of the week 1 through 7. Then we need scan f to get user input. We're accepting an integer. We need a format specifier of percent D at the address of day of the week. And now we should be able to accept user input. Enter day of the week. I'll type in one, it is Monday. Three, it is Wednesday. Six, it is Saturday. Then I'll type in something that's out of bounds. It's the 69th day of the week. Please only enter a number 1 through seven. Switches can also be used with characters. Let's change day of the week to be a char. And I will initially set this to be a null terminator character. When we enter the day of the week, we'll want to type in a character. M will be for Monday, T for Tuesday, W for Wednesday. Thursday is going to be R because we already have T for Tuesday. F for Friday, S for Saturday. We already have an S for Saturday. Sunday will be U. Since we're accepting a character, we have to use the format specifier of percent C for a character. Now, the matching cases will be characters this time. If our day of the week, this character matches a case of capital M, it is Monday. T is for Tuesday. W is for Wednesday. R is for Thursday. F is for Friday. S is for Saturday. U is for Sunday. Then we'll need to copy these characters. For our default case, please only enter a character. And then we'll give them the following options. All right, this should work too. Enter a day of the week. I'll type in capital M. It is Monday. R is for Thursday. It is Thursday. Capital S, it is Saturday. And then I'll type in something that's not valid. P for pizza day. Then we get that default case. All right, everybody. So, that's a switch. It's an alternative to using many if else statements. It's actually more efficient when using fixed integer values, which is what we did initially. These work really well with integers and characters, and in many cases, it's easier to read than using many if else statements. And well, everybody, those are switches in C. Hey everybody, in this video I'm going to discuss nested if statements in C. In this sample program, we're going to sell movie tickets. If a user is a student, they get a 10% discount. If they're a senior, they get a 20% discount. If they're both a student and a senior, they get a 30% discount. Here's one way in which we can write this program using nested if statements. We'll be working with booleans. We'll need to include the following header file. Include stdbool.h. Let's declare our variables. We'll create a floatingoint variable for a price. I'll set the price to be 10.00 for $10. Let's create a boolean variable of is student. I'll set this to be true right away. Now, if is student is true within our if statement, we can check that if this variable is true, let's print the following message. you get a student discount of 10%. My IDEVS code, it thinks I have an incomplete format specifier here. That's why it's red. You can just ignore that cuz normally with percent signs, we use a format specifier. Then we just have to lower the price by 10%. Let's take our price equals price time 0.9. That will do the trick. Just to shorten this, you can use an augmented assignment operator by using times equals 0.9. Price equals price time 0.9. That's going to do the same thing. Then outside of the if statement, let's print the total price. We'll say the price of a ticket is I'll add pick a unit of currency. I'll pick American dollars. I'll need to insert a format specifier. We're displaying a floatingoint number. We need F. I would only like to display two digits after the decimal. I'll set the precision to be two with 22F. Going to need some new line characters. And then I will insert my price here. All right, let's do a test run. Currently, I'm a student. you get a student discount of 10%. The price of a ticket is $9. Now, what if I wasn't a student? I'll set this to be false. The price of a ticket is $10. We're paying the full price. I'll add a comment before we proceed that says 10% discount if we're a student. If that's true. Now, what if somebody's a senior? Cool. I mean, bull. bool is senior. I'll set that to be true. If somebody's a senior, they get a 20% discount. But if they're a student and a senior, they'll receive a total of 30. Just as a few comments, I'm going to lay out the full prices. A student should only pay $9. A senior is going to pay $8. And if they're a student and a senior, the total should be $7. What we're going to avoid is giving them a 10% discount off the 10. That's going to be $9. And then giving them 20% off of $9. I think that's going to be $7.20 when they really should be paying seven. What I'm about to write is what we want to avoid. If I was to write an if statement outside of the already existing if statement where we check if is senior is true, we're going to give the user a senior discount. And I'll just copy these two lines of code and paste them. You get a senior discount of 20%. And we're going to multiply the price by 0.8. If is student is true and is senior is true, we end up paying $7.20 even though it should be seven. That's because we're taking 20% off of $9 rather than 10, which is where we got the extra 20 cents from. One way in which we can write this program is to use nested if statements. Let's cut this if statement and paste it within our if statement. Pay attention to the indentation too and the sets of curly braces. If somebody's a student and a senior, the total price of a ticket should be $7. Let's move this print statement where somebody's a student and move it to within the nestedive statement. You get a student discount of 10%. you get a senior discount of 20%. And the price is going to be 70% of what it is normally. Let's cut this line of code where we reduce the price by 10%. We're going to add an else statement. If somebody's a student, we enter this block of code. If they're also a senior, we enter this block of code. If they're a student but not a senior, we'll only lower the price by 10%. Let's copy this print statement. You get a student discount of 10%. Then we will take our price and reduce it by only 10%. 0.9. So far so good. What if the user is not a student? Well, we don't end up giving them that senior discount because the only way to access this block of code is if somebody is a student. Why don't we add an else clause to the outer if statement? If we're within the else statement, that means the user is not a student. But we still have to check if there's that senior discount. We'll add a nested if statement within our else statement. I'll just copy this block of code, this nested if statement, paste it, then get rid of that student discount. The price is going to be reduced by 20%. price equals price time 0.8. All right, and that should work. Let me zoom out so you can see it. This is what our full program should look like. Let's do a test run. Initially, I'll set is student to be false. Same thing with is senior. We're going to be paying $10. The price of a ticket is $10. If we're a student, we should receive a 10% discount. you get a student discount of 10%. The price of a ticket is $9. What if we're not a student, but we're a senior? You get a senior discount of 20%. The price of a ticket is $8. What if we're a student and a senior? You get a student discount of 10%. you get a senior discount of 20%. The price of a ticket is $7 rather than $7.20. That was when we weren't using nested if statements. All right, everybody. So, those are nested if statements. It gives you different branches of decision-m. But in the future, there's more advanced techniques such as using the and logical operator. We could check if is student is true and is senior is true. But this is a future topic we'll discuss later. And well everybody, those are nested if statements in C. Yo. Hey everybody. In this video, we're going to create a calculator program using C. This is meant to serve as a practice project to get us used to working with switches and nested if statements. A user is going to enter in two numbers and an operator. Do they want to add, subtract, multiply, or divide? Let's begin. We'll start by declaring our variables. We'll need an operator. This will be a character a char which I will set to be a null terminator in the beginning. This will eventually be a plus sign for addition minus for subtraction that sort of thing. Then a double to store num one. Double num one. I will set that to be 0.0 right away. And we'll need num two which I will just copy and paste and change num one to num two. then a result double result which will well store the result. Then we need some prompts. We'll write them in this order. A user is going to enter in the value for num one followed by the operator then num two. To create a prompt, we'll use print f to print something. Enter the first number. We'll use scan f to get some input. scan F. Now, we need a format specifier. Since we're working with doubles, we'll use the format specifier of LF, meaning long floating point number. Then store this at the address of num one. Let's copy these two lines of code, paste them just to save some time. Then we need the operator. This will be plus minus asterisk for multiplication or a forward slash for division. The format specifier is C because we're accepting a character at the address of our operator variable. Now we do have to clear the input buffer. We'll take care of that in a moment after our test run. Then we have to enter the second number. Enter the second number. store this at the address of num 2. Let's do a test run. Enter the first number 3.14. Well, we're not given the opportunity to enter in the operator. After typing in our number and hitting enter, we've inserted a new line character within the input buffer. We read that number, but we also don't include that new line character. During the next scan f before the format specifier, add a space that will skip over any white space. Let's test it again. 3.14 plus a second number. I'll say two. There we go. I'm just going to add a comment here that you need to clear the new line character from input buffer because people might not notice this space right here. I'm just pointing it out. We have num one, our operator, and num two. At this point, we'll create a switch. We'll type the word switch parenthesis curly braces. I'm just going to zoom in a little bit. Within our switch, what are we examining? We're examining our operator. We examine this value against any matching cases. If our operator matches a case of plus, that means the user wants to do addition. If these two values match, we'll take our result variable and assign it. Assign it with num one plus num two. And then this part's important. We have to break to break out of the switch. Then we need a case for subtraction. I'll just do some copying and pasting. Case minus for subtraction. Num one minus num two. Then multiplication case asterisk for multiplication result equals num one times num two then division. Use a forward slash for division and then num one divided by num two. Then we have to display the result. I'll use print f. I'll display the word result colon space. Insert a format specifier. We're displaying a double. We'll use lf. For a long floatingoint number, I'll display let's say four digits after the decimal. But feel free to pick a different number. Then we will insert our result at this location, this placeholder. Okay, let's do a test run. Pick a number. I'll pick 3.14 plus another number just two. The result is 5.14. Enter the first number 3.14 minus 2 1.14 3.14 * 2 6.28 28 3.14 / 2 1.57. Now, what if somebody types in an operator that doesn't exist? For example, 3.14 P for pizza 420. Well, we don't perform anything within the switch. There were no matching cases. Why don't we add a default case? Default. And then within this case, let's print the following. Let's say invalid operator, then a new line character. Let's try it again. Enter the first number 420 P for pizza 69. Invalid operator and then the result is zero. Here's another scenario. What if somebody divides by zero? Because mathematically we can't do that. 3.14 divided by 0. The result is infinity according to C. So this is where nested if statements are going to come in. Within our case of division, rather than dividing num one by num two right away, let's use an if statement. We'll use if. If num 2 is equal to zero, we don't want to divide by zero. We'll output the following. Print f. You can't divide by zero. If num two is not zero, then we will let them divide num one by num two. This is an example of a nested if statement within a switch. Oh, and then we need a new line character because I forgot 3.14 / 0. You can't divide by 0 and the result is zero. What it was initially, at least it's not infinity. That's an example of a nested if statement within a switch. This just demonstrates that within a switch, there's still additional logic that you can perform. All right, everybody. And that is a calculator program that you can write using C. All right, everybody. In this video, I'm going to explain logical operators in C. Logical operators are used to combine or modify Boolean expressions. There's three we'll discuss and, or not. We can use these logical operators to combine or modify Boolean expressions. Here's an example. We'll begin with and. In this sample program, we'll have a temperature. We'll say temp for short. For now, I'll set it to be zero. Using an if statement, I'll check the following. If my temp my temperature is greater than zero, we'll print the following. The temperature is good. I'll add an else- if statement. else if the temperature temp is less than 30 my temperature is going to be in Celsius 30° C is fairly hot for the weather so anything under 30 will print the temperature is good and I'll just copy this else the temperature is bad the temperature is bad I'll set the temperature to be something reasonable like 25°. Well, the temperature is good. If I change the temperature to be 5°, well, the temperature is still good. Here's an extreme example. What if I set the temperature to be like a cajillion degrees? It's hotter than the surface of the sun. Well, the temperature is still good. Uh, it's actually, in fact, pretty horrible. The issue that we're running into is that with this if statement, our temperature is technically greater than zero. This is true. So, we do this code and skip over everything else. What if there was some way we can check to see if our temperature, our variable, falls within a certain range? Well, we can do that with the and logical operator. Here's how. After checking one condition, you can use the and logical operator to check another condition. To use the and logical operator, you use two and amperands. Let's check if the temperature is greater than zero and the temperature is less than 30. Then we can delete this lip statement. In order for us to execute this code, whatever is within this block, both conditions must be true. This has to be true. The temp has to be greater than zero. And the temp has to be less than 30. If our temperature is set to 1 million° C, well, the temperature is bad. Really bad. This condition is still technically true, but this one is false. And in order for us to execute this code using the and logical operator, both conditions must be true, which they weren't. Or if I set the temperature to be -1° C, well, the temperature is bad. It's below freezing. This condition was false, but this one was true this time. Since both weren't true, we don't perform this code. If I were to set the temperature to be 20, well, that should fall within that range. The temperature is good. This condition was true, and this condition was true. So we do this code using the and logical operator. You can check more than one condition. Now there's the or logical operator which is two vertical bars. In order for us to execute this block of code, at least one of these conditions needs to be true. Let's change this program around. This time let's check if the temperature is less than or equal to zero or the temperature is greater than or equal to 30. If the temperature is below freezing or the temperature is above 30, meaning it's really hot outside, well then the temperature is bad. Else the temperature is good. My temperature is set to 20 currently. The temperature is good. So with the or logical operator, at least one of these conditions needs to be true. This one was false. 20 is not less than or equal to zero. This one was false as well. 20 is not greater than or equal to 30. But if we change these around, I'll set my temp to be 5. Well, the temperature is bad. This condition was true and this one was false. Since at least one of these conditions was true, we execute this code. If I set the temperature to be like a million again, well, the temperature is bad. This condition was false, but this one was true. And since at least one of these conditions was true, we execute this code. So that is the or logical operator. It's represented by two vertical bars. Then we have the not logical operator. We'll create a new variable. This time it's going to be a boolean. Bool is sunny. I'll set that to be true. If we're working with booleans, we'll need the following header file. Include std bool.h. We'll write an if statement. If is sunny, we'll print the following. It is sunny. outside. Else will print it is cloudy outside. Is sunny is set to true. It is sunny outside. If this were false, is sunny is false. It is cloudy outside. The notlogical operator, it's represented by an exclamation point. the not logical operator, it's going to reverse any boolean expression. In this case, we're asking if it's not is sunny. If it's normally false, it becomes true. It's kind of like saying do the opposite. So, if it's not sunny outside, that must mean it's cloudy. Else, it must be sunny. If is sunny is set to false. It's cloudy outside. If is sunny is set to true, well then it's sunny outside. Just remember with the not logical operator, it does the opposite. If something is false, it's now true. If it was true, it's now false. And in the English language, it kind of makes sense. Is it not sunny outside? Well, if it's not sunny, it must be cloudy. All right, everybody. Those are logical operators. They're used to combine or modify boolean expressions. There's and, or, and, and not. And well, everybody, those are logical operators in C. Okay, everybody, we have a very important video today, and that's on functions in C. All a function is is a reusable section of code that can be invoked, also known as calling a function. Functions are nice because we don't have to repeat ourselves. We write some code once and then we can reuse it whenever we want. Here's our task. We have to sing the happy birthday song three times. First, we're going to do this without using functions and then you'll see how they're helpful. We'll begin with a print f statement, a new line character. We'll output happy birthday to you. We'll copy and paste this line again. Happy birthday, dear. And then we'll insert somebody's name here later. Happy birthday, dear name. Happy birthday to you. One more line. We'll say you are some age years old. Then I'll add another new line character. All right, let's see what we have so far. Here's one verse of our happy birthday song. Now, if we have to sing this three times, well, we're going to do a lot of copying and pasting. That's two. And that's three. We have our happy birthday song, not once, not twice, but three times. So, we have accomplished our task. But this is a lot of code to write. And in programming, we try and follow the dry principle. Don't repeat yourself. We're repeating ourselves three times, even though we don't necessarily need to. Wouldn't it be nice if we could write this code once and then reuse it whenever we need? Well, that's the purpose of a function. Let's cut these last two verses of our song. And outside of the main function, we're going to create a whole new function. You start with the return type. Return types are going to be the next lesson. For now, we'll write void. There is no return type. Then we need a name for this function. It should be descriptive of what you're doing. Well, we're singing happy birthday. Let's call it the happy birthday function. Add a set of parenthesis, then a set of curly braces. Any code you want to reuse, you're going to paste within this function. Let's cut our happy birthday song, and then paste it. Now, if we were to run this program, nothing's going to happen. There's no output. In order for us to use this function, we have to call it. You type the function's name, in this case, happy birthday, and follow it with a set of parenthesis in order to call it. If you don't have that set of parenthesis, you won't actually call it. So, be sure to add those. And that does work. We have one verse of our happy birthday song. I like to think of the parenthesis as a pair of telephones talking to each other. You have to call a function to use it. You have to talk to it. We still have to sing our happy birthday song three times. All we have to do is call the happy birthday song three times. And there we go. We have sung happy birthday once, twice, three times. A function is nice because you can write some code once and reuse it whenever you want. You just have to call it. Next, we'll discuss arguments. Suppose I would like to insert a user's name and their age here. If I were to set up some variables, I'll create a name variable, a character array of name. Set it equal to some name, whatever your first name is, and some age. Int age. We have a variable of name and a variable of age. If I was to place my name here, I need to insert a format specifier of s because we're working with strings. I will insert my name variable. Same thing with my age variable. It's an integer percent d for the format specifier. We will insert our age. All right, let's see what happens. I'm calling my happy birthday function. Well, we get some errors. name is undeclared. Age is undeclared, too. Functions can't see inside of other functions. Our happy birthday function has no idea what name and age is. To make our happy birthday function aware of what these variables are. We have to pass them as arguments to the function. Within the set of parenthesis, place whatever you would like to send this function. I'll send our name and our age. However, there's one more step. Our function isn't set up to take these two values. You need a matching set of parameters. Within the parentheses of the function name, you have to list the data type of what you're receiving. We're receiving an array of characters. Char. Then you need a name for what you're receiving. In this case, name. This is a character array. That's the first parameter. We are also receiving an int of age and this should work. Happy birthday dear your first name in my case bro. You are whatever your age is years old. So that did work. Arguments are what you send a function but you need a matching set of parameters. So that function is set up to receive those arguments. Arguments are what you send a function. Parameters are what the function expects to receive. It's really easy to mix up the two. At times, I'll accidentally call these parameters, but people usually know what you're talking about, but technically they're different. Here's a trick to help you remember that these are arguments. In order to use a function, you have to call it. You pass arguments to a function. It's kind of like you're arguing over the phone. Now, what if we didn't pass in any arguments? We have some parameters set up for our function, but we're not sending any arguments. Well, we get an error. Too few arguments to function. Happy birthday. What if the order of our arguments was wrong? I'll pass in age, then name. Our arguments weren't compatible with the types of our parameters. When passing in arguments, you do have to pay attention to the number of arguments you're sending and their data type. One trick you can do with the parameters is you can rename them. They don't necessarily have to be the same. For example, let's rename name as birthday boy when inside the scope of this function. Let's rename age as years old. And this would work too. We still have our name and our age. With your parameters, you can rename the data you're receiving. It won't permanently change these variable names. All right, let's take this a step further. Let's accept user input. We'll need the help of the following header file. Include string.h. I'll set my name to have a size of 50 50 characters and I'll initialize it so it's an empty string. I'll set h to be zero. Now before we call the happy birthday function, we'll get some user input. We'll need some prompts. Print f. Enter your name. Since we're accepting a string, we'll use fgets. So fgets is a function too. That's why we have the set of parenthesis afterwards. We have to call it. It's a built-in function. We have to pass in our name as an argument. The size of our name, we'll use the function of size of pass in our name. Then std in then just to remove the new line character from the input buffer, we can do the following. Take our name with a set of straight brackets. Get the length of our name with the string length function. Pass in our name minus one. Set the ending character to be a null terminator. Then let's get our age. Print f. Enter your age. Then we have to use scan f to get an integer. Scan f. The format specifier is d at the address of age. And that should be everything. So now a user can type in a name and an age. Let's test it. Enter your name. I'll say Spongebob. Enter your age. Spongebob seems like he's about 30. Here's our song. Happy birthday to you. Happy birthday to you. Happy birthday, dear Spongebob. Happy birthday to you. You are 30 years old. All right, everybody. Those are functions. Functions are a reusable section of code that can be invoked. Also known as calling a function. Arguments can be sent to a function so that it can use them. Basically speaking, you can write some code once and use it whenever you want. You just have to call it. And well everybody, those are functions in C. Hey everybody, in this video I got to explain the return keyword in C. return will return a value back to where you call a function. When you call a function, the function can send something back. It's as simple as that. Here's an example. What we would like to do is take a few integers and square them. We'll say int x = 2 * 2. int = 3 * 3 int z = 4 * 4 and then let's print the results. Let's print. We're displaying an integer. We need a format specifier of d. We'll display x. Then we'll need a new line. Then we'll do the same thing with y and z. y z. So this does work. 2^2 is 4, 3^2 is 9, 42 is 16. Wouldn't it be nice if we had a function and we can call that function to square a number. Well, we can do that. Let's declare a function. The first step to declaring a function is you need a return type. A return type precedes the name of the function. For now, we'll write void. We'll fill that in momentarily. We'll create a function to square a number. But we have to pass in a number. We have to set up the parameters. We will accept an integer of num. We'll declare a local variable of result equals the number we receive times the number we receive to square it. Now when assigning these variables, we can just call these functions and then pass in a number. Square the number two. Square the number three. and then square the number four. But we're missing one thing. Our function doesn't return anything. We're passing in two, squaring two, and then storing the result, but we're not actually doing anything with it. What we can do is use the return keyword and return a value or variable back to the place in which we call a function. Once we have our result, let's take our result and return it. Return our result. If you're returning a value or a variable, you do have to list the data type of what you're returning. We're working with whole numbers. We're going to return an int. So, replace void with int. And this should work. Now, it does. 2^2 is 4, 32 is 9, 42 is 16. After calling a function and returning a value, just imagine at the end we're replacing this function call with that value four 9 16. In this case, we can simplify this code too. Instead of creating a local variable of result, we can just return num* num. Then we don't need to declare a local variable. And that's more concise. There's less lines of code. If these were floatingoint numbers or doubles, we'd have to change the data type of what we're returning. Let's say we're returning a double, the parameter for num will be a double. int x will be a double. Same thing with y and z. The format specifiers will be lf. Let's pass in some numbers including decimal portions. 2.1 3.2 2 4.3 and here are the results. Let's create a function to cube a number. We'll return a double. The return type will be double. The name will be cube. We need to set up the parameters so we can accept arguments. We'll receive a double which we will name num. We're going to return num* num * num. That's going to cube a number. So, let's cube two. Cube three. Cube 4. 2 cubed is 8. 3 cubed is 27. 4 cubed is 64. Here's a few more examples. This function is going to be age check. We'll check if somebody is 18 or older. We'll return a boolean value this time. boolean age check. We have to pass in an int of age. Now, if we're working with booleans, we'll need to include the following header file. Include stdbool.h. Once we receive an age, we'll check if our age variable is greater than or equal to 18. Now, since we're returning a boolean, we can return true or false. If age is greater than or equal to 18, we'll return true. Now, this part you don't have to explicitly write. But just for readability and teaching purposes, else I'm going to return false. If age is greater than or equal to 18, we'll return true. Else will return false. So, this is a reusable function. We can use it whenever we call it. Let's create an integer variable of age. Set it equal to some age. Using an if statement, I'll check if call our function of age check. Pass in our age. This function is going to return true or false depending on what the age is. If that's true, why don't we print the following? We'll print you may sign up. Perhaps we're signing up for a credit card or a membership or something and you have to be 18 or older. Else will print you must be 18 plus to sign up. Age is 21. This will result in you may sign up. If age were 12, you must be 18 plus to sign up. Here's one last example. We'll create a function to return the greater of two numbers. It'll return an integer. We'll name this function get max. We have to pass in two numbers, two integers. int x int y. Now we'll check if x is greater than or equal to y. We'll return x. x is the bigger number. else will return y. Return y. Within our main function, we'll create a variable of int max equals call the get max function. Then pass in two numbers two and three. Then print the result. We're displaying an integer. We need a format specifier of d. Then print our max variable. Well, it's three. What about four and three? Well, it's four or four and five. It's five. So, in this example, we have two different options to return x or y depending on which number is bigger. All right, everybody. That is the return keyword. It returns a value back to where you call a function. When you call a function, at the end, you can return something. Just imagine that after the function resolves, we're replacing that function call with a value. Another important detail too is with the main function at the end we're returning zero. We're returning an integer. Zero serves as an exit code. If we return a number that's not zero, that means we have an error in our program. That's why at the end of the main function, we return zero. And well, everybody, that is the return keyword in C. Hey, uh, what's going on everybody? In this video, I'm going to explain variable scope in C. Variable scope, it refers to where a variable is recognized and accessible. Variables, they can share the same name as long as they're within different scopes. You could say a scope is a set of curly braces. Anything within that set of curly braces is a scope, a local scope. Within the same scope, two variables can't share the same name. Let's try and do so. I'll create a variable of result. I'll just set it to be zero. I will also declare another variable of result. I'll set it to be one. I guess here's what happens when I compile this program. We have an error. Redefinition of result. There's a previous definition of variable result. Variables in the same scope. They can't share the same name. We could say result one and result two. That's completely fine. But if a variable is within a different scope, we can reuse the same name. Here's an example. Let's create a function to add. We'll add two numbers. We'll return an integer. This function name will be add. We have two parameters, an int of x and an int of y. Inside of this function, I will create a local variable of result. Much like what we did with the main function, result equals x + y. Then we are going to return our result variable. In order for this program to work, you don't necessarily need to declare a variable. You could just say return x + y. That's how I would do it, but that would defeat the purpose of this lesson. Just for this example, we'll declare a variable. Now, within our main function, we'll call the add function. then pass in two numbers. I'll just pass in three and four. Then at the end, we will print whatever our result is. We're displaying an integer and we will display our result. So this program should run and compile just fine. Our result is seven. We have two variables of result. They share the same name. They can have the same name as long as they're within different scopes. They're each within their own local scope. Our main function can't see what's within this other function. We could create another function too of subtract. I'll do some copying and pasting. Let's create a function of subtract. Result equals x minus y. Then we will call the subtract function. Subtract 4 from 3. Then print the result which is -1. Functions can't see inside of other functions. If I was to create two local variables within the main function, we'll say intx equals, I don't know, five this time. int y= 6. Let's modify these functions so they don't take any arguments. We'll call the subtract function, but have no arguments. Let's see what happens. We have two variables x and y within the main function. Well, we get an error. our function of subtract. It doesn't know what x and y is. They're within a different local scope. Our subtract function can't see inside the main function. Think of a scope as a house. The main scope is our house. The subtract function is our neighbor's house. Our neighbor can't see what's inside of our main function. And our main function can't see what's inside of the subtract function. That's why when we call a function, we have to pass in arguments in order for that function to use them. int x and int y. We're calling our neighbor to let them know about these variables x and y. And that does work. These variables have a local scope. There's also something called a global scope. That's where you define any variables outside of any functions. If we had a variable of int result, I could set that to some number. Then any part of my program would recognize this variable. However, I would not actually recommend doing this, and I'll explain in a moment. This would work too, but it's not best practice. Result is negative one. Result is within a global scope. Any part of my program has access to it, but that makes my program more difficult to debug. Hard to debug. That's because any function could accidentally modify this variable unintentionally. It's best to avoid global variables in C. Unless you're creating a constant, which is another lesson entirely. In C, we try and avoid using global variables if we can. It's better to stick to local variables. All right, everybody. That is variable scope. It refers to where a variable is recognized and accessible. Variables can share the same name if they're within different scopes. We've discussed local and global. And well everybody that is variable scope in C. Hey, what's going on everybody? In this video, I got to explain function prototypes in C. A function prototype is a statement that you list before the main function. A function prototype provides information about a function's name, its return type, and its parameters. It has a few benefits. It enables type checking, allows functions to be used before they're defined, improves readability, organization, and helps prevent errors. It is considered good practice to use function prototypes. Here's one of the benefits. We'll create a hello function. Void hello will accept a character array for the name and an integer for the age. All we'll do is print the following using print f. Print f hello. Add a format specifier. New line character. Then display our name parameter. Then our age. Print f u r. Add a format specifier. We need a format specifier of d years old. New line character. Then a parameter of age. So this does work. Let me call this function. Call the hello function. Pass in a name and an age. I'll just pass in Spongebob because that's the first thing that came to mind. Spongebob will be 30. Hello Spongebob, you are 30 years old. One issue with functions in C is that imagine this is a very large program and we have hundreds of functions. With C programs, we read them from the top down. Before we use a function, we have to define it. It would be nice if our main function was at the top because it drives our program. Let's cut the hello function and paste it after the main function. And we'll see what happens exactly. Well, we get an error. Our C compiler doesn't know what the hello function is. We're trying to use the hello function before we've defined what it does exactly. This code is a lot more organized, though. We have all of our functions after the main function. One way in which we can use the hello function and then define it later is to use a function prototype before the main function. Really, all you got to do with your function is copy the return type, the name, and its parameters. Add a semicolon. And this is a function prototype. We're telling the compiler about the name, the return type, and the parameters of this function, which we define later. So, this should work, too. Hello, Spongebob. You are 30 years old. Let's create another function. We'll do this after the hello function. This function is going to return a boolean. If you're working with booleans, be sure to include this following header file. B check. We'll check to see if somebody's old enough to work at the Krusty Krab where Spongebob works. If age check, we're going to pass in an age. Int age. If our age is greater than or equal to 16, we'll return true. Else, we'll return false. Return false. If you're more experienced with programming, you could just condense this code to the following. Return age is greater than or equal to 16. This would return a boolean, true or false. So, that's a little shortcut that you can do. It'll do the same thing, though. Then we need a function prototype. We're going to copy the return type, the name, and the parameters. Here's our function prototype for age check. And now we can use it. I'll use an if statement. If call our function of age check, pass in an age. We'll say 30. If that function returns true, we'll print the following. You are old enough to work at the Krusty Krab. Else we're going to print print f. You must be 16 plus to work at the Krusty Krab. Okay, let's try it. Our age is set to 30. Hello, Spongebob. You are 30 years old. You are old enough to work at the Krusty Krab. If I were 14, well then you must be 16 plus to work at the Krusty Krab. All right, everybody. Those are function prototypes. They provide the compiler with information about a function's name, return type, and its parameters before you actually define what they do exactly. It improves your code's readability, organization, and helps prevent errors. It is considered good practice to use function prototypes. We'll be using these in the future going forward. And well everybody, those are function prototypes in C. Hey, what's going on everybody? In this video, I got to explain while loops in C. It's a really important topic. A while loop will continue some code while the condition of the loop remains true. Basically, do some code while some condition is true. Here's how to create a while loop. We'll type while, add a set of parenthesis, then a set of curly braces. Within the parenthesis of the while loop, you're going to place a condition. You're going to perform whatever code is within the set of parenthesis while this condition remains true. What you want to avoid is an infinite loop. Here's one example. Let's say that while 1 is equal to 1, we'll continue this code. Since we can't change this, we're going to be stuck in this loop forever. Let's print the following. Now, I wouldn't recommend doing this at home. I'll show you what happens. I'm going to print help. I'm stuck in a loop. Now, don't try this at home. Forever will print help. I'm stuck in a loop. Using a while loop, you can perform some code forever. As long as this condition is true, you're going to need some way to escape a while loop because you need to continue on with the rest of the program and then eventually exit. Here's a more practical example. We're going to have a user enter in a number. We'll create a variable int number. I'll set that to zero right away. We're going to check with the while loop. While our number is less than or equal to zero, we're going to have a user enter in a number, but the number has to be one or greater. We'll create a prompt of the following. Using a printf statement, we'll print enter a number greater than zero. Then we'll need some user input. Scan f. We're accepting an integer. We need a format specifier of percent d. And then at the address of our variable number, we'll insert a value. Now to enter a while loop, the condition needs to be true to begin with. Enter a number greater than zero. I'm going to type in zero. Enter a number greater than zero. I don't think I will. 1. Nope. -2. Nope. -3. Nope. This will continue on forever until we can escape the while loop. This condition has to be false in order for us to escape. I'll type in one this time. And we escape the while loop. We have exited the program. While loops are great when accepting user input because if a user types in something that's not valid, you can reprompt them again to enter in something that is valid. The condition must be true to begin with in order for you to enter it. If I were to set number to be one from the get- go, well, we never actually enter the loop because this condition was false. So, we skip over it. Now, there's also a variation of a while loop called a dowhile loop. With a normal while loop, we check the condition first and only enter the loop if that condition is true. In the beginning, if we say do, we'll do this code once and then check the condition at the end using while and then our condition. Then add a semicolon to the end. Now, what we're doing is saying do this code once and then check the condition at the end rather than the beginning. And this will work, too. Enter a number greater than zero. I'll type in one. That appears to work. What if I set my number to be something that's greater than zero, like one? Well, we still perform this dowhile loop because we check the condition at the end. Enter a number greater than zero. 9. Nope. -1. Nope. 10. And that works. A dowh loop is another variation of a while loop, but you check the condition at the end rather than the beginning. All right. Here's another example. A user is going to enter in their name. We'll create a character array of name. I'll set this to be a max size of 50 characters and I'll initialize it to be an empty string. We'll need a prompt. I'm going to print the following. Enter your name. We'll need to use fgets so we can get a line of text. The first argument is our name. We need the size. Rather than typing 50, I'm going to use the size of function. Pass in our variable name and then std in meaning standard input. Then just remove the new line character from the input buffer. I'm going to write the following. Take our name, use a set of straight brackets, call the string length function to get the length of our name minus one. set that equal to a null terminator character. That'll remove the new line character when we hit enter when entering our name. Oh, and then we need to include the following header file. Include string.h. That's if we're working with the string length function. Okay. So, once somebody enters in their name, we're going to write a while loop. while parenthesis curly braces for the condition. What we're going to check is if the length of our name is equal to zero, that means somebody didn't enter in their name. To get the length of a string, you can use the string length function. Pass in your string, in this case name. If the length of our name is zero characters, is equal to zero, that means the user didn't enter their name. If that's the case, we're going to print the following. Name cannot be empty. Please enter your name. And then we'll use fgets again as well as remove the new line character from the input buffer. Then when we escape the while loop, let's print the following. We'll say hello. Add a format specifier for a string, our name. And this should work. Let's try it. Enter your name. I'm just going to hit enter and not type in anything. Name cannot be empty. Please enter your name. No. Please enter your name. No. No. No. No. No. Okay, I give up. We're stuck in a loop. In order for me to escape this loop, the length of my name cannot be zero. I'll type in my first name. And there you go. Hello, your name, whoever you are. And we have escaped the while loop. Here's one last example using booleans. This time we'll use booleans. Be sure to include the following header file. We're going to pretend that we're playing a game. We'll create a boolean variable of is running. Is running. And I'll set that to be true right away. A user is also going to type in a response. This will be a character, a char response. I'll set this to be a null terminator. If our response, if this character is Y, we'll continue the loop. If they'd like to quit the game, they type n to quit. With our while loop, we're going to write the following. The condition is going to be is running. Now, since this is a boolean, you don't need to say is equal to true. You can just say is running because this already is true or false. While our pretend game is running, that's true. We'll print the following. I'll use print f. You are playing a game. And then we will create a second print f statement. Would you like to continue? y equals yes. N equals no. Then we need scan f. We're accepting a character format specifier. We need to clear the new line character from the input buffer. So, we're going to type space format specifier C. That way, scan F will ignore any white spaces. Then add the address of our response variable. We'll insert a character. Let's do a test run. It's not complete quite yet. You are playing a game. Maybe it's Oregon Trail or something. I don't know. would you like to continue? Then you'll type in a letter like yes, I would like to continue. So why why really you can type in anything. But we have no way of escaping the loop. In order for us to escape this loop is running needs to be false. We'll write an if statement within the while loop. We'll write the following. If our response does not equal, for not equal, you can use an exclamation point then an equal sign. If our response does not equal a character of capital Y, maybe they type in N, we'll set is running equal to be false. And then we can escape the while loop. Once we do escape, let's print the following. print f you exit the game and make sure you write this outside of the while loop, not within it. Okay, let's do another test run. You are playing a game. Would you like to continue? I'm going to type in capital Y. You are playing a game. Would you like to continue? Yes, I would. You are playing a game. Would you like to continue? I'm going to type in N for no. You exit the game. If somebody were to type in a lowercase Y, well, technically our response would not equal a character of capital Y. There are string functions where you can make a character uppercase, but another option is to use the and logical operator and our response does not equal a character of lowercase Y. To continue playing the game, we can type in an uppercase Y or a lowercase Y. You are playing a game. Would you like to continue? I'll type in an uppercase Y. Therefore, we continue. A lowercase Y also works. But if I type in any character besides Y, then we exit the game. You exit the game. This can also be done with a dowhile loop, too. You can write do move the while and the condition to the end. And this would do the same thing. All right, everybody. Those are while loops. You continue some code while the condition remains true. The condition must be true for us to enter the while loop. A loop will continue forever as long as its condition remains true. And well everybody, those are while loops in C. Yo, what's going on people? So today we got to discuss for loops in C. A for loop, it's really similar to a while loop. One of the differences is that you tend to use a for loop if you want to repeat some code. a limited number of times. If you need to possibly perform some code forever, a while loop would be better, but there's a lot of overlap where you could use one or the other. Creating a for loop, there's three optional steps. Initialization, a condition, and then update. Each is separated with a semicolon. Let's say we would like to count to 10. Here's how to create a for loop. You type four parenthesis curly braces. Within the parenthesis, we have our optional steps. The first step is initialization. We can create some sort of counter. A common programming convention for your counter is to create an integer of I. I in this case means iteration, but really anything will work such as X, but you tend to see I. We'll set that equal to some number. We'll set it to zero. We'll start counting from zero. Each of these steps should be separated with a semicolon. The next step is a condition. When do we want to stop? We'll stop as long as I is less than 10. If I becomes equal to or greater than 10, we'll exit the for loop. This is our stopping condition. For the next step, we need a semicolon. Then we can update our counter, our counter of I. We'll say I ++. During each iteration of our loop, we'll increment I by one after each cycle. Just to test this, let's print the following using print f. We're going to display an integer. We need a format specifier of d. I'll add a new line character. Then we will display our counter of i. We should print the numbers 0 through 9. 0 1 2 3 4 5 6 7 8 9. If you want to count to 10 starting at 1, you could change i to be 1. And then the condition will be I is less than or equal to 10. Then we'll start at one and then count to 10. Or if we want to count to 100, we can set our condition to be I is less than or equal to 100 and we count all the way to 100 starting at one. You can even count by twos or some other number. Instead of incrementing I by 1, we're going to increment by two by setting the update step to be I +als 2. Then we should count by twos starting at 1. 1 3 5 7 9. Or if we were to start at 2 where I equals 2, we start at 2 and then count by twos all the way until 10. Or what if we counted by threes? I plus equals 3. We start at two, counting up by three, five, 8. What if we would like to count down? Let's start at 10 and count down to zero. We'll set I equal to 10. We'll continue as long as I is greater than or equal to zero. Then I minus minus to decrement. We start at 10, count all the way down to zero. If we would like to count down by twos, we could say I minus equals 2. Start at 10. And we're counting down by two all the way to zero or even three or some other number. 10 74 1. All right. Now, here's a mini project. We're going to count down from 10. We'll start at 10, countdown to zero, and then print happy new year. Like it's a countdown to a new year on New Year's Eve. We'll print happy new year when we escape the for loop. We'll start at 10, countdown to zero, and decrement by one. I minus minus. Then we have 10 9 8 76 54 3 2 1 0. Happy New Year. We can have our program sleep for approximately 1 second between each cycle of the for loop. Here's how. We'll need to include the following header file. include. Now, if you're using Windows, include this header file, windows.h. This header file includes a sleep function meant for Windows. If you're on Linux or Mac, you'll need to include the following include uni st.h. This file is for Windows and this one is for Linux/Mac. All right. Before displaying a number, we're going to call the sleep function. If you're on Windows, type sleep with a capital S, then pass in 1,00 milliseconds. If you're on Linux or Mac, sleep is going to be lowercase, and you pass in seconds rather than milliseconds. I'm running Windows, I'm going to pass in 1,00 milliseconds to the sleep function, which starts with a capital S. And now this should work. Between each cycle, our program is going to sleep for approximately 1,000 milliseconds. Here we are. We have 10 9 8 7 6 5 4 3 2 1 zero. Happy New Year. All right, everybody. That's a for loop. You repeat some code a limited amount of times. There's a lot of overlap where you could use a for loop or a while loop. Four loops tend to be better to do something a certain or limited amount of times. And well everybody, those are for loops in C. Yo. Hey everybody. Today I got two important keywords to discuss with you today. Those keywords are break and continue. We'll be using these two keywords in the context of a loop. If you use break, you'll break out of a loop. If you use continue, you'll skip the current cycle of a loop. Imagine you have a remote. Break would be similar to a stop button. Continue would be similar to a skip button. Here's a demonstration of both. We're going to create a for loop that just counts to 10. We'll need a counter int i. I'll set that equal to one. We'll continue this loop as long as i is less than or equal to 10. After each cycle, we will increase i by one. During each cycle of this loop, let's print the following. I'll use print f. We're displaying an integer. We need a format specifier of percent d. I'll display a new line. And then I will display i. This should display the numbers 1 through 10. Which it does. We have 1 through 10. What I would like to do is if i is equal to 4, I would like to break out of this loop. Well, we can use an if statement. Then add the break keyword. During each cycle, we'll check the following. If I is equal to 4. If I is equal to 4, then we will break. We will break out of this for loop. Here we are. We have counted 1 2 3. Once I equals 4, we break. If you ever need to break out of a loop, you can use a break statement. You also see this in switches, too. In order to break out of a switch, you need to use a break statement. Break is similar to a stop button on a remote. Now, continue will skip the current cycle of a loop. Let's replace break with continue. If I equals 4, we're going to skip the current cycle as if we're skipping it. 1 2 3 5. We skipped four because we have this continue statement here. We skip the current cycle. All right everybody, that is a super short lesson for you today. Break break breaks out of a loop. Continue will skip the current cycle. And well everybody, that is both break and continue in C. All right, what's going on everybody? In this video, I got to explain nested loops in C. A nested loop is really just a loop that's inside of another loop. It can be any combination of for loops, while loops, or dowhile loops. Here's an example. We'll start with a for loop. All we'll do is print the numbers 1 through 9. We're going to set int i equal to 1. Continue as long as i is less than 10. Then increment i by 1 with i ++. During each cycle of this loop, we're going to print the following using print f. We're going to display an integer. We need a format specifier of percent d followed by a space. Then we will display whatever i is our counter. It'll start at 1 and stop once it reaches 10. Here's the output. We have the numbers 1 through 9. Each cycle is separated with a space. What if I would like to do this three times without using any sort of nested loops? We could do the following. Well, we would need a for loop three times. And really, we can just copy and paste what we already have. There's one thing we're missing currently, but I'll show you the output. We do display the numbers 1 through nine three times because we're using three different loops. 1 through 9, 1 through 9, 1 through 9. Before each for loop, I'm going to print a new line character just so it's easier for us to read. After escaping the for loop, let's print the following. just a new line character. And here's the new output. We're displaying the numbers 1 through 9 three times because we're using three different loops. We are repeating ourselves a lot. We try our best to follow the dry principle. Don't repeat yourself. And we're repeating ourselves three times. What we can do instead is write a loop that will cycle three times and stick this loop within it. Here's a demonstration. Let's create another loop. Four int i. I'll set this equal to one. We'll continue as long as i is less than four. Increment i by 1. This loop is going to cycle three times. Then stop once i reaches four. Let's take the loop that we've previously written, cut it, and then paste it within this other loop. There's one issue I would like to bring up before we run this. We're reusing the same index of I within the outer loop and the inner loop. If you have an inner loop, a common naming convention for the index is to use J rather than I because J comes next in the alphabet. This is a common programming practice. Then we're going to print J. Just be sure that you're using a different counter with the outer loop and the inner loop. And this will have the same output as we did previously. We get the numbers 1 through 9 three times. We have an inner loop that prints the numbers 1 through 9. Then our outer loop just cycles three times. A nested loop is really just having a loop inside of another loop. Here's an exercise that we can work with. We'll create a multiplication table. We'll start with the loop that cycles 10 times. For int i is equal to 1. We'll continue as long as i is less than or equal to 10. Then increment i by 1. During each cycle of this loop, I'm going to print the following. We'll display an integer and a space to follow each value. We will display whatever i is. This will give us the numbers 1 through 10, each separated with a space. Now, I would like to do this 10 times. We'll need another loop to cycle 10 times. And really, we can just copy what we have to save a little bit of time. This outer loop is also going to cycle 10 times. Let's cut this for loop. Paste it within the outer loop, but change the index from I to J. Be sure that we're printing J rather than I because I forgot to change that originally. After the inner for loop is complete, we're going to print a new line character using print f. We're going to display just a new line character. Here's the output. We get the numbers 1 through 10 10 times. Rather than displaying J, we're going to multiply I * J and output the result. Here's our multiplication table currently. But we'll want to do a little bit of formatting because nothing's really aligned properly. With the format specifier, I'll allocate three spaces, let's say, to display each integer. And here's our multiplication table. 1 * 1 is 1. 10 * 10 is 100. And we have everything in between. These indices of i and j are going to change. That's how you can use nested loops to display a multiplication table. All right, one last example. Using nested loops, we're going to create some two-dimensional rectangles. A user is going to enter in the number of rows and columns and a symbol that they want to use. Int rows, I'll set that to be zero. Int columns, I will set that to be zero. And a character, which we will name symbol, and I will set this to be a null terminator. We'll create a prompt. Enter the number of rows colon space. We'll use scan f to get an integer. The format specifier is percent d at the address of our rows variable. We're asking how many rows do you want for our 2D graphics. Then the columns. Enter number of columns. At the address of our variable columns, then a symbol to use. Enter a symbol to use. We're accepting a character and we also want to remove the new line character from the input buffer. Before the format specifier, we'll add a space to ignore any white spaces or new line characters. At the address of our symbol variable, let's see what we have currently. We should be able to enter in the number of rows, columns, and a character. We'll say three rows, nine columns, and I'll use an at sign. Okay, so far so good. Now, here's the tricky part. Our outer loop is going to be in charge of the rows. Our inner loop is in charge of the columns. Let's start with the columns. That's going to be the inner loop. We'll need a for loop. Int i. I'll set that equal to zero. We'll continue as long as i is less than our columns variable. Let's pretend that columns is 9. We're going to cycle this loop nine times. Then then increment i by one. For the time being, let's print our symbol to test it. We need a format specifier of C because we're displaying a character. Then display whatever our symbol is. Currently, this should only be one row. I'll just type in three rows, nine columns, and I'll use an at symbol. And this should be nine. Nine columns. 1 2 3 4 5 6 7 8 9. There we go. Now, we need an outer for loop that's in charge of the rows. Let's create another for loop. Int i is equal to zero. We'll continue as long as i is less than our variable of rows. Increment i by one. We're going to take our previous for loop, cut it, and paste it within this loop. This is the outer loop. This is the inner loop. Once we finish displaying each row, we'll want to print a new line character to go down to the next line. Display a new line character. The outer loop is in charge of the rows. The inner loop is in charge of the columns. Now, here's the result. Enter the number of rows. I'll say three. Enter the number of columns. I'll say nine. Enter a symbol to use. I'll use an at sign. And there we are. We have a rectangle. It has three rows and nine columns. Let's test it one last time. I'll mix up the number of rows and columns. Let's do six rows, three columns. And I'll use a dollar sign. We have six rows. 1 2 3 4 5 6 and three columns. 1 2 3. All right, everybody. So, those are nested loops. It's really just any kind of loop within another loop. There's various different situations in which you'll find you'll need a nested loop. And well, everybody, those are nested loops in C. Hey everybody. In this video, I'm going to show you how we can generate some very basic random numbers in C. What I'm about to show you are pseudo random numbers. They appear random, but they're actually determined by a mathematical formula that uses a seed value to generate a predictable sequence of numbers. They're not truly random, but they appear random. There are more advanced techniques such as using the Meren Twister or even hardware entropy, but we're not at that level yet. That's more advanced stuff. We're just going to cover generating some very basic pseudo random numbers. Here's how. We're going to need the following header files. Include stdlib.h meaning standard library. Also, time include time.h. One of the steps to creating a random number is to call the random function, rand for short. However, if I were to output this, we're going to have one issue. The result is always going to be the same. We'll call the rand function and then display whatever the integer is. Every time I run this program, I myself I'm getting the number 41 every single time I run it. That's because with generating pseudo random numbers, we're plugging a base seed value into a mathematical formula to generate a sequence of numbers that appear random. The base seed value in most cases is either zero or one. It's similar to Minecraft for generating a world. If you type in the same seed value, the world is going to be the exact same. It's a similar concept. What we'll do is create a seed value based on the current time. To set the seed, we'll call the s rand function. Within this function, call the time function to get the current time. But you can either pass in zero or more commonly, you see people pass in null, meaning no value. Zero and null will do the same thing. This is just more readable using null. All right. Whatever the current time is, we'll use that as a base seed. Now, our random number should at least change. Again, I'll use print f. We're displaying an integer. We will call the random function. And now we should get a somewhat random number based on the time. Now depending on your operating system and the compiler you're using, the number you're given can vary. To find out what the maximum value is, you can output this constant of rand max. For me, this number is just over 32,000, but for you, it might be over 2 billion. Again, it depends on your operating system and the compiler that you're using. With this number that we're given based on the current time, how can we use this to generate pseudo random numbers? Here's one technique. We're going to create a variable. Let's say random num equals called the rand function. We're going to use the modulus operator. The number we're given, modulus gives you the remainder of any division. Let's say I would like one of two possible values, one or two. I could say modulus 2. And then we'll print our random number. Using print f for displaying an integer, we will display our random number. And here's what I have currently. I either get zero or one. We'll need to add an offset. If I would like a random number between 1 and two, well, I'm given 0 through one. We'll add an offset by enclosing this formula with a set of parenthesis, then add plus one to the end. That will give us a random number that's either 1 or two. For greater ranges, let's create a few more variables. Int min, I'll set that equal to one. And int max, I'll set that equal to six. Maybe we're rolling a six-sided die. We'll say modulus 6 or in this case max. Then add our offset of one. Whatever the minimum is. Let's see what we have currently. I got five 6 3 1. Let's change up the minimum. What if it was 50 and the max was 100? Here's what we have. Well, I got 109, which is above our maximum. For the modulus operator, we're going to subtract the minimum from the maximum. Max minus min and close them within a set of parenthesis, then add plus one for the offset. And that's the full formula. And let's test it. And I got 55. 61 68 71. If max is 100 and min is 50, this would give us 50. We're adding an offset of one because with the modulus operator, zero is a possible value. Then since the minimum is 50, we're just adding that as an offset. This will generate a random number between 50 and 100. If you need a few random numbers, we can just call the random function again. Let's copy this line of code. Paste it twice. Rename these variables because they need different names. We'll need to display three integers. Percent D, percent D, output random number one, random number two, random number three. And we should get three pseudo random numbers. 60 93 77 80 68. This is the formula that you'll need to create a pseudo random number. All right, everybody. And those are pseudo random numbers and how to generate them in C. Yo. Hey everybody. In this video, we're going to create a very basic number guessing game in C. We'll be generating some pseudo random numbers using a while loop. We'll continue to guess what the correct number is until we get the right answer. This is meant to serve as a practice project for beginners. Let's begin. You'll need to include the following two header files. Standard library.h and time.h. To generate some pseudo random numbers, we'll need to set the seed. We can do that with the function srand. The default value for a seed is usually one. So, what we'll do is use the current time by calling the time function and passing it into the srand function. To get the current time, you can either pass in zero or null. Null, in my opinion, is more readable. If we don't set the seed for a random number generator, it's going to give us the same number each time. We'll need the following variables. An int of guess to hold our current guess. We'll keep track of how many times we've guessed, how many tries. int tries. I will set that to zero. Here you'll pick the range of numbers you would like to use. The random number will be between 1 and 100. Int min. The minimum I'll set that to be one. And max I'll set that to be 100, but feel free to pick different numbers if you would like. You could even increase the range, too. Here's the formula to generate a random number and see. I'm going to create an integer of answer. This will be a random number. Set it equal to. We're going to call the rand function. This will give you a random number between zero and whatever the max value is with your operating system and the compiler. For me, the maximum random number is just over 32,000. We're going to combine this with the modulus operator. The modulus operator will give you the remainder of any division. You would think I could say just 100 or max because it is 100. Rand modulus max in my case would give me a random number between 0 and 99. This number is exclusive. I don't get 100. So let's pretend that our minimum was 10 for a moment. I need a number between 10 and 100. I could say max minus min. That would give me 90. This would generate a number between 0 and 89. Technically I'll add + one and close this part of the equation with a set of parenthesis just to force operator precedence. then add the minimum as an offset. Here's the full formula, but I'll set the minimum back to one. It is kind of complex. I admit that. Just to test our answer, let's print it. I want to be sure that everything's working. We will print an integer. We will display our answer. And it should be a random number between 1 and 100. 90. There we go. Let's print a welcome message. I'll print the following. We'll say number guessing game just as a title. We're going to continue playing while our guess does not equal our answer. Well, we can do that with a dowhile loop. do this code once while our guess does not equal our answer. Now, once we finish this game, we're going to display a score as well as what the random number is. We're going to print the following. We'll print the answer is insert an integer. Add a new line. We will display our answer. Then display the number of tries. How many attempts did it take the user to guess the right answer? It took you insert an integer tries. Then display our variable of tries. All right, within the dowhile loop, we'll ask for a number between our minimum and our maximum. We'll print using print f. Guess a number between insert an integer. This will be for the minimum dash insert an integer for the maximum colon space. We will display our min and our max. Then we will use scan f to get some user input. Scan f. We're accepting an integer at the address of our guess variable. Once we insert our guess, we're going to increase our variable of tries. tries++. How many attempts did it take for us to get the right answer? Let's do a test run. Oh, then I need a new line character after our title. There we go. Number guessing game. Guess a number between one and 100. I'll just guess something right in the middle. 50. No, that wasn't it. 75. Nope. After each incorrect guess, we'll let a user know if their guess is too high or too low just to narrow down the possible ranges. After we increase tries by one, we'll write an if statement. We'll write if our guess is lower than our answer then we will print too low just to let the user know too low new line character. If our guess is greater than our answer, we'll check that with an else- if statement. Our guess is greater than our answer. we will print too high. If our guess isn't less than our answer and our guess isn't greater than our answer, that must mean our guess equals our answer. If that's the case, then we should reach this else statement where we'll print correct correct new line. And that should be everything. Let's run it. Number guessing game. Guess a number between 1 and 100. With these sorts of games, I like to do a binary search. I just keep on guessing in the middle of a range. I'll start with 50. Something right in the middle. Too high. The number should be between 1 and 50. Then again, I'll just guess something right in the middle. 25. Too high. The answer is between 1 and 25. 12. Too low. It's between 12 and 25. 18 too low. It's between 18 and 25. 21 too low. 23 too low. 24. That should be it. Correct. The answer is 24. It took you seven tries. All right, everybody. And that is a very basic number guessing game that you can write as a project in C. Yo. Hey everybody. In this video, we're going to create a working game of rock paper scissors in the C programming language. It's pretty straightforward. Pick rock paper scissors and the computer is going to pick a random choice. Then we'll determine who wins. That's pretty much it. Let's get started. Okay, let's get started everybody. For this project, we'll be generating some random numbers. You'll need to include the following two header files: standard library.h and time.h. Let's declare our function prototypes. This project requires three functions. The first is to get the computer's choice. This will return an integer, a number 1 through three. One is for rock, two is for paper, three is for scissors. The name of this function will be get computer choice. Then a function to get the user's choice. Int get user choice. We'll also return a number 1 through three. and a function with no return type. The return type will be void. This function will be named check winner. There's two parameters, an int of user choice and an int of computer choice. We have our function prototypes. Let's copy them and paste them after the main function. add a set of curly braces to each and we'll fill them in later. With these functions that return something, we'll just return zero for now just so that everything runs fine. But when we're done, these functions are going to return a number 1 through 3. We'll fill these in momentarily. Going back to our main function, we'll be working with random numbers. We need to set a seed to generate some pseudo random numbers. If we don't, when we call the random function, we'll be given the same number each time. We're going to call the srand function, then use the current time as a seed by calling the time function, passing in null, meaning no value. This function will give you the current time in seconds, and we'll use it as a seed to generate pseudo random numbers. Then we'll need a title for this game. We'll print something like this. Rock, paper, scissors. Yeah, that's good enough. Then a new line. We need two variables. An int of user choice and an int of computer choice. We're going to be assigning these right away, but instead of setting them to zero, we're going to call these functions. For the user's choice, we'll call get user choice. This will return a number between 1 and three. The user will pick what number that is and assign it to this variable. Now, with the computer's choice variable, this is where we'll generate a random number between 1 and three and return it. User choice equals get user choice. computer choice equals get computer choice. Now we'll fill in the get computer choice function. Here we'll generate a random number between 1 and 3. We can return call the rand function. This will generate a pseudo random number. But I want a number 1 through 3. We'll use the modulus operator three. This would give us a pseudo random number between 0 and two. We'll add an offset of one by enclosing this formula with a set of parenthesis. Then adding + one. This formula will give you a random number between 1 and three. One is for rock, two is for paper, three is for scissors. And then let's output it to test it. I'm just going to print using print f. I'll display an integer. New line. We will display our computer choice variable just to be sure that it's working fine before continuing. We should get a random number between one and three. Again, one is for rock, two is for paper, three is for scissors. Now, we have to get the user's choice. We're done with this get computer choice function. We can collapse it since we're done with it. We don't need it anymore. With the get user choice function, I will create a local variable just for convenience. I will set this to be int choice equals zero. A user is going to type in a number 1 through 3. We'll continue to prompt them with a while loop. A dowh loop more specifically. Do this while our choice is less than one or our choice is greater than three. In order to escape this loop, a user has to type in a number that's between 1 and three. If they're outside of this range, we continue the loop and keep on reprompting them. We'll print the following prompt. Choose an option one is for rock new line. And I will just copy this print f statement. paste it. The second option will be for paper. The third option is for scissors. Scissors. Then we'll ask the user to enter your choice colon space then scanf to get some user input. We're accepting an integer. Percent D for an integer. At the address of choice, we'll store this value. At the end, we're going to return our variable of choice, and it should be a number between 1 and three. Let's be sure that it's working. I'm just going to output our player's choice. Then I will output user choice. These should be numbers 1 through three. Rock, paper, scissors. Choose an option. I'll pick something outside of this range. Negative 1. Choose an option. 1 through 3. Four. Nope. I have to pick a number 1 through 3. I'll pick one. We picked one. The computer generated three. So, it looks like everything's working. Instead of outputting numbers, we're going to output either rock, paper, or scissors based on the numbers using switches. That's the next step. We're done with this function. we can collapse it. Rather than printing these numbers directly, we're going to use some switches. We'll start with a switch to examine the user's choice. We'll create a switch. We're examining our user choice. We'll examine this value against any matching cases. If our user's choice equals a case of one, if that's a match, then we will print the following message. You chose rock new line then break to break out of the switch. If our user's choice matches a case of two, we'll print you chose paper. Then case three is for scissors. Case three, you chose scissors. then break. Let's copy the switch. We have to do the same thing for the computer. Replace user choice with computer choice. Replace the word you in these sentences with computer. Let's be sure that it's working. Choose an option. I'll pick rock. I'll type in one. You chose rock. The computer chose scissors. I'll pick paper. I'll type in two. You chose paper. The computer chose rock. Then scissors. Three. You chose scissors. The computer chose rock. All right. Then we just have to determine a winner. After our second switch where we examine the computer's choice, we'll call our function to check winner. But there's two parameters, two arguments we have to pass in the user's choice and the computer's choice. Then we have to fill in this function. Let's start with an if statement. The if statement is going to be easy. If our user's choice is equal to our computer's choice, then it's a tie. If we pick the same thing, it's a tie. Now, here are the different win conditions for us. We'll start with a few else if statements, but we'll condense it later. Else if our user's choice is equal to one, we'll use the and logical operator. The computer's choice is equal to three. That means we pick rock and they pick scissors. We win. Then we'll print using print f. You win. We'll copy this else if statement. Else if our choice is two and the computer's choice is one, we also win. Two means we pick paper, one for the computer means that they pick rock, then we win. Else if the user's choice is three for scissors, and they pick two for paper, we win. If none of the above conditions are true, that means we lost. Then we'll print you lose. Now, we do have a lot of else if statements. We can condense it, although it makes it a little more difficult to read. But if you would like to condense this code, here's how. Let's enclose the first with a set of parenthesis. You could use the or logical operator. Copy the next two conditions in the next else if statement. Paste them and close them with a set of parenthesis. Then do the same thing with the third set. Add the or logical operator. Paste your two conditions. Enclose them within a set of parenthesis. Then we no longer need these extra else if statements. This code is more concise, but it might be a little less readable, especially for a beginner. But that's another option for you if you'd prefer to write it this way. And that should be everything with our rock, paper, scissors game. Let's run it. Rock, paper, scissors. Choose an option. I'll pick rock. You chose rock. The computer chose paper. You lose. I'll pick paper. You chose paper. Computer chose rock. You win. Hopefully I get a tie. I'll choose scissors. The computer chose scissors. It's a tie. All right, everybody. And that is a rock paper scissors game that you can write in C. Hey everybody. In this video, we're going to create a banking program in C. A user can check their balance, deposit money, withdraw money, and exit the program. This video is meant to serve as a practice project for beginners. Let's get started. All right, let's get started, everybody. Now we have a few functions to create. We'll start by declaring some function prototypes with our banking program. We need to check a balance. The return type will be void. The function name will be check balance. But we'll have to pass in a balance. This will be a floatingoint number. For a parameter, we list the data type followed by the name of the parameter balance. We'll need a function to make a deposit. Float deposit. There will be no parameters and a withdraw function will be returning a float. The name of the function will be withdraw. There will be one parameter a floating point number of balance because if we're withdrawing money, we need to know what our balance is because we don't want to withdraw more than our balance. Okay, these are the three functions we'll need. Let's copy these function prototypes. After the main function, we'll paste them. Add a set of parenthesis. We'll finish defining them later. We do have to return something for deposit and withdraw for the time being just so our program runs successfully. I'm going to return 0.0F, a floatingoint number. We'll do this for withdraw, too. We'll get back to these functions later, but we can at least use them. We'll declare the variables we'll need now that we have our functions at least declared. Let me zoom in a little. We're going to create an integer of choice. Set that equal to zero. Based on a user's choice 1 through 4, they can check their balance, deposit money, withdraw money, or exit. We're going to need a floatingoint number of balance. This will represent how much money they have in their bank account. We'll set this to be zero right away. 0.0F 0 F because it's a floatingoint number. Then when we start up this program, let's create a welcome message of some sort. We'll use print f. I'll display the following. Welcome to the bank or maybe this is an ATM or something. We're going to continue this program while choice does not equal four. Ideally, a user is going to select a choice one through four. We'll use a dowhile loop. do this code once while our choice this choice does not equal four. If user types in four, that means they want to exit the program. Within the dowhile loop, we'll create a menu. We'll need a few print f statements. Print f. I'll add a new line character to begin with. We will ask a user to select an option. Then I'll add another new line character. This will be for option one. I'll add a new line character. Option one will be to check balance. New line. Option two will be to make a deposit. Option two, deposit money. Three will be to withdraw money. Three, withdraw money and four is to exit. Four, exit. Let's create a prompt to enter your choice. New line, enter your choice. Then colon space. We'll need to use scanf to get some user input. We're accepting an integer at the address of our variable choice. We will insert a value there. Let's do a test run. This program should continue as long as our choice does not equal four. Welcome to the bank. Select an option. One is to check your balance. Two is to deposit money. Three is to withdraw money. And four is to exit. Let's start with one. We continue the loop. That's good. 2. 3. 5. If I press four, we should exit. Four. And we exit the program, which is good because we need some way to get out of this loop. While choice does not equal four, continue the loop. Now we'll need a switch. Using a switch, we'll examine our choice against any matching cases. Within the loop, we'll create a switch. We're examining our choice variable. If our choice matches a case of one, that means the user wants to check their balance. We'll call the check balance function. But we do have one parameter set up. We have to pass in our balance, whatever it currently is. Initially at zero when we start the program we will pass in our balance. Then be sure to break to break out of the switch. Now if case is two if our choice is two that means we want to make a deposit. We will call the deposit function. There's no parameters. We don't have to pass in anything. We will make a deposit. Now, the deposit function does return a floatingoint number. So, what we could say is our balance equals our balance plus our deposit because we're returning a number. If our balance is zero and we're adding, let's say, $100, our balance after making the deposit should be 100. Let's shorten this to plus equals our deposit. Then, let's break Break case three is to withdraw money. We will take our balance equals our balance minus call the withdraw function. But we do have to pass in our balance. Withdraw pass in our balance. And again we can shorten this code by saying balance minus equals the withdraw function. And that's a shortcut you can use. Again, we still have to fill in these functions. Then break case four is to exit. Case 4. We'll just print something. A goodbye message. I'll add a new line. Thank you for using the bank. and then break. Now, let's add a default case. If somebody types in something besides one through four, we'll add a default case and we'll say I'll add a new line. Invalid choice. Please select let me zoom out a little bit. One through four. New line. All right, let's do another test run. Welcome to the bank. I will check my balance. It doesn't do anything currently, though. Two to deposit, three to withdraw. I'll type in five. That's not a valid choice. Invalid choice. Please select one through four. And then four to exit. Thank you for using the bank. All right, the main body of our code is done. Now we just have to fill in the various functions. We'll start with check balance all the way down here. This one's pretty simple. We'll just write a print statement. We'll print a new line. We'll say your current balance is colon space pick unit of currency. I'll pick American dollars. We're displaying a floatingoint number. We need percent f. I'm going to display two digits after the decimal. So then we're displaying dollars and cents. Two digits after the decimal. New line. Then our balance, whatever it is. We'll receive this as an argument because we have this parameter set up. Let's do a test run. Currently, I will check my balance and it should be zero. Your current balance is $0. Now, we'll make a deposit. We'll fill in the deposit function. We will create a floatingoint number of amount. What's the amount we would like to deposit? Initially, I'll set this to be 0.0F. We need a prompt where we will ask a user to make a deposit. How much do they want to deposit new line enter amount to deposit colon space I'll add a dollar sign then scanf to get some input. We're going to accept a floatingoint number. The format specifier is percent f at the address of our amount variable. Now if somebody tries to deposit negative money, we can check that with an if statement. If our amount is less than zero, we'll just print the following message. Invalid amount. New line. We do have to return something. We're just going to return zero. We'll just print invalid amount. We're going to add zero to our balance. Else the amount is valid. And we can print something like this. Print f successfully deposited. Pick unit of currency. Percent F for floating point number. Display two digits after the decimal. new line display our amount whatever we're depositing then we will return our amount rather than 0.0F 0 F. We're going to add this amount to our balance. Return amount. Let's test these two functions. Check balance and deposit. Let's check our balance with one. Currently at zero. I'll make a deposit. Enter amount to deposit. $1001. Successfully deposited $1001. I'll check my balance again. and I have $100 and one. Let's try and deposit negative money. Two to deposit. I'll deposit 42069. Let's say invalid amount. Check my balance again. And we still have $1001. Then we just have to withdraw money. That's the last function to fill in. Within the withdraw function, we will create a local variable, a floatingoint number of amount. And I will set this to be 0.0F. Right away, we'll ask the user how much they want to withdraw. We'll add a new line. Enter amount to withdraw. And I'll add a dollar sign. Scan F to get some user input. We're accepting a floatingoint number. store this at the address of our amount variable. Now, if our amount is negative, we can't withdraw negative money. If amount is less than zero, we will print invalid amount. New line then return 0.0F. So, we don't withdraw anything. Now, else if our amount is greater than our balance, well, we can't withdraw money that we don't have. Not normally at least. If our amount is greater than our balance, then we will print insufficient funds. Then display the balance. Your balance is dollar sign percent f and display two digits after the decimal new line character. Then display our balance return 0.0F. We'll add an else statement. If these two conditions are true, we should have a valid amount. Then if that's the case, we'll print the following. successfully withdrew dollar sign percent f and we're displaying two digits after the decimal. New line we are displaying the amount. Then we will return our amount and deduct it from our balance. All right. And that should be everything. Let's run this. Welcome to the bank. Select an option. I will select five, which is invalid. Invalid choice. Please select 1 through 4. I will check my balance. $0. I'll make a deposit. I'll try and deposit negative money. 200. Invalid amount. Deposit money again. I'll deposit $1,000. Successfully deposited $1,000. I'll check my balance again. My balance is $1,000. I'll withdraw money. Enter amount to withdraw. I'll try and withdraw negative money. 420. Invalid amount. Let's try and withdraw again. I'll try and withdraw money I don't have, like one cajillion. Insufficient funds. Your balance is $1,000. Let's withdraw something that we do have. I'll just withdraw one penny. 0.01 successfully withdrew one penny. Let's check our balance again. And I have $999.99 and then I will exit four to exit. Thank you for using the bank. All right everybody, that is a banking program that you can write as an exercise in C. So yeah, today I got to talk about arrays in the C programming language. An array is a fixedsized collection of elements of the same data type. Think of it this way. An array is similar to a variable, but it can hold more than one value. It's a little more complex than that, but that's a good way of thinking of it. Here's a demonstration. I'll create an int of number. Set it equal to some number. This is a variable. Well, I could convert this to be an array after the name of the variable. Add a set of straight brackets. Enclose any values with the set of curly braces. Then you can add more than one value, but they have to be commaepparated. I'll add 20, 30, 40, 50. The name of your array should be descriptive of what it contains. Instead of number singular, I'll say numbers plural. That makes more sense because we have a couple numbers in here rather than just one. Now, if I were to print my numbers directly using print f, for example, I'll display an integer and I will display my array of numbers. Here's my result. I get some really long funky number. Normally, if you pass an array to a function, including print f, it decays into something called a pointer. But that's a future lesson. We'll run into unexpected behavior. Rather than printing the name of the array, we're going to print the elements within this array. Each value in an array is an element. To display my array at the first index, take the name of your array, add a set of straight brackets, then list an index number. For the first element in an array, you actually use zero because computers like to start with zero. If I were to print this, this would display 10. Numbers at index zero, that's 10. Index one is 20, 2 is 30, 3 is 40, 4 is 50. If I attempt to access an element that doesn't exist, well, we're out of bounds technically. You'll get some sort of garbage value. And in my example, I got 624. In C programming, you can go out of bounds when working with arrays. In most other programming languages, you'll encounter an error. Usually, some sort of index out-of-bounds exception, but we don't have that luxury in C. Be sure that when accessing elements, you don't go out of bounds. In my array, I have five indices, 0 through 4. Let's create a few more arrays. It'd be good practice for us. Let's create an array of characters named grades. These are letter grades. Let's start with a single variable, just a character of a. I'll convert this variable to be an array. After the name, add a set of straight brackets. Enclose all values within a set of curly braces. Comma separate each value A, B, C, D, and F. Let's change grade to be grades because that's more descriptive. Rather than displaying an integer, let's display a character percent C for the format specifier. Let's display grades at index zero. That's going to be an A. Index one is B, two is C, three is D, four is F. An array of characters is very similar to strings in C. When we've created strings, we would declare an array of characters such as name equals. Then within double quotes, we list a bunch of characters. These are both arrays of characters. If I were to display name at index of zero, it should give me a capital B, which it does. Index one is R 2 is O. After creating an array, you can change the values, but you have to access an index number, which is what we did here. Let's display numbers at index zero. We're displaying an integer. We'll access our array of numbers at index zero. Then change it to be 100. Set it equal to 100. That should give me 100. Let's do this with the others. I'll do a lot of copying and pasting. Index one will be 90. Two will be 80. Three is 70. Four will be 60. Then let's display all these. I'll add some new lines numbers at index zero. Then 1 2 3 4. And here are my numbers. I have 100 90 70 60. If you do need to display all the elements of an array, you could use a loop. Here's a demonstration. Let's say I would like to display my grades. I have five grades within here. I need a for loop to cycle five times. Four. Int i. Set that equal to zero. Continue as long as I is less than five. Increment I by one after each cycle. During each cycle, I'm going to print the following. We're displaying a character. This time, I'll add a new line. Then display my array of grades. Rather than putting a number here, such as 0, 1, or two, we're going to use I. After each cycle of this loop is complete, we're incrementing I by one. It'll start at zero and stop at four because that's what we set the condition to be. Here's the output. I get the letters A B C D F. Rather than using a new line, let's use a space to separate each each element. A B C D F. Let's display numbers. Numbers at index of I during each cycle. Oh, but we have to display an integer, not a character. There we go. 10 20 30 40 50. Let's display our name. And then we are displaying a character. Well, my name gets cut off because we're only looping five times. For this for loop, I have to manually change the condition. In my name, I have let's see how many characters. 1 2 3 4 5 6 7 8. I would have to manually change this for loop and that's a lot of work. But we display all the letters of my name. Let's go back to numbers. Let's say that I set the condition to be I is less than 5 and we're displaying an integer. What if I add a new number such as 60? Well, we're only cycling five times. If I need to display the full length of the array, I would manually have to change this condition to be six because there's six elements, we have 10 through 60. Wouldn't it be nice if we can calculate automatically what the size is going to be, the size of the array? Well, there's one way in which we can do that. Here's a trick. Just for the time being, I'm going to comment out this for loop. We can use the size of function to get the size of something. Whatever we pass in, I'm going to print the following two things. We're going to display an integer. I will display call the size of function. Pass in my array of numbers. The size of function will give you the size of something in bytes. My array of numbers, it takes 24 bytes. 24 bytes of memory. Now let's get the size of one of the elements. print f percent d because we're displaying an integer. Get the size of one of the elements numbers at index zero. The reason that I'm choosing zero rather than one or some other number is because what if our array only has one element? Numbers at index one would be out of bounds. So people go with zero. Then let's add some new lines. The size of my array is 24 bytes. The size of one of the elements is four bytes. If we divided the size of the array by one of the elements, that's going to give us six. Six elements. If I were to add another element, the size of my array should change, but the size of one of the elements is going to stay the same. Now, my array is 28 bytes. The size of one of the elements is still four bytes. Let's change that back. Why don't we divide the size of the array by the size of one of the elements? That's going to calculate the number of elements in my array. We'll declare a variable. Let's name it size equals call the size of function. Return the size of my array numbers divided by the size of one of the elements. numbers at element zero. In my example, size should be six. Then with our for loop, let's bring that back in. Size will be six. We'll continue as long as I is less than the size, the size of our array, the number of elements that is. And we should get the numbers 10 through 60. Let's add a few more just to be sure that it's working. Let's add 70. Yep. We have 70, then 80, and we have 80. If you would like to condense some of this code, you could copy this section where we divide the size of the array by the size of one of the elements. We'll cut that, delete this line, then we'll continue. while I is less than whatever number is returned from this equation. The code is more condensed, but it's less readable, especially for a beginner. Use whatever technique you would prefer. All right, everybody. Those are arrays. They're a fixed size collection of elements of the same data type. They're similar to variables, but they can hold more than one value. It's nice if you need a collection of something. And well, everybody, those are arrays in C. Yo, what's going on people? In this video, I'm going to show you how we can enter user input into an array. Normally, when you create an array, you list the data type followed by the array name, such as scores. We'll create some test scores. Add a set of straight brackets equals then within curly braces, you can add some values. For example, I'll just add 100, 90, 80, 70, and 60. That's good enough for now. What if we would like to fill these values in? We would need an empty array such as this. However, when declaring an array, you do need to set the size, meaning the number of elements that you want. If I'm going to insert five values into this array, I need five elements. You can set the size of an uninitialized array by adding a number between the set of square brackets. Our array contains five elements, which we're going to fill in later. But there's one thing I want to show you. Using a for loop, I'm going to display the elements. We'll need a counter int i. I'll set that equal to zero. I'll continue while I is less than the size of our array. I'll just put five here, but you could calculate the size using the size of function. Then increment i by one. During each cycle, I'm going to print each element in this loop. We're going to display an integer. separate each with a space. I'll add a space. Then print my array of scores at index of I. I've declared an array, but have not initialized it. I haven't assigned any values. Here's what's in it currently. When I run it, well, I get some garbage values in my array. I have 8 0 36 0 and then 1.9 billion or something. These values were left over from a previous program. If I access and use an array and not assign it any values, it's going to already be filled with garbage, which would lead to unexpected behavior in my program. What I would recommend is that when we declare a fixed size array, we set all the elements to zero by setting them equal to then within curly braces zero to clear them out. Now, if I were to run this program, all the elements of my array are zero, which is a lot better than those garbage values. Now, when you partially initialize an array, any unspecified elements are automatically set to zero as well. Setting one of the elements to zero would be the same thing as me typing in a bunch of zeros. Five zeros if there's five elements in this array, but you don't need to do that. C will implicitly do that. We have an array of five values and we've cleared out all the previous values just to avoid any unexpected behavior. Now we need to get some user input. Later on we'll be using a loop. I'll show you how we can add elements one by one. Let's start with a prompt. Let's say print f enter a score colon space. Then I'll use scan f. We're accepting an integer. We need a format specifier of percent d. Then store this at the address of my array of scores at index. Then pick an index. We'll start with zero. Let's give it a test run. Enter a score. I'll say 90. Here's my array. Currently, we have 90 0 0 0. We've entered an element at the index of zero. the first element. Let's do this with the others. But don't worry, we'll use a loop later to make it more simple. We're going to enter in five elements. Scores at index zero. Scores at index 1 2 3 4. Let's run this again. Enter a score. I'll say 90 80 70 60 then 50. And here's my array. We have the scores of 90, 80, 70, 60, 50. Now, we are repeating ourselves a lot. We can use a loop instead. We need a loop to cycle five times cuz there's five elements in this array. Let's use a for loop. Int i equals z continue while i is less than the size of our array. Five. Again, you could use the size of function to automatically calculate that, but that might be overkill for this lesson. I'm trying to keep it simple. We'll continue while I is less than five. Cut our prompt and scan F. Paste it within the for loop, but change the index to be I to reflect the current cycle of the loop. I is going to change during each cycle. It'll start at zero and stop at four. This will do the same thing and it's a lot less code to write. Enter a score. 90 80 70 60 50. And here's my array of numbers. We have 90 80 70 60 50. That's how to enter data into an array. When you use scanf, use the address of operator. List your array. But then you need an index number. All right, everybody. That's how to enter values into an array in C. Yo. Hey everybody. In this video, I got to explain two-dimensional arrays in C. Twodimensional arrays are also known as multi-dimensional arrays. They're an array where each element is an array. It's an array of arrays. Rather than just using one set of straight brackets, you use two. Think of it like it's two-dimensional. Here's how to create a two-dimensional array. Let's start with a one-dimensional array. Then we'll convert it to be a two-dimensional array. We'll have an array of integers named numbers. Int numbers. For an array, we need a set of straight brackets equals some values. I'll just say 1 2 3. This is a one-dimensional array. We can convert it to be a two-dimensional array by adding a set of straight brackets. Then enclose all arrays within another array. Now we can add more than one array. They each have to be commaepparated. Comma. Add a set of curly braces for another array. And then let's add another. And then we'll fill in some values. The second array will be 4 5 6. The third array will be 7 8 9. Two-dimensional arrays are great if you need a matrix or grid of data. If I were to place each of these elements on a new line, they would kind of resemble a grid with rows and columns. We have rows and columns. Two-dimensional arrays are great if you need a grid or matrix of data. One issue with this, let me compile this program. We have an error. Declaration of numbers as multi-dimensional array must have bounds for all dimensions except the first. If we have a multi-dimensional array, we have to list the number of columns. What's the maximum size for the number of columns? We'll say three. So, you do have to declare that in C. Let's print the first value. We'll use print f. We're displaying an integer. I'll add a space afterwards. Display numbers. We have two sets of straight brackets. The first set of straight brackets corresponds to the row number if this were a grid. This first array has an index of zero, then one, then two. The second set of straight brackets is for the columns 0 1 2. If I need row zero, column zero, those indices would be zero and zero. It's kind of like that game battleship. There's A1, A2, B1, B2, so on and so forth. We're going to print numbers at row 0, column 0. That's going to give me one. Let's try and print two. That would be row 0, column 1. And I'll just copy this print f statement and paste it. Numbers at row 0, column 1. That's going to give me two. Let's try and print three. That's row 0, column 2. Row zero, column 2. There we go. We have one, then two, then three. Let's go down to the next row. I'm just going to add a new line character to the end of this print f statement so we go down to the next row when displaying it. Let's copy these print f statements. Paste them. Now we're going to access the next row. The first index is going to be one rather than zero. That corresponds to the second row in our grid. And let's see what we have. We have four, five, and six. Then let's go down to the next row. Again, this row has an index of two. Row two, column 0, row 2, column 1, row 2, column 2, and we get 7 8 9. So here's our grid, our matrix of data. It's stored within a two-dimensional array. Using nested loops, we can display all the elements in this array. Here's how. Let's cut these print f statements. We're going to create a nested loop. We'll start with the outer loop. Int i equals zero. We'll continue while i is less than the number of rows that we have. We have three rows. i is less than three. Then increment i by one. I ++ for loop. I'll just add a note here that this is in charge of the rows. Then we need a nested loop for the columns. And I'll just copy this for loop. Paste it within the outer loop. This for loop is going to be in charge of the columns. But we need a different index. Let's change this to J. All right. Print f. We're displaying an integer. Separate each with a space. Display numbers. And there's two indices. numbers where our row equals I and the column equals J. Then outside of this for loop, I'm going to print a new line character. New line. This should print all the elements of our 2D array, which it does. 1 2 3 4 5 6 7 8 9. I and J will constantly be updated as we're cycling through the nested loop. We'll print the first row, go down to the next row, print the second row, go down to the next row, print the third row. Let's say we have some additional rows. I'll add 10, 11, 12. Our outer loop is in charge of the rows. We'll continue while I is less than four. Then we can print the new row that we just added with 10 11 12 to display all the elements of a two-dimensional array. You can use nested loops. Here's an exercise that we can work on. We're going to create a telephone number pad. We can keep our nested loops. We'll declare a two-dimensional array of characters. Let's call it numpad like it's a number pad. We need two sets of indices. We have to at least declare the number of columns. We'll have three columns. Equals. We need a set of curly braces to contain everything. We'll have a total of four rows. We need four arrays. And then I'll place each on a new line just for readability. Now, these are going to be characters. We'll start with a character of 1 2 3. I'll just copy these. Paste them in the next row. Then we need four five six. For the next row, 7 8 9. Then the last row is going to be an asterisk zero. Then a pound sign. I like to call it a hashtag. And here's our number pad. The name of our 2D array is going to be numpad rather than numbers. Oh, and then change this to characters rather than integers. There we go. Here's our telephone number pad. It's all arranged in rows and columns. All right, everybody. Those are two-dimensional arrays. They're an array where each element is an array. It's an array of arrays. It's useful if you need a grid or matrix of data. And well everybody, those are 2D arrays in C. Hey everybody, I felt like creating a video on arrays of strings and how they work in C. To be honest, working with strings in C is kind of a pain in the ass, but we got to learn how to deal with them. In this demonstration, let's create a string. Normally, we would declare a type of character. Let's name the string fruit equals. Then within double quotes, pick some fruit. I'll just pick an apple. A string is really just an array of characters. We can store more than one string by using a 2D array. We need two sets of indices. Within the second set of straight brackets, we need to specify the size. What's going to be the maximum number of characters in each string? Let's say 10. Then any values we enclose within a set of curly braces. Then we can commaepparate each string. I'll add a few more fruit, banana, and coconut. Let's rename fruit as fruits. And there we go. We have an array of strings. Conceptually, it's very similar to a 2D array of characters. I've already typed this out. They behave very similarly, but with a 2D array of characters, all the data is stored in contiguous blocks of memory. With an array of strings, each of these strings can be at different memory locations, but conceptually they're the same. To display the elements of an array of strings, you could use a for loop. We'll say int i equals zero. We'll continue while I is less than the number of elements within our array. Currently, there's three. There's a better way to calculate that, which we'll get to in a moment. Increment I by one. We're going to use print f to display a string. We need a format specifier of percent s for string. A new line. We're going to display our array of fruits at index of i. This should print each string in our array of strings. We have apple, banana, coconut. Or if you would prefer, we can separate each with a space. Apple, banana, coconut. With our for loop stopping condition, it would be a lot better if we were to calculate the size of the array rather than just hardcode a number here. Let's determine that. Let's create an int of size equals get the size of our array fruits. Use the size of function. Pass in our array divided by one of the elements. Size of fruits at index of zero. Then we'll have this for loop run while i is less than three. Again we get apple, banana, coconut. If we were to add new strings to our array of strings, the size will update. Let's add a pineapple. Pineapple. Then run this again. Apple, banana, coconut, pineapple, or a lemon. Apple, banana, coconut, pineapple, lemon. by calculating the size of our array. We can use that with the for loop and loop that many times. Now, here's an exercise that we can work on. I'll arrange our array so it represents rows and columns. Think of each string as a row and each character as a column. We'll use two indices to change some of the letters around. For example, let's say I would like to replace the A and apple with the E. Well, we would access our 2D array of fruits. There's two indices for the first row. That would be the first index. That would be row zero. Then the column number, column zero. Let's set that to be a character of E. Then we're going to change this last letter, the E and apple. Again, we need our 2D array. Fruits, there's two indices. We're in row 0, column, let's see, 0 1 2 3 4. Column 4. We'll set that character to be an A, a capital A. And let's see the output. There we go. We've swapped two of the letters around using indices. Apple is now EPA. Let's do this with the others for practice. We'll switch the B and banana with the last A. I'll copy these two statements. Paste them. Now we're in row one. Row one, column zero. Then row one, column 0 1 2 3 4 5. We'll replace the B and the A. Column Z is A. Column five will be B. Then we get an NAD. I think that's how you say that. Then coconut. We're in row two. Row two, column zero. That will be a T. Then row two, column, let's count it. 0 1 2 3 4 5 6. That will be a capital C. Oops, I miscounted. That should be six. Coconut is now. I thought that might be some good practice. Here's an exercise. We'll create an empty array of strings and a user is going to type in the input. This will be an exercise. A user is going to type in some names. We'll start with a single string. A string is an array of characters. We'll name this name. It's an array. An array of characters. Set it equal to I recommend initializing all string arrays. Set them equal to zero. That will effectively clear them out so there's no garbage values from a previous program. But we do have to set a size. I'll just say 25 characters for the maximum size. Now, if this is an array of strings, we'll need two indices. We need two sets of straight brackets. If this array is going to be empty, we do need to set the number of rows. Let's say that we can store three names. We have an array of strings. It can hold three names and each name has a maximum size of 25 characters. Since this is an array of strings, let's rename name as names because it can hold multiple names, not just one. Now, we're going to get some user input. Later on in this topic, we'll be using a loop. We'll start with accepting three names without using a loop just to keep it simple, but we'll use a loop later. Let's use print f for a prompt. We'll ask a user to enter a name colon space. We'll use fgets because fgets ignores any white spaces. Now, normally we would type the variable name here, but we need an index number because this is an array of strings. Names at index zero. That will be the first. We need the size of this element. Rather than just typing in 25 like this, I'm going to use the size of function. Get the size of this element names. But we also need an index number names at index zero. Then stdn for standard input. Just to remove the new line character from within the input buffer. Normally we would take our variable in this case names use a set of straight brackets. Previously in the series, we've been using string length, the string length function, the string length of names minus one and setting this equal to a null terminator character. But since this is an array of strings, we have to list the index number. With names, we'll add zero. Then when getting the string length of names, we need the index number, too, zero. And if we're working with the string length function, we do need to include the following import. include string.h. All right, let's print our name. We'll use print f. We're displaying a string. I'll add a new line. Display our array of strings at index zero. Currently, we'll just have one name filled in. Enter a name. I'll just enter Spongebob. Pick whichever name you would like. And we get Spongebob. We've entered one element into our array of strings. Let's copy the snippet of code and paste it twice, but change the indices around. Replace any instance of names index zero with one because that's the next element. Then with the next section, we'll do two names at index 2. Later on, we'll be using a loop. Don't worry. Then we'll print names at index of zero, one, then two. Now we can enter three names in. Enter a name. I'll pick Spongebob, then Patrick, Squidward. And here's our three names. Spongebob, Patrick, Squidward. Okay, now let's use a loop. We can condense a lot of this code because we're repeating ourselves. We'll cut these two blocks of code. Write a for loop to cycle three times. int i equals zero will continue while i is less than three because that's how many rows we have but we could calculate that later which we will increment i by 1. During each cycle of this loop we're going to do the following. Let's copy this whole paragraph of code then stick it within the loop. replace names where index is zero with i. I is going to increment during each cycle and that should work too and it's a lot less code to write. Enter a name. I'll enter in Spongebob Patrick then Squidward. We have Spongebob Patrick Squidward. When we print our names, let's also use a loop. We'll need another for loop. four int i equals zero. We'll continue while i is less than three because that's the amount of rows that we have. Then increment i by 1. During each cycle, we'll print names at index of i. And we can delete these print statements. Let's try that again. Enter a name. Spongebob Patrick Squidward. Spongebob, Patrick, Squidward. All right, last modification. What if we have four rows? We can fit four strings each of 25 characters. Well, we would have to hardcode this number for the four loops and change these to four. Rather than doing that, let's calculate the size of our array of strings. Let's say int rows. Let's get the size of our array. Size of names divided by one of the elements. Size of one of the elements names at index zero. The size of function returns the size in bytes. We're dividing that by the size of one of the elements 25 bytes. Replace three with rows. And that can change. Now our array of strings has four rows. We should be able to enter in four strings. I'll add Spongebob, Patrick, Squidward, and Sandy. There we go. We have Spongebob, Patrick, Squidward, Sandy. All right, everybody. Those are arrays of strings in C. They're kind of a pain in the ass, but it's an important topic. And well, everybody, those are a few ways in which you can work with an array of strings in C. Yo, what's going on everybody? In this video, we're going to be creating an interactive quiz game using C programming utilizing 2D arrays. We'll be asking some questions and displaying options. A user can type in a guess. If they get a correct guess, they get a point. Then at the end, we'll display the total points. This video is for beginners. And well, let's get started. All right, everybody. Let's create a quiz game. We'll start by creating an array of strings to hold all of our questions. This will be a 2D array of characters which we will name questions to hold our questions. If this is a 2D array, we need two sets of indices. We do have to place a size within the second set of straight brackets. We'll say that each question can hold 100 characters, but feel free to increase this. We're going to set this equal to and close all of our questions within a set of curly braces. Each question has to be commaepparated. Let's think of a question to ask for our quiz game. My quiz game is going to be astronomy related. My first question will be, what is the largest planet in the solar system? All right, we have one question currently. We'll add a few more. But now we need the options. Char options. This is a 2D array. We'll set the size to be 100 for 100 characters equals. Then within curly braces, add a string. Within the string, we'll list the different options that a user can guess. A will be Jupiter. Rather than placing each option within a new string, kind of like this, we'll say Saturn is B. Well, we would end up needing a 3D array. And that's going to get really complicated with these separate strings. Let's instead combine them and separate them with the new line character when displaying them. Option C will be Uranus. Option D will be Neptune. Let's see what these look like currently. For testing purposes, let's print questions at index zero. We're displaying a string. We're displaying questions at index zero. Here's my question. What is the largest planet in the solar system? Then we need our options. I'm going to print a string. We'll display options at index zero. options index zero. And then we need a new line. Let's see what we have currently. What is the largest planet in the solar system? We have Jupiter, Saturn, Uranus, Neptune, and it looks like I need to fix some of the spacing right there. This is all one long string, but since I'm adding new line characters between each option, think of it like it's unfolding when we display it. I'm doing it this way. So we avoid making a 3D array. Then we need an answer key. This will be a one-dimensional array of characters. Char answer key. And it's an array. Equals within curly braces. List the letter that corresponds to the correct answer. The largest planet in the solar system is a Jupiter. The first character in this array will be a capital A. Let's display the answer just to test it. Of course, we won't display it when the quiz game is done. We're displaying a character. We'll display our answer key at index zero. And that should be an A. But I do need a new line character when displaying it. Let's display a new line. What is the largest planet in the solar system? That is a Jupiter. But let's hide that because we don't want to display the answer. We were just testing it. Okay, let's add some more questions. That's our first question. Each question is going to be commaepparated. I'll place the next question on a new line just to help with readability. My next question, although feel free to pick different questions, is what is the hottest planet? Then we need another set of options. Each string is commaepparated and I'll place it on a new line for readability. A will be Mercury. New line B will be Venus. New line C will be Earth. New line D will be Mars. What is the hottest planet? That would be Venus. There's a greenhouse effect on Venus. Within our answer key, the correct character is going to be a capital B for Venus. Let's display it all to test it. Questions at index one, options at index one, answer key at index one. And this is a character. What is the hottest planet? Mercury, Venus, Earth, Mars, and that is B, Venus. Let's add another question. Again, each question is commaepparated. What planet has the most moons? We need another set of options. A will be Earth, new line. B Mars, new line. C. Jupiter. New line. D. Saturn. As of March 2025, NASA confirmed that there's 128 new moons orbiting Saturn, bringing the total to 274, but it used to be Jupiter for quite a while. As long as new moons aren't discovered after the filming of this video, Saturn currently has the most moons. Let's test our output. We're displaying questions, options, and our answer key at index two. What planet has the most moons? Earth, Mars, Jupiter, Saturn, and that is currently Saturn. Let's add one more question. This last question for me is going to be a joke, but feel free to put something serious in. I'm going to ask as a joke, is the Earth flat? I'll add another set of options. A will be yes new line. B will be no new line. C will be maybe and D will be sometimes. Again this is a joke question. The last time I checked the earth is not flat. The answer is no. B. Let's display the question, the options and the answer. Index three. Is the earth flat? Yes, no, maybe, sometimes. The answer is B. All right, we have our questions. We have our options and our answer key. Using this 2D array of questions, we're going to determine the size. I'm going to name this variable question count. It's going to be an integer. Question count. We'll get the size of our questions array divided by the size of one of its elements. Questions at index zero. This is going to return the amount of questions we have, the size of our array. Currently, it's four because we have four elements within this 2D array. We'll need a character to hold our guess. Char guess. I'll assign this a null terminator right away. then an integer of score to hold our score. I'll set that to be zero. All right, let's print a title for our quiz game. We can say something like this. Quiz game. Then we need a for loop. We need a for loop to cycle for as many questions as we have. And we've calculated that currently question count is four because there's four elements within this array. We'll write a for loop for int i set that equal to zero. We'll continue while I is less than our question count variable. Currently it's four. Increment i by one. During each cycle really we can copy these print f statements and paste them. Replace the index with i. And we are not going to display the answer. Let's do a test run. We're not accepting user input yet. We should display all the questions and the answer. Looks like I need a new line character here, too. We should display all the questions and all the answers. What is the largest planet? What is the hottest planet? What planet has the most moons? Is the Earth flat? And I think I'm just going to add a new line after each question. Let's do so here before displaying the options. H and let's add another. Okay, that's pretty good. Now we need to accept some user input within the loop. We'll create a prompt. Print f. Enter your choice colon space. We'll use scanf to get some user input. We're accepting a character, but there's going to be a new line character within the input buffer. By adding a space, we can ignore it. We'll insert a value at the address of our guess variable. I think I'm just going to add a new line character before displaying enter your choice. Quiz game. What is the largest planet in the solar system? Here are the options. We should be able to enter in one option. I'll say A. For the next question, B, C, D. Looks like our user input is working. Now, we have to determine if we have the correct answer. Within the for loop, we'll write an if statement. If our guess, our character that we type in is equal to our answer key. Where is it? There it is. Answer key at index of I. If these two characters match whatever we guess and the corresponding character within the answer key, then we will print correct. Then I'll add a new line. We'll also increment our score by one. Score plus+. At first it's zero. else. If our guess doesn't match the character within our answer key, we'll print wrong. Wrong. And we will not increment the score. Let's do a test run. What is the largest planet? I'll say A. Jupiter. Correct. What is the hottest planet? I'll get this one wrong. I'll say Earth. C. Wrong. What planet has the most moons? D. Saturn is the Earth flat. I'll say yes. A wrong. Okay, then we just have to display a final score. Outside of the for loop, we'll print something like this. I'll add a new line. Your score is we're going to insert our score. It's an integer. Out of insert the number of questions. It's also an integer. the word points. New line. We're displaying two variables. Our score and the number of questions, our question count. All right, one last thing. Let's do a test run. What is the largest planet? A B C D. Your score is two out of four points. I've gotten two questions right out of four. Now, one thing to consider, the answers are all uppercase. What if I type in some lowercase characters? A, B, C, D. Well, they're all wrong. That's because with our answer key, we've listed these characters as uppercase characters. A lowercase version is not going to equal an uppercase version. Why don't we do this? After accepting our user input, let's convert it to be uppercase. There's a function that can help us with that. But we need the following. Import. Include this file. Include C type.h. This will provide us with a function named two upper. After accepting our guess, we're going to reassign it. call the two upper function and pass in our guess. If we're passing in, let's say, a lowercase A, this is going to return an uppercase A. Now, our lowercase answers should be valid because with this line of code, we're going to convert them to be uppercase before examining them. And here's the final product. What is the largest planet in the solar system? I'll say A for Jupiter. Correct. And notice that I did type in a lowercase A and that's still correct. What is the hottest planet? B. Venus. Correct. What planet has the most moons currently? It's Saturn. D. Correct. Is the Earth flat? H. Sometimes it's flat. D. Wrong. Your score is three out of four points. All right, everybody. That is a beginner's quiz game that you can write using C. Yo, what's going on everybody? In this video, I got to explain the turnary operator using C. The turnary operator, it's represented by a question mark. It's shorthand for using if else statements. Basically, you write a condition, then add the turnary operator, a question mark. It's kind of like you're asking a question. Is this condition true? If it is true, return some value. Otherwise, return some other value. I think the best way for me to explain this is to just give you a bunch of different examples. Here's the first example. We'll have two integers. Int x will equal some number five. That's the first thing that came to mind. Int= 6. I'm also going to create a variable of max. Max will store the greater of these two numbers, either five or six. Well, we can do that with the trinary operator. But first, we need a condition. Now, you don't necessarily need a set of parenthesis to wrap your condition, but it does help with readability. The condition will be, is x greater than y? That's the it turnary operator. It's as if we're asking a question. Is this true? If it is true, we can return some value. Some value if it is true. If that condition is true, we'll return x colon. Think of it like otherwise. Return y. And then let's output the max variable and see what it contains. We're displaying an integer percent d. We will display a max. Max has a value of six. That's the greater of these two numbers. If y were seven though, well then max is seven. You follow this formula. Condition question mark some value. if that condition is true or some value if that condition is false. Here's another example. We'll need to work with booleans this time. Include the following header file standard bool.h. We'll create a boolean variable of is online. I'll set that to be true. We're going to print the following. We're displaying a string. Our condition is going to be is online. Since it's a boolean, we can just list it here. It is already true or false. Question mark the turnary operator. Is this true? We're asking a question. If it is true, we'll return a string of online. Otherwise, we'll return a string of offline. Are we online? Currently, that's true. So, we output online. If this were false, then we'll output offline. Here's another example. We'll determine if a number is even or odd. We'll need a number int number equals I'll say 8. Using the turnary operator, we'll output if this number is even or odd. We'll use print f. We're displaying two values this time. Our number, it's an integer. the word is then a string. Here we'll insert our number. Then we'll use the trinary operator. This will be our condition. Is our number divisible by two? Number modulus 2. The modulus operator gives you the remainder of any division. If a number divides by two evenly, the remainder is zero. Is this equal to zero? Then the turnary operator, we're asking a question. If number divides by two evenly, we'll output even. Colon will output odd if it's false. Number is currently eight. 8 is even. If this were an odd number like 9, well then 9 is odd. Here's another example. We'll create a variable of age. Set it equal to some age. We'll use a condition to check to see if somebody is 18 or older. We'll use print f. We'll display a string. Then we need a condition. Is our age greater than 18? Question mark. Is that true? If it is, return a string of adult. Otherwise, return a string of child. Currently, my age is 21. That will output adult. If this were 12, this would output child. All right, last example. The last example involves time. We'll display A.M. or P.M. if the hours is 12 or greater. We'll need a few things. int hours. This will be in military time. I'll set hours to be 11 and int minutes. I'll set minutes to be 30. We'll print the time. We're displaying an integer for the hours, an integer for the minutes, and then a string for the meridian. The meridium is either A.M. or P.M. We have to insert three values. We have hours, minutes, then the meridium. But here we'll use the turnary operator. We start with a condition. The condition will be is hours less than 12. Question mark turnary operator. If that's true, we're going to output A.M. Otherwise, output P.M. because after 12 hours, it's P.M. All right, let's see what we have currently. We do have to do a little bit of formatting, though. Hours is 11, minutes is 30, our meridium is A.M. I'm going to add some zero padding. Let's say that minutes is just three, 3 minutes after 11. We would like to add some zero padding with these format specifiers. I'll add two zeros for padding. 02 following the percent sign. And that's better. Then we just have to add a colon here between the hours and the minutes. Replace that space with a colon. That's a lot better. Now, let's set ours to be 12. It's 12:30. Well, the time will output 12:30 p.m. Hey, this is Bro from the future. I haven't talked about pointers yet in this series, but what you could do is create a pointer that points to the first character in the strings of AM or PM, then display it. Here's how. We'll create a pointer. The data type will be char. Use an asterisk for a pointer. We'll name this pointer meridian equals. We'll cut our formula for the turnary operator and paste it. Our meridium is either going to point to the string of am or pm. Then we will display our meridium. And there we go. I think that's a lot more readable, too. All right, everybody. That is the trinary operator. It's shorthand for using if else statements. You have a condition, then you use the trinary operator like you're asking a question. Is it true? If so, return some value. If not, return some other value. It's a pretty useful shortcut. And well everybody, that is the turnary operator in C. Hey, what's going on everybody? In this video, I got to explain typed defaf in C. Typ is a reserved keyword. It gives an existing data type a sort of nickname. By using typed defaf, it helps simplify complex types and improves code readability. You type defaf an existing data type and then a new name you want to give it. Here's a demonstration. Let's create three integers. int x equals some number three. That's the first thing that came to mind. int y = 4. Int z= x + y. And then I'll output z using print f. Print f. I'm printing an integer. I will output whatever Z is. Z will equal seven. Well, what if I told you that we can rename int and give it a nickname? That's maybe a little more readable. We would have to use that type defaf keyword. And we'll do so outside of the main function. Type typed defaf an existing data type, then a nickname. Type defaf, an existing data type. In this case, int. Since we're working with integers, let's rename ins as numbers number. And then we can use this nickname number x number y number z. And this works the same number z is seven. Now I would still stick to ins because that still is readable, but this is a demonstration that you can rename data types to something else. Here's another example. We're going to create our own strings. Normally in C to create a string, you need a character array. Charame, it's an array. Then assign it some characters. Type in your first name and last name. Then I will output my name using print f. Print f. We're displaying a string. Percent s. I will display my name. And this will output whatever your name is, your first name and last name. Now in many other programming languages to create a string the data type is string usually with a capital or lowercase s then a variable name without that set of straight brackets but we're going to recreate that. We need that keyword of type def type defaf an existing data type char. The nickname we'll give it is string but we do have to specify a size and see. I'll say 50 characters. Then our new data type is a string. And you don't need that set of straight brackets. And this will work the same. However, in C we've set a maximum size of 50. We'll allocate 50 bytes to display each of these strings. If you're familiar with pointers, you could use a pointer instead. Then you don't have to specify a size, but that's a more advanced topic. We'll say that each string has a maximum size of 50 bytes, 50 characters, just to keep it simple. Now, we'll create a set of initials. Normally, this is a character array. We'll say user 1. This is an array. Equals use the initials for your first name and last name. And then we'll display our initials stored in a character array of user 1. My initials are BC for my YouTube channel. Let's do this a few more times. User 2, user 3, user 4. User 2's initials will be Spongebob Squarepants, SS, Patrick Star, PS, Squidward Tentacles, ST. Then we'll have a few different users. We'll need some new line characters. User one, user two, user three, user four. And here are the initials. Let's use type defaf to give a name to an array of characters that can hold two letters, two characters. Again, type defaf char. Since we're working with characters, let's give these a nickname of initials. Now, the size is actually going to be three because you need that null terminator at the end. Two characters and a null terminator technically. All right. Now, we can use this nickname initials. Initials, initials, initials. And you can delete the straight brackets. And this will work the same. We have our set of initials. All right, everybody. That's the type defev keyword. It's reserved keyword that gives an existing data type a nickname. It helps simplify complex types and improves code readability. You type typed defaf, an existing data type, and then a new name, a nickname so to say. And well everybody, that is the type defaf keyword in C. Hey, uh, what's going on everybody? In this video, I'm going to explain enums in C. Enums, it's short for enumerations. Enums are userdefined data types. They consist of a set, a set of named integer constants. You have a constant and then a number associated with that constant. Here's how we can use enums in C. Outside of the main function, we'll type enum to create a set of enums. Then we need a tag name. It's kind of like a data type. Our tag name will be day. What day is it? Sunday, Monday, Tuesday. We need a set of curly braces. Then end the set with a semicolon. Now here we'll create constants. And in C all constants should all be uppercase letters. We'll say Sunday. Be sure to comma separate each constant too. We'll go through the days of the week. Monday, Tuesday, Wednesday, Thursday, Friday, Saturday. You could assign a value to each if you would like. You could say Sunday equals 1, Monday equals 2. If you don't, the first constant has a value of zero. Then the value of the next constant is incremented by 1. Sunday is zero, Monday is 1, Tuesday is 2, Wednesday is three, so on and so forth with the rest. Let's test it. We're going to create a variable, but the data type is going to be day. You'll have to type enum, the data type of day, then a variable name. We'll say today equals. Now, you can use one of these constants. We'll say today is Sunday, all capital letters. And then we'll print the variable today and see what it is. I will display an integer. We will display today. This is going to print a number. Sunday has a value of zero. We can treat it as if it was the number zero. Let's change today to be Monday. Well, today has a value of one. Tuesday is two. Two for Tuesday. And Saturday should be Looks like I misspelled Saturday. Saturday should be, let's see, 0 1 2 3 4 5 6. I bet it's six. Yes, it is. Saturday has a value of six. Now, you could assign numbers to these, too. The first constant will normally start at zero. I'll set Sunday to be one instead because it's the first day of the week. Monday is two. Tuesday is three. Wednesday is four. And I'll place some of these on a new line for readability. Thursday is 5. Friday is 6. Saturday is 7. If we were to print Saturday, it should be seven, which it is. Then if we go back to Sunday, it should be one. And Sunday is one. Enums are a set a set of a constant and a value. Now you could combine this with the type defaf keyword precede enum with typed defaf type t type defaf enum and move our tag name to the end after the set of curly braces. The nice thing about writing it this way is that throughout the program preceding the data type of your enum, you don't need to use that enum keyword again. This will work the same and it's more readable. Sunday is still one. Here's a few more things we can do with enums. We're going to write an if statement. Let me zoom in. If today is equal to Sunday or today is equal to Saturday, that means it's the weekend where we will print the following. It's the weekend. else it's a weekday print f we will print it's a weekday today is Sunday that means it's the weekend if it were Saturday well it's still the weekend if it were Tuesday well it's a weekday Okay, by using enums, this is fairly readable for a human. It's a lot easier for us programmers to understand rather than saying if today equals 1 or today equals 6. A computer understands this, but not humans. Sunday and Saturday make a lot of sense to me. Here's another example of enums. We'll create a set of enums for a status. enum status curly braces semicolon at the end. We'll have three constants for a status success, failure, or pending. Perhaps we're trying to connect to something. If we don't assign a value, success will be zero, failure is one, pending is two. Let's create a variable where the type is status. Again, we need that enum keyword if we're not using typed defev. Enum status. I'll create a variable name of just status equals success failure or pending. We'll say success. Now, if we use the type defaf keyword, we don't need to list enum right here. Type def enum then move the data type to the end. And we can eliminate this keyword of enum. So what we'll do this time is pass this variable to a function. Let's define a function called connect status. void connect status parenthesis curly braces. We're going to be passing in our status. We have to call the function and pass in our variable of status. We need to set up a matching set of parameters. But we need the data type of what we're receiving. Well, the data type is status. Status. Then the parameter name status. Do pay attention to the capitalization. Once we receive this value, let's examine it with the switch. We'll write a switch and we are examining our status in case of success then we will print connection was successful new line then be sure to break to break out of a switch in case of failure let's do some copying and pasting case failure. We're going to print could not connect. Could not connect. In case of pending again we'll do some copying and pasting. Case pending we'll say connecting dot dot dot. And one last thing that we need, since we're defining a function after the main function, we have to add a function prototype. Copy the data type, the name of the function, and the parameters. After our set of enums, we'll paste that function prototype. All right, let's test this. Whoops, looks like I made a spelling mistake. Okay, we're ready to begin. Our status is set to success. Connection was successful. Let's set it to be failure could not connect then pending pending connecting dot dot dot. All right everybody those are enums. They're a userdefined data type. They consist of a set a set of named integer constants. Each constant has a value associated with it. One of the major benefits is that you can replace numbers with readable names which makes coding a lot easier. And well everybody, those are enums in C. Well, hello again everybody. Today I'm talking about strrus in C. A strruct is a custom container. It holds multiple pieces of related information. They're very similar to objects in other programming languages. It's basically C's version of object-oriented programming. Here's a demonstration of strrus. Outside of the main function, we're going to define a strct. We'll type strrruct, then a tag name. We'll create a strruct of student curly braces, then a semicolon at the end. Student is the tag name. It's kind of like a data type. Think of a strct like a blueprint. We're designing what all students are going to have. We'll say in this example that all students will have a character array of name char name. It's an array. I'll set the size to be 50 characters long. These are members. We're saying that all students that we create will have a variable of name, but we're not going to be assigning them. We'll do so within the main function. What else should students have? They should have an int of age. How old are they? a float of GPA for their grade point average. Let's also add a member to see if a student is full-time or not. We'll be working with booleans. We'll need to include this header file. Include stdbool.h. Let's add a boolean member of is fulltime. Are they a full-time student? All right. And that's a strruct. It's very similar to object-oriented programming in other languages. Now let's create a strruct of student. We're going to do so within the main function. We need that strruct keyword strruct the tag name. Think of it like the data type student. Then a variable name. We'll just say student one equals. We're going to assign all these values. That's if you want to initialize them right away. Kind of like an array. The first element will be a name. I'll just pick Spongebob. Then an age. We'll say Spongebob is 30. Then a GPA. Spongebob's GPA will be 2.5. Is Spongebob a full-time student? That's true. He goes to boating school. We have a strruct of student one. To cut down on some of the repetition, you could use the type defaf keyword when defining a strruct. If we were to proceed strct with type defaf, we can move the tag name to the end. Anytime we use this data type of student, we don't also need to say strruct. That will cut down on some of the repetition going forward. Let's print some of student one's members. Name, age, GPA, and is full-time. I'll print the following. Print f. Let's start with a string. a new line. Take the name of your student. In this case, student one. To access a member of a strruct, you use dot. The dot is the member access operator. If you would like to access a member within a strruct, you follow the name of the strruct with a dot. We'll access the name member of student one and print it. That's going to output the name of Spongebob. Then, let's get the age. Let's do some copying and pasting. We're displaying an integer. We need a format specifier of percent d student one. And the age of Spongebob is 30. Let's get the GPA. Student one.GPA. And this is a floatingoint number. Student one.GPA. Spongebob's GPA is 2.5. And you can format the output if you would like. Actually, let's do that. We'll display two digits after the decimal. That looks a lot better. Spongebob's GPA is 2.50. Is Spongebob a full-time student? There's a couple different ways that we can do this. I'm going to print a decimal to begin with. We'll display student one is full time. If you display a boolean variable as an integer, it will be zero or one. Spongebob is a full-time student. That's one. But if this were false, then we're going to output zero. We could use this with the itinary operator. Let's display a string percent s. Does this condition evaluate to be true? We'll use the itinary operator. Question mark. Is that true? If so, return yes. If Spongebob is a full-time student, otherwise return no. Spongebob is not currently a full-time student. We set that to be false. That is no. If we set this value to be true, well then Spongebob is a full-time student. All right, let's create a few more strcts. We can follow a similar formula. We type the data type student student 2 equals. Then we can add a new set of values. Let's say Patrick for the name. Patrick will be 36. Patrick's GPA is only 1.0. Patrick is not a full-time student. He watches a lot of TV. Let's display some of student 2's members. Student 2.name. Student 2. Student 2.G. GPA student 2 is full-time. And here's the output. We have Patrick. Patrick is 36. Patrick's GPA is 1.0. Patrick is not a full-time student. We're outputting no. Let's create another student three. Student three will be Squidward. Squidward seems like he's about 48 or so. Squidward has a GPA of 3.2. Student 3.name. Student 3. Student 3.GPA. Student 3. And we have Squidward 48 3.2 GPA not a full-time student. Now, here's something to consider. What if we create a strct but don't assign it any values? student student 4 and we're just going to declare it but not assign any values. What if we were to access these members of this strct? Here's what happens. Well, we get undefined behavior. When we declare a strruct, we're using up some blocks in memory, but we've never cleared out what's in those memory blocks from a previous program. This is some leftover data from a different program. Whatever used that memory last. If we declare a strct, we should clear out all that memory. We can say student 4 equals then within a set of curly braces set all the values to zero to reset it. And there we go. And all the values are effectively zero. It's all cleared out. If you declare a strct but would like to assign values later, here's how. We will manually assign all of the members of student 4 after we've initialized it. To assign the name, since it's a string, an array of characters, this is one function that we can use. String copy str CPY parenthesis. We'll assign student 4's name member student4.name. We'll assign it Sandy. Then let's output it. We do need to include the following import because I forgot to do that. String.h to work with string functions. There we go. Student 4's name is Sandy. You can also use string and copy to safely copy a certain amount of characters. You could say five since name is five characters long, but I haven't talked about string functions yet. Let's assign student 4's age. We'll take the name of the strct. Student 4 age. Set it equal to Sandy. Seems like she's about 27 or so. And then we'll output her age. Name is Sandy. Age is 27. Let's assign her GPA. student4.GPA. She has a perfect 4.0 because she's smart. She's a scientist. Sandy's GPA is a 4.0. And we'll say that she's a student. Student 4 is fulltime. She is a full-time student. Sandy is a full-time student. That's true. And we're outputting yes. That's how we can assign various members of a strruct after we've initialized it. What you could do as well is that you can pass a strct to a function. We're going to change this program around. We'll create a function that will display the info of every student. Every student that we pass to the function. Here's how we can do that. After our main function, we will declare another function. The return type is void. We're not returning anything. Let's name this function print student. We have one parameter to set up. We're passing in strrus. The strruct has a data type of student. Student is the data type. Then we need a name for this parameter. Let's rename any student that we pass in just as student. Let's cut our print f statements and then paste them within the print student function. We're printing students name, students age, students GPA, and student is full-time. Then afterwards, I'm just going to add another print f statement. And we'll just print a new line character just to keep them all separated. Oh, and then we do need to add a function prototype. So, copy the return type, the name of the function, and the parameters after our strct, but before the main function, paste that function prototype. There we go. We're going to call our function of print student and then pass in our first student, student one. Here we go. We have Spongebob 302.5. Fulltime is set to yes. Then let's print student two. We'll pass in student two here. Now we have Patrick's data. Patrick 36 1.0. No. We'll do this with both Squidward and Sandy. Student three and student four. Student three, student four. Here's Squidward's data. And here's Sandy's data. And then let's change the output a little bit. I'll format the output slightly. We'll say name colon space age colon space GPA colon space then full dash time colon space. Oh yeah, that looks pretty good. All right, everybody. Those are strrus. Strus are custom containers that hold multiple pieces of related information. It's very similar to object-oriented programming in other languages. And well everybody, those are strrus in C. Hey y, in this video I'm going to explain how arrays of strrus work in C. An array of strrus is an array where each element contains a strct, a strct data structure. If you have a lot of strcts to work with and they're all of the same type, you can stick them within an array. By doing so, it helps you organize and group together related data. Here's an example. The type will be cars cuz I like cars. To create a strct, we'll type strruct. Then a tag name for the strruct. We'll say car curly braces semicolon. Let's say that all cars have the following members. a character array of model. I'll set that to be a max size of 25 characters. An int of year for the year and an int of price. All right, let's create a few car strrus. To create a car strruct, you would have to type strruct car, then a name for the strruct. We could say car one. If we use the type defaf keyword, we don't have to preede each instance of car with strruct that keyword. We'll say typed defaf strruct then move the tag name to the end car. And then we don't need to precede car with the word strruct. That's just going to make it convenient for us. All right, let's initialize the members of car one. Pick a car that you like. I like Mustangs. I'll set this to be a Mustang for the model. A year, I'll say 2025. Then a price 32,000 for $32,000. Let's create a few more cars. Car car 2 equals then we'll initialize the members. For my second car, I'll pick a Corvette. The year will be 2026 and the price will be $68,000. It's really expensive. Then a third car. Car car 3 equals I'll pick a Challenger. The year will be 2024. The price will be $29,000. Okay, we have a few strrus. They're not within an array yet. Let's display their members. We can use print f for this. Print f. We'll display the model first, which is a string. We need a format specifier of percent s. Then the year, that's an integer. Then the price, it's an integer, but I'll precede it with the dollar sign if we're working with American dollars. Then we will access car 1's model. Car 1 dom car 1.ear car 1. Then I'll add a new line. Let's see what we have currently. All right, here's car one. It's a car strct. Here's the model, the year, and the price. Those members. Then let's display car 2 and car 3. We can do some copying and pasting. For the second print statement, let's replace car 1 with car 2 and the third print statement with car 3. All right, here's our car strrus. We have three car strus each with a model, a year, and a price. Now, what we could do is store all of these car strrus within an array for convenience and better organization. Here's how. When we declare an array, we have to list the data type first. While we're storing car strrus, the data type is car. Then, we need a name for this array. We'll say cars plural. then a set of straight brackets because it's an array. Equals. With arrays, we enclose all elements with a set of curly braces. For each strct, we're going to cut everything within the set of curly braces, including the curly braces. Then paste it within our array. This would be one element. Each element is going to be commaepparated. So, we'll finish doing some copying and pasting. And just for readability, I'll put these each on a new line. And we can delete our previous declarations. There we go. It's kind of similar to a 2D array. However, if I were to run this, well, car 1, car 2, and car 3 no longer exist. To access these str, we're going to access them by an index using a for loop. Here's how. For our for loop, we'll need to calculate the number of elements we have. We'll say int number equals call the size of function pass in array of strrus divided by one of the elements size of cars at index zero. Now we're going to create a for loop. Int i equals z. We'll continue while i is less than the number of elements we have. I is less than number. In this case, we have three elements. Number is going to be three for this example. Increment i by one. We can cut one of these print f statements and paste it within the for loop. And then delete them. We no longer need them. replace any instance of car 1 with the name of our array at a given index number. Cars at index i. So let's go ahead and replace all these. And this should work. We're accessing our array by an index number. If we access cars at index i and get the model, well during the first cycle, we're accessing this array of cars index zero. That's the first element. Return the model. Then we're doing that with the year, then the price. Then during the next cycle, we go down to the next element because we're incrementing i. And let's try this. This should work. And there we go. Here's our array of strrus. We have car 1, car 2, and car 3. All right, everybody. That is an array of strrus in C. It's where you have an array and each element is a strct. It helps keep your code organized and you can group together related data. And well everybody, that's how array of strcts work in C. Hey uh what's going on everybody? We have a super important topic to discuss today and that is pointers in C. For a beginner, pointers are very intimidating. A pointer, it's a variable. It stores the memory address of another variable. One of the major benefits of pointers, they help you to avoid wasting memory by allowing you to pass the address of a large data structure instead of copying the entire data and passing it. For a real life example, let's say I would like to have a pizza party and I'd like to invite all my friends and there's a lot of pizza. There's like 20 pizzas. Instead of me going to each of my friends houses and handing them pizza, I could instead go to each of their houses, knock on the door, then tell them where I live so then they can get pizza. It's a lot less work for me this way because I don't have to carry 20 pizzas around. I'm telling all of my friends what my address is. Pointers work in a similar way. We're working with the address. We're passing the address of something so that other parts of our program know where to find that data. Here's how to create a pointer. Let's say we have an integer of age. Set it equal to some age. Our variable of age stores the number 25. This variable has a memory address. Let's take a look at it. To print the address of this variable, we'll use print f. The format specifier is going to be percent p. Rather than just type the variable name here, we're going to use the address of operator, the amperand. This is going to return the memory address of this variable. This is where my variable age is located in memory. It's a hexodimal address. It's an address like 123 fake street if it was a real life address. How a pointer works is that we're going to store this address as a value in another variable, a separate variable. Here's how. To create a pointer that points to another variable or other data structure, we're going to keep the data type the same. This will be an integer. We're going to use an asterisk to create a pointer. This is known as the dreference operator. We're telling the C compiler we're going to be storing a pointer by using the dreference operator when declaring a variable. Then a common convention for creating pointers is to use a lowercase P. Then the name of the variable we're pointing to. In this case, age. But we'll change the capitalization around. A will be capital cuz it's the first letter. GE for age. Equals. Then we're going to get the memory address of our variable age. We'll use the address of operator age. There we go. We have created a pointer. Now with the asterisk can be a suffix after the data type or a prefix before the variable name. Both work. All right, let's take a look at these. Let's see if the address of our age variable is equal to the value of our pointer to age. Let's test it. We're going to use percent p for the format specifier. Let's display the address of our variable age and then percent p we will display whatever values within our pointer of age and they should be the same addresses. Oops. And I need a new line character. There we go. We're given the same value. our address of our variable age. It's the same as the value stored within our pointer to age. If we ever need to do any sort of work on this variable, we could pass in this pointer. How can we pass this pointer to a function? Now, here's one thing to consider. We're going to create a function that will increment our age. We'll call it the birthday function. void birthday. We need to accept an integer of age. int age. Now, if I were to say age++, well, this isn't going to work as you would think, we're going to call our function, our birthday function, so we can have a birthday. Then pass in our variable of age. Once we receive our age, we'll increment age by one. And then let's display it within the main function. print f we'll say you are percent d for an integer years old then we will display our age and then we need a function prototype we'll cut that and then paste it before the main function now this isn't going to work how you think my age is still 25 well what the heck we had a birthday right we should be 26 now with function Funs in C, they're passed by value. Pass by value. When we pass a value to a function, we actually make a copy of that value. When we increment that value, we're not changing the original the original variable. We're changing the copy of it. What we need to do is pass by reference. If we need to change this variable within another function, to pass by reference, we can pass in a pointer. Rather than passing in the original age, we're going to pass in a pointer to our age variable. PH. It's our pointer to our age variable. But we do have to set up the parameters, too. Expected integer but argument is of type pointer to an integer. If we're passing in a pointer, a parameter also needs to accept a pointer. You'll add that asterisk. And then be sure to do that within the function prototype, too. Again, the asterisk can be a suffix for the data type or a prefix for the parameter. Both work. We're accepting a pointer to an integer. But there's one last thing. We're still 25 years old. I set the parameter to be age. What we ended up doing is incrementing the address of age. We need to dreference it by using the dreference operator. the dreference operator. It's going to return the value at a given address. With our age, we're going to use the dreference operator. And in this case, we need to enclose it within a set of parenthesis. dreference age and return the value. This will give me the value of 25. And then we're going to increment it by one. And this should output 26. You are 26 years old. The reason that I have our age within parenthesis is that there's operator precedence in C. If I were to write this line this way, we would end up incrementing our memory address by one because we would increment first and then dreference. By adding a set of parenthesis, we're forcing operator precedence. Dreference this variable first and then increment it. So, what might help you visually with pointers is that think of the asterisk as a star- shaped key. It'll unlock a memory address and return the value to you like you're using a key to open a box. That's a visual that helps me remember how pointers work. Another thing you can do with pointers too is that if we have a function that accepts a pointer, we don't necessarily need to declare a pointer then pass it in. We could just pass in a memory address like this. We'll pass in the address to age and then cut this line. And this would work the same, too. You are 26 years old. That still works. A pointer is just an address to another variable or other data structure. All our function wants is an address to an integer. It doesn't care how it gets it. All right, everybody. That's an introduction to pointers. They're a variable that stores the memory address of another variable. It helps you avoid wasting memory by allowing you to pass in the address of a large data structure instead of copying over the entire data. And well everybody, that is an introduction to pointers in C. Hello again everybody. In this video, I'm going to show you how we can create and write to a file using C. To work with files, there's a built-in strruct of file provided by the standard input output header file. The data type is going to be file all caps. What we'll be doing is creating a pointer to a file strruct. To create a pointer, we'll use the dreference operator. Then we need a name for this file. A common convention is to type lowercase p and then a variable name. We'll say file. Now this will equal here. We'll attempt to create a file. We'll call a function of fop file open. The first argument is a file path. It can be a relative file path or an absolute file path. We'll stick with the relative file path just because it's more simple, but later on we'll use an absolute file path. What would you like your file to be named? Let's say output. And this will be a plain text file. TXT. Now the second argument that you need to pass in is a mode. W is for write mode. R is for read mode. We're going to be writing a file. We need W. Now when you open a file, it is good practice to close your file when you're done with it. We'll do so at the end of our program. We can use f close. This is a function. Then pass in our pointer to our file strruct. You do want to be sure that you're closing any files that you open. You want to free those resources when you're done using them. Or in case if you forget to close your file, you might not be able to edit it in a different program because another program might see that something is currently editing it. When you open a file, just be sure to close it. It is easy to forget though. Just as a habit, whenever I open something, I'll also write the code to close it at the end, just so I don't forget to do that later. Now with the fop function, if we're unable to create and open a file, this function is going to return a value of null, but we can use that. Let's check if the pointer to our file is directly equal to null. That means we couldn't open the file. So let's print something. Let's print error opening file. To exit a program prematurely, you can return a value that's not zero. Let's return one. This serves as an exit code. If we reach the end of the program and we return zero, that means there were no errors. If we return something that's not zero, that means there was an error. So, just to test this, I'm going to cut our file name and just see what happens. Error opening file. Okay, that's a good sign. Now, let's put that file path back in. output.txt. And nothing appears to happen, which is good. And we end up creating a file output.txt, but there's no text. That's a good sign. But now we need to write some text to this file. Here's how. Let's say we have an array of characters. Some text. We have a character array named text equals. And this will be a string. Think of something to write. Booty. Booty. Booty. I'll add a new line. Rocking everywhere. We're going to take our text and write it to this file. Assuming we pass the check where our pointer does not equal null, this is where we'll write some text. Rather than using just print f to print something, we're going to use f print f. File print f. And there's three arguments. We need a pointer to a file, a format specifier of what we're trying to write. We're going to write a string percent s and then our text which we just named text right here. This part isn't necessary. Let's print a confirmation message. We'll just say file was written successfully. And then be sure we're closing our file at the end. All right, let's delete our current text file and run this again. File was written successfully. And let's take a look at this file. There we go. Here's my poem. Booty booty booty rocking everywhere. The file should appear in the same folder or around the same folder as your executable. Let's say that when I generate this file, I would like to do so on my desktop. Well, I can use an absolute file path, but I need to know what that is. I'm going to click on one of these folders, go to properties, and cut this location. Preceding the name of the file, we're going to paste that file path. You'll likely need to use double backslashes, otherwise C thinks you're using an escape sequence. Let's see if we create and place this file on my desktop. File was written successfully. And let's take a look to see if it's there. Here it is. It says booty booty booty rocking everywhere. All right, everybody. That's how to create and write a file using C. Hello everybody. In this video, I'm going to show you how we can read a file using C. To read a file, we'll need a file to work with. Within our project folder, let's create a new file. I'll name this file input.txt. Then think of something to write. I'll write a poem. Here's my poem. Roses are red. Violets are blue. Booty, booty, booty, rocking everywhere. Let's be sure to save it. You can use Ctrl S to save it automatically. Now, we're going to read this file. Here's how. We'll define a pointer to where this file is located. This is a strct. The data type is file all caps. Then, let's think of a pointer name. Use the dreference operator. We'll say lowerase P then the word file. Now this is going to equal we'll call the f open function. We have to pass in a file path and a mode. The file path can be a relative file path or an absolute file path. We'll stick with the relative file path at least in the beginning just because this file is within the same project folder. Here you'll list the name of the file. The name of my file is input.txt. Be sure to get the extension too. Then we need a mode. We'll use R for read. Whereas in the last video, we used W for write. We need R this time. Now, when we open a resource, such as opening a file, I recommend we write the code to close it right away, just so we don't forget to do it later. When we open a file, when we're done with it, we'll call f close to close it. We will close the pointer to the file. The reason that we're closing this file is because you don't want to leave any resources open when your program is finished. Now, in case for some reason we can't open this file or locate it, this function will return a value of null and we can use that. If the pointer to our file is null, then we'll print could not open file. We'll use print f could not open file. At the end of this if statement, we'll return an exit code of one. We're telling the C compiler that there was an error. If you reach the end of the program and you return zero, that means there were no errors. If you return one, that means there was an error. And let's test this. Let's say I get the file extension wrong. Instead of txt, this will be txp. Well, we get this error message that we wrote could not open file. But if we could locate this file input.txt, well, then we don't get that error message, which is good. Now, another thing that we'll need is a buffer. A buffer is like a waiting room, and it temporarily stores data for us to read. In this case, we'll create a character array of buffer, but we do need to specify a size. The size will be in bytes. A good general purpose size is 1,24 bytes, 1 kilob. And then just to clear it, I'm going to initialize it to zero. Just in case we accidentally read it before assigning it, we won't get unexpected behavior. Now, the reason that we need a buffer, it's going to temporarily store data. For a real life example, if we didn't have a buffer, that'd be like us reading a book one word at a time, then going across the room to write down that word. If we have a buffer, it would be as if we're reading a whole paragraph from a book, then going across the room to write that paragraph down. It'll make your program more efficient. But if your buffer is too big, you'll be using a lot of wasted memory. 1,024 bytes is a good general purpose size, but you can adjust this depending on what you're reading. All right. Now, here's how we can read the text from a file. One technique is to use a while loop. Within the condition of the while loop, we'll use the fgets function. Once we run out of text, fgets will return a value of null. And we can check for that while the value returned by fgets does not equal null. But there's a few things we need to pass into the fgets function. We need our buffer. That's where we'll be storing the text from the file. Then the size of the buffer, which is 1,024 bytes. But rather than manually coding a number here, I recommend using the size of function. Return the size of our buffer just in case we decide to change it later. We don't have to manually do it here, too. This will adjust it automatically. Then we need a pointer to our file. All right. Now during each cycle of this while loop, we'll print whatever's within our buffer. Print f. We're displaying a string. We will display what's within our buffer. And that's it. Let's run this. Here's my poem. Roses are red, violets are blue, booty, booty, booty, rocking everywhere. Let's say that this file is someplace else, maybe on your desktop. Well, we can use an absolute file path. Here's how. Let's take our file. Let's pretend this wasn't here. Let's take our file and move it to our desktop. Then we just need the file path. You can rightclick it, go to properties, then copy this location, and we can delete this. With F open, we're going to paste that file path preceding the file name. You'll likely need to use double backslashes. All right. And we should be able to read that file, too. Roses are red, violets are blue. Booty booty booty. Rocking everywhere. All right, everybody. That is how to read a file using C. Yo, what's going on everybody? In this video, I'm going to explain the Malo function in C. Malo is a function. It's short for memory allocation. It's a function in C that dynamically allocates a specified number of bytes in memory. Here's why you might want to use this function. The arrays that we've been creating are fixed in size. Let's say we would like to enter in some test scores, some grades. Well, to create a static array, we would say char. Then an array name, we could say grades. Then we have to specify a size. For example, five. I would like to enter in five grades. I have five test scores. Then I'll go ahead and just initialize these all to zero. So this works if we have a fixed size. Well, what if we don't know the number of elements we need until after the program is running where a user is going to type in how many grades they have. What we're going to do is actually return a pointer from the malo function. We will have a pointer to an array-like data structure and that's going to be returned by the malo function. Now with the Malo function, we have to pass in a number of bytes that we would like to reserve in memory. For example, I would like 100 bytes. I would pass in 100 here. Rather than hard- coding a number, we're going to ask a user how many elements they want to enter in. Then we'll multiply it by the size of a character. Here's how we can do that. We'll create a variable of number. Then a prompt. print f enter the number of grades and then we'll use scan f to get some user input. We're accepting an integer. We need a format specifier of percent d. Then store this at the address of our number variable. Let's say we would like to enter in six grades. We have six test scores. We're going to take our number that the user types in and multiply it by the size of what we're storing. Well, we're storing characters. We will multiply this by use the size of function. Pass in the data type of char. Now, normally a char is one bite. If we have six test scores, each test score is a character. Well, this would use up six bytes. But if this were integers, in most systems, an integer is four bytes. If we need six scores * 4, that would be 24 bytes. Basically, we're going to calculate how much size we need. How much space in memory are we going to reserve. Now, the memory that we reserve, it's from a location known as the heap. For most situations when we use memory, it's from a place called the stack. We're going to be borrowing or renting space from the heap. This function is going to return a pointer to where that memory is located that we reserved. Now, this next part is really important. Let's say that with the Malo function, it's like we're renting an apartment. We're renting some space that doesn't belong to us. When we're done using it, we have to return the space. When we no longer need the space, we have to return the apartment back, so to say, because we're just renting it. We're going to free the space that we no longer need by calling the free function. then pass in that pointer to our array like data structure. Think of it like we're returning the rented space back to the operating system. But not only do we have to return the apartment, so to say, we have to reset the pointer. I like to think of pointers as a star-shaped key. They unlock a value at a memory address when you dreference them. We have a key to our rented apartment. We have to return the key too. We have to reset it. We will take our pointer of grades and set it back to be null when we're no longer using it. If we don't, this would become what is known as a dangling pointer. Avoids dangling pointers. We don't want a pointer within our program that points to memory that we're not using anymore. It's like we're returning the key to our apartment. We don't need that key anymore. When you're done renting some space, you got to return the apartment and the key. In case this function fails for some reason, it's going to return a value of null. And we should check for that because if we dreference a null pointer, it's dangerous. It can cause a segmentation fault. We'll check with an if statement if the address stored within grades is equal to a value of null. If that's the case, we're going to print something. We'll say memory allocation failed. And then we'll return one to exit the program. The one serves as an exit code. That means there is a problem. Once we've made it past the if statement, that means we have some memory to work with because grades is not null. Here we'll get some user input and store it within our array. We can use a for loop for int i. I will set that equal to zero. We'll continue as long as i is less than the number of elements that we have. Now, previously with static arrays, we've been using the size of function something like this. int size equals the size of the size of our array grades divided by one of the elements. This is what we've done previously. However, this isn't going to work because grades it's a pointer to an array like data structure. What we'd be doing is getting the size of our pointer rather than the size of the array. What we'll do instead is take that user input. The user entered in how many grades they want. We'll continue this loop while I is less than the number of elements they have to enter in. Then we will increment I by one. I ++. Now we're going to use print f to create a prompt. Print f. We'll say enter grade number insert an integer. We're going to insert i. But during the first cycle of this loop, i is going to equal zero. And to a user, grade number zero might not make sense. We'll add an offset of one. I + 1. Then we're going to use scanf. We're accepting a character. We need a format specifier of percent c for a character. To remove the new line character from the input buffer, we're going to preede the format specifier with a space to ignore any white space or new line characters. Then at the address of our pointer to our grades with the pointer to our array-like data structure, we can treat it like it's an array. We can access it by index at the index of I. Insert a value here at this address. Then let's print our grades. For int i equals z continue while i is less than the number of grades we have to enter in. Then increment i by one each time. Then we're going to print each grade. Print f. We're displaying a character. We'll separate each with a space. I'll add a space afterwards. then access our pointer of grades at index of i. With our pointer to our array like data structure, we can treat it like it's a normal array. We can access it by an index. And this should work. Let's run it. Oh, one last thing. We need an import if we're using the malo function. Standard library stib.h. And I'm just going to add a colon then a space because I forgot to do that just so it looks better. Enter the number of grades. Seven. Enter grade number one. I'll say A, B, C, D, F, A, B. And here's my grades. I have seven grades. 1 2 3 4 5 6 7. Or I could pick a different number. Maybe three grades. A B C or maybe 10. A B C D F A B C D F. There we go. All right, everybody. That is the Malo function. It's a function in C that dynamically allocates a specified number of bytes in memory. If you need an array and you don't know what the size is going to be, you can use the malo function to reserve some space in the heap. But you have to be sure that you're freeing the memory when you're done with it and returning the key, setting it back to null. And well everybody, that is the Malo function in C. Hey, what's going on everybody? In this video, we're going to explain the calick function in C. Cal, it's short for contiguous allocation, but I like to think of it as clear allocation. What it does is that it allocates memory dynamically and sets all allocated bytes to zero. Malo is faster, but calick leads to less bugs. With calick, there's an extra step. We set allocated bytes to zero to effectively clear it. And there's two arguments we pass in, the number of elements and the size of each element. With Malo, we pass in a number of bytes instead, but they both behave very similarly. Here's how we can use calick in C. We're going to include the following header file. Include std dib.h. Let's pretend that we're playing a game. There's a number of players, but we don't know the number of players until the program is already running. We'll create a prompt to ask the user. We'll create a variable of int number for the number of players. I'll set that to be zero right away. Then we will ask using a print f statement enter the number of players colon space and then we will use scan f to get some user input. scan f percent d store this at the address of number. Here we're going to allocate some memory dynamically. We'll start with malo but then convert it to be calic. We'll need a pointer. This will be a pointer to an array-like data structure where we're going to store integers. The data type is int. This is a pointer. We need the dreference operator. We'll create an array like data structure named scores to hold all the player scores. Equals. We'll start with malo. For Malo, you pass in a number of bytes. For example, 100 for 100 bytes. We're actually going to calculate this. What is the number of players we have times the size of what we're storing? We're storing integers. In most cases, an integer is four bytes. We need the size of an integer. If we have 10 players and the size of an integer is four bytes, well 10 * 4 is 40, but we'll calculate that. Now, if we dynamically allocate some memory, we have to free it when we're done with it. Call the free function, pass in our pointer, our pointer of scores. That will free the memory. Also, take our pointer and set it to be null when we're done with it. I like to think of dynamically allocating memory like renting an apartment. We're renting space in the heap. Once we're done with our apartment, we have to release it. We have to give it back and we're returning the key, the key to the apartment. Both of these steps are very important. As good practice, we're going to check to see if our pointer is null. If our pointer of scores is equal to null, if for some reason we can't allocate this memory, it's going to return a value of null. If you dreference a pointer that's null, it can cause a segmentation fault. If our pointer of scores is null, then we will print the following. Let's say memory allocation failed. We will return an exit code of one. To exit the program after the sift statement, let's see what's within this memory that we've allocated. And there's a big difference between Malo and Calick. Let's cycle through this array. This array like data structure int i equals z continue while I is less than the number of elements we have. If we have 10 players, we got to cycle 10 times. Increment I by one. During each cycle, I will print. We're displaying an integer. I'll separate each with a space. With our pointer, we can treat it like it's an array. We can access it by index. Display what's at index I. Let's see what's within this memory that we've allocated. Let's say we have 10 players. 10 players for our game. Well, here are all the scores initially. They all contain garbage values because we didn't clear it out before accessing these elements. If we assign all of them, it won't lead to unexpected behavior. So, another option is to use calick to reset all those scores. Replace Malik with calick. But we pass in two arguments. The number of elements, then the size of each element. Now let's take a look at our scores. Enter the number of players. We'll say 10 again. And all the scores are zero. And then if you would like, we can enter in some scores. After our if statement, we'll create another for loop. And I'll just copy the one we have currently. We'll say enter score number percent D colon space. We'll insert I. Whatever I is currently, I is going to be zero during the first cycle. Enter score number zero might not make sense to a user. We'll add an offset of one when displaying it. And then we will use scanf to get some input. We're accepting an integer at the address of our pointer to scores at the index of i. We'll insert a value during each cycle. And then let's run this. Enter the number of players. I'll say 10. Enter score number one. We'll say 10, 20, 30, 40, 50, 60, 70, 80, 90, 100. And here are the scores. All right, everybody. That is the calick function. It means contiguous allocation. It allows you to allocate memory dynamically and sets allocated bytes to be zero. Malo is faster, but calick leads to less bugs because we take an extra step to zero all the bites. And well everybody, that is the calick function in C. Yo, what's going on people? In this video, I'm going to explain the realloc function in C. Realloc, it means reallocation. We can resize previously allocated memory. The realloc function, it takes two arguments. a pointer to smold memory and a new size in bytes. If you're familiar with other programming languages, the memory we allocate behaves very similarly to a dynamic array. Now, this topic is probably going to be one of the most complicated in this series. We'll take it step by step at a time. To work with the realic function, we need to include the following header file. Include standard library.h. In this scenario, let's say that we're a store owner. We need to dynamically allocate some space for some prices, some floatingoint numbers. So, we're going to start with the Malo function and then reallocate it later. Let's say we have an integer of number. What is the number of prices that we need for our store? If we have five products, number is going to be five. Let's initialize this to be zero right away. And then we will ask for the total number. Enter the number of prices colon space. Then we will accept some user input. Scan f. We're accepting an integer percent d. Store this at the address of our number variable. Now, we're going to dynamically allocate some space, but we're not going to use the realic function right away. What are we storing within our dynamic memory? Well, we're storing prices. An appropriate data type would be a floatingoint number. We're going to be returned with a pointer. A pointer to some dynamic memory. Let's name this prices. It behaves like an array if we access it. Now we're going to use the malo function or you can use calick 2 to clear it. Either one. We need to pass in a size in bytes of the memory we would like to allocate. But we're going to calculate that. Take our number for the number of elements times the size of function. Well, what are we storing? We're storing floatingoint numbers. With this formula, we can calculate the size we need and reserve that amount of memory in bytes. If we're dynamically allocating some memory, we'll want to be sure to free it when we're done with it. It's like renting an apartment, we have to return the apartment when we're done with it. To do so, we'll call the free function, pass in our pointer to free it, and then we will take our pointer, set it equal to be null. I like to think of a pointer as a key. Once we're done with the apartment, we have to return the key to the key to the apartment. Now, as good practice, if for some reason we can't allocate some memory, we will be returned with a value of null. We'll check for that. If prices equals null, we don't want to continue because if you dreference a null pointer, it can cause a segmentation fault. So, let's print the following. Print f. We'll say memory allocation failed new line and then let's return an exit code of one to exit the program. Let's be sure that everything is running fine just as a test. Enter the number of prices. I'll just say five. Okay, no problems. Now let's enter some prices in. We'll use a for loop for int i equals zero. We'll continue while i is less than the number of elements we have. Then increment i by one. During each cycle, we'll create a prompt. Let me scroll down. We'll say enter price number. We're going to insert an integer. I'll add a colon, then a space. We'll insert whatever I is, but I'll add an offset of one because I is going to start at zero and price number zero might not make sense to a user. Then we'll need some user input. Scan F. We're accepting a floatingoint number. The format specifier is percent F. Then we're storing this at the address of our pointer of prices at index of I. We can treat this pointer like it's an array. that is acceptable. Then let's display our prices. I'll copy this for loop, paste it, and we're just going to display the prices using print f. If we're displaying prices, I'll add a dollar sign or pick a different unit of currency. We're displaying a floatingoint number, percent f, I'll display two digits after the decimal. I'll add 2 and then separate each with a space. We are displaying prices at index of i. All right. And this should work. We want to be sure that this base program is running. Enter the number of prices. Let's say we have five prices. Enter price number one. I'll just make something up. 199. Price 2 will be $2.99. And I'll just go through all five. Then lastly, we have 5.99. All right. Here are my prices. We have $1.99 through 599. Now, here's where realic comes in. Once we have our dynamic memory, what if we would like to add more prices or get rid of some? Here's how. At which point would we like to use the realic function? Let's say after we've already typed in some prices, we're going to ask if we would like to change the number of prices we have. So let's create a variable. Let's say int new number. I'll set that to be zero right away. We're going to have a new number of elements. So let's create a prompt. Print f enter a new number of prices colon space. We'll use scanf. We're accepting an integer. Store this at the address of our new number variable. Now it's time to use realic. What's the data type of the memory we're storing? We're storing floatingoint numbers. One common convention for realic is to create a pointer named temp. Temp meaning temporary. We're only going to be using this pointer temporarily. equals realloc function. We have to pass in a pointer and a new size. We have to pass in a pointer to the old memory and a new size in bytes. So let's take our pointer of prices. The realic function is going to copy the prices over to some new memory. Then we need a new size. Rather than just hard- coding a number here, we're going to calculate it. take the new number of elements we have times the size of a floatingoint number. The realic function will return a pointer to some new memory and copy the previous values over from our old memory of prices. Now in case this fails, this will return a value of null. Let's check for that. We'll use an if statement. If temp equals null then we will print using print f we'll say could not reallocate memory new line. Now you could return an exit code of one to exit. I don't want us to lose the previous memory. We don't actually need to return one if we don't want to exit. Before displaying all the prices, let's add an else statement. We're going to take our pointer of prices and copy the address over from temp. Prices equals temp. If a pointer is a key, we're basically copying the key. Our pointer of prices now points at this new memory rather than the old memory. Now, what you could do, although it's optional, if you plan on reusing this variable of temp, I would recommend setting temp to equal null, but that's not necessary in this case. Now, we have to enter in some more prices. So, what we can do is copy this for loop and paste it within the else statement. We're going to begin where we left off. We'll set I equal to the original number but continue while I is less than the new number. Let's say the original number of elements was five. And now we would like 10 elements. I will start at five then and we'll continue till 10. We're continuing where we left off in the old memory. Once we enter all the new prices, let's display them. Really, we can just cut this loop where we display the elements and paste them within the else statement. But we'll continue this for loop while I is less than the new number of elements. And that should be everything. Let's test it. Enter the number of prices. Let's say we have five prices. I'll just make up some numbers. 199 29. and I'll just go through the list. Here's where the realic function is going to kick in. We're going to change the size of the memory we've allocated. Let's say now we would like 10 prices. Well, now we can enter price six in and we'll finish with $10.99. And here's all the prices. We have 10 elements. Each holds a floating point number. We have 199 through 1099. What if the new size of the array is less? Let's test it. Enter the number of prices. I'll say five again. I'll make up some numbers. Let's say I would like to change the size of the memory to be three. We have two less products in our store. Enter a new number of prices. I'll say three. What we end up doing is copying these three values to some new dynamic memory. And then we're only displaying three this time. So with Realic, we can take some memory and resize it. We can make it bigger or we can make it smaller. All right, everybody. That's the realloc function. It means reallocation. We can resize previously allocated memory. We have to pass in a pointer to some old memory and a new size in bytes. And well everybody, that is the realic function in C. Hey, what's going on everybody? In this video, we're going to create a working digital clock using C. Here's what it looks like. Let's get started. To kick off this project, we'll need a few imports. We'll do some copying and pasting. Along with the standard input output header file, we'll also need the time header file to work with time related functions. We'll also need standard bool stdbool to work with booleans. And then uni std meaning Unix standard. This header file will provide a sleep function to make our program wait for 1 second before updating the time. Here's the imports we'll need. Now, we need to declare our variables and other data structures. This first variable, it's going to have a data type of time t. The variable name will be raw time. And I'll set that to be zero right away. This variable of raw time, it's going to hold a number of seconds. The reason I'm not using an integer, it's because we need a very big integer. In fact, a long. There's a limit to how big an integer is. It's a number just over 2 billion. But if we use a long or more specifically this type of time t, we can hold a number that's even bigger than that. This data type of time t, it specifically holds what is known as Unix epic. We use epic as a reference point. It's usually some date around January 1st, 1970. We'll measure how many seconds have passed since this date. Depending on when you're watching this, it's a number around 1.7 billion. 1.7 billion seconds has passed since this date, and we'll use it as a reference point. This is the epic. This date, January 1st, 1970. The next thing we'll need is a strruct, but not just a strruct, a pointer to a strruct. There's a strct provided to us from the time header file. The data type is strct. The tag name is tm meaning time. This will be a pointer. We need the dreference operator. And we'll name this variable p time. Since the strruct isn't using the type defaf keyword, we do have to type strrruct. If it was using the type defaf keyword, we wouldn't need that keyword strruct. However, we do in this case. P time is going to be a pointer. If we declare a pointer but don't assign it, it could contain a garbage value. So what you could do with pointers is set them to be a value of null. Null meaning no value. But be sure that you don't dreference it before assigning it. Don't later in your program dreference it while it's still null. That can cause a segmentation fault. Dreferencing a null pointer is very dangerous and can lead to unexpected behavior. Then the last thing we'll need is a boolean of is running and we'll set that to be true right away. We'll continue the digital clock while the program is running. Then once we have our variables and other data structures, let's create a welcome message. We'll just print the title digital clock new line. Then we need a while loop while our condition is is running. What other programmers might do is say while true, which you could do, but I don't like doing that. just because it offers less control of the while loop. Then at any point within this program, we can say is running equals false to exit. But that's my own personal preference. So while is running continue the program, we need this while loop to execute some code approximately every second. Well, we could use the sleep function. Now, if you're on Linux or Mac, you can use sleep and then pass in one to sleep for 1 second. And then let's print something just to test it. Print f. I'll just print the word test. New line. And this does work for me. Every second we're printing the word test. But if you're a Windows user, you may have to use a different function. If this doesn't work, you may need a different import. Windows.h. This function instead is going to be sleep with a capital S, then you pass in 1,00 milliseconds rather than seconds. So if you're on Windows, you may have to use this function instead. I'm on Windows and the reason that both work for me is that the sleep function is actually provided to me by my compiler. If you're on Windows and this version of sleep doesn't work for you, then you may need to use the sleep function with a capital S, then pass in milliseconds rather than seconds. But again, it depends on your compiler. All right, our while loop is working. We're printing something and then sleeping and then we're doing that forever. Now, what we're going to do is update the time, our raw time variable. If we call the time function, we can update our time variable, but we have to pass in a pointer or an address. We're going to pass in the address of our raw time variable to update it so that it's passed by reference rather than passed by value. We're going to update the time with the current time, whatever it is. And then let's print it to test it. Print f. Since our raw time is a different type of integer, we have a different format specifier that is ld meaning long decimal. Then I'll add a new line. we will display our raw time variable and it should be a very large number. Yeah, you'll get like 1.7 billion seconds or so. But it is updating every 1 second though, which is good. This is the amount of time in seconds that have passed since our reference point. That epic January 1st, 1970. 1.7 billion seconds has passed since then. But we can use that as a reference point to calculate the current time. All right, we know that we're updating the time every second. But now we have to display it in a readable format. Here's how. We can use our timestruct. Our timestruct contains a bunch of members that represent the year, month, day of the week, hours, minutes, seconds, and so on. We will assign our pointer of p time equals call the local time function and then pass in the address of our raw time variable. Pass in the address of our raw time variable. This function is going to return a pointer. It's going to return a pointer to a time strruct that contains those fields of hours, minutes, and seconds. We're finishing assigning the strruct because originally it was null. Our pointer of time should point to a time strruct and it contains the current time. Now we just need to print it. Here's how. Let's start with a printf statement. We'll display three digits each separated with a colon. We'll do a little bit of formatting in a moment. We have a pointer of time. To access a member of a strct, normally you would type a dot. That's the access operator followed by the member name. In this case, we have tm hour. But what we have to do is dreference this pointer and then access one of its members. Kind of like this. However, there's an order of operations. we would end up accessing this member first of this memory address and then dreferencing it. So we would need to dreference this pointer first and then access the hour. But there is a shortcut too. Rather than using the dot, you can use the arrow operator. It's a shortcut. That'll do the same thing and it's more readable. Dreference our pointer then give me the current hour of our time strct. And then let's do this with the other members. Take our pointer to our timestruct, dreference it, and access tm just m for minute. Again, take our time pointer, dreference it, and access tmc for seconds. We should have the hours, minutes, then seconds. Oh, and then we need a new line. Here we go. Currently, it is 716 and some seconds. Let's add some zero padding. After the format specifier, type 02 to add two spaces of zero padding. And that looks a lot better. We're zero padding these digits. After each second, we're printing the new time on a new line. What if we could edit it in place? Here's how. Rather than printing a new line in print f, we'll go back to the beginning and use back slash r for carriage return. We'll end up moving the cursor back to the beginning and reprinting something. And now our time should update in place because we're moving the carriage back to the beginning. All right, everybody. And that is how to create a digital clock using C.