all right what's going on everybody it's you bro hope you're doing well and in this video i'm going to explain how we can get started writing code in c so sit back relax and enjoy the show if you wouldn't mind please like comment and subscribe one like equals one prayer for the youtube algorithm i'm going to tell you why you need to learn c c is a middle level language that originated in the 1970s and it is one of the most widely used programming languages to date on a spectrum of high-level languages to low-level languages
c is a middle level language low-level languages are efficient they work closely with machine architecture they consume less memory and they're fast as however they're difficult to understand and it takes more time to write code that's in a low level format high-level languages are easier to work with easier to understand they allow for more abstraction but they're slower they use more memory and they're abstract so it's difficult to work with low level hardware and systems a major advantage of middle level languages is that they can act as a bridge between high-level software and applications as
well as low-level hardware and embedded systems most compilers kernels and operating systems are written in c nearly all programming languages are influenced by c in some way c is what provided many of the original programming concepts such as variables data types loops arrays functions etc in fact the python language is written with c the default implementation is known as c python if you're already familiar with the programming language learning c will give you an even deeper understanding of how those operate c is literally everywhere from databases to self-driving cars operating systems to embedded systems it's
been around for so long and used for so many purposes here are some important notes before we get started c is not an object-oriented language it's procedural not abstract c plus plus is an object-oriented extension of c if you know c you already know some c plus plus however c is a difficult language for beginners don't get discouraged you can do it so what you'll need you'll need an ide an integrated development environment which is basically a fancy text editor to help us write c code as well as a gnu compiler collection which we abbreviate
to simply gcc this compiles or otherwise converts c code to machine code you know all those ones and zeros that a machine can read let's begin by downloading an ide i recommend vs code it's flexible and you can use vs code for more than just c all right what you're gonna do is head to code.visualstudio.com and then look for this drop down menu to install for your operating system i'm running windows i'm going to install for windows and then i will simply just open when done okay accept the license agreement next you can create a
desktop icon and add to path next then install and then give it a second or a couple minutes then you can launch this if you prefer i think i will okay we are now within visual studio head to the left hand menu for extensions we're going to install two extensions c c plus plus that contains intellisense and a couple other useful things so install that and then next we will install code runner code runner install after installing these extensions you may need to restart vs code okay then we are going to add a new folder
go to the left-hand menu add folder i'll create a new folder on my desktop so i'll right click go to new folder i'll name this c files then add i think you might have to click within the folder okay we now have a folder named c files then to create a new c file go to new file after clicking this folder i'll name this hello world and make sure that it ends with the c extension helloworld.c and we now have a c file that we can work with and on this tab at the top this
says hello world dot c now the next thing that we'll need is that gcc compiler to convert c code to machine code now if you're running windows this is how to check to see if you have a gcc compiler already installed so you're going to open command prompt and enter this command g plus plus dash dash version i already have a gcc compiler already installed if you're getting an error then you'll probably have to download one here's an interruption from future bro i traveled from the future to the past to deliver you this message so
if you need to install gcc on a mac operating system what you're going to do within a terminal window is enter the following command c lang dash dash version if c lang isn't installed enter the following command xcode dash select dash dash install and that's all there is to it if you need additional assistance you can always visit this webpage code.visualstudio.com docs slash cpp and if you're running on linux within a terminal window you'll enter this command instead gcc dash v if gcc isn't installed run this command sudo apt-get update and then next type in
this long command and if you need any additional assistance or documentation you can always visit this webpage so google this min gw dash w64 install.exe and the first link is for sourceforge so click on that then you can find this underneath home browse development compilers mingw64 for 32 and 64-bit windows and the download should start automatically so click next change the architecture to x8664 next and then copy this path for the destination folder it's going to be relevant later then next next and finish now what we're going to do is add our path to our
gcc underneath environment variables so open up control panel then go to system and security then system scroll down to advanced system settings underneath the advanced tab go to environment variables underneath path we are going to edit i already have this path configured so i'm going to delete this you probably won't have this setup and then new paste that file path to the gcc compiler then add slash min 64 slash bin then okay okay and then you can close out of everything and now we need to configure our build task so go to a terminal your
default build task if nothing appears within the search box you may need to restart vs code i think i do so i'm going to restart it and then let's try that again terminal configure default build task and there it is i will select that this creates a json file that tells vs code how to compile the program and with that out of the way we can begin coding now before we do start coding anything i'm going to increase the font size because as you can see this font size is really small so within vs code
to change the font size go to file preferences settings and you can change that here let's try maybe 20. you can also change the font family too if you want and everything uh but let's close out of that and try that again okay that isn't too bad i'll stick with this font size for now i also recommend enabling autosave that's going to save you a lot of headaches later in the future so go to file auto save okay the first thing that we're going to include within our c program is the word hashtag include so
this is a pre-processor command that tells the compiler to include the contents of a file and the file that we would like to include is within angle brackets std for standard io input output dot h this file contains some useful functions related to input and output so we'll need that now the entry point of our program is the main function type int main parentheses curly braces anything within our main function is read procedurally starting from the top and working its way down so anything within this set of curly braces is within the main function and
at the end of our main function we're going to add the statement return 0 semicolon a semicolon is used to terminate statements kind of like a period at the end of a sentence at the end of our main function we have this return zero statement this returns the exit status of our program we return a zero if our program runs successfully with no errors if there is an error then we'll return a 1. so now we can add anything that we want within this main function but we'll need return 0 at the end to check
for any errors so let's print something to our console as output so to display something we're going to type print f parentheses semicolon because we end our statements with a semicolon and within the parentheses add a set of double quotes because we would like to literally print something and you can type in whatever you want let's say i like pizza then to run this code you can either right click then go to run code alternatively there is a run code button in the top right corner of the s code so after running this code this
displays my output i like pizza so what if i would like to add a second line well i would just follow these steps again so i need another printf statement print f parentheses semicolon any text i would like to display i'll place that within a set of double quotes this time let's add a second line i like pizza it's really good and then save all right and this is what this looks like i like pizza it's really good so this is all one long line what if i would like my second line of text on
the next line well i can add an escape sequence for a new line character so at the end of my printf statement within the double quotes i'll add backslash n for a new line character and let's try that again so i'm going to clear my output make sure i save and then run this again i like pizza it's really good and then we have that extra space at the bottom because we added an additional new line character which is optional also take notice too that we have this message exited with code equal zero so if
there are no errors and your program runs successfully this function will return zero if there is an error well then this will return one so let's misspell something let's say instead of printf we just have print so save and then run this again okay it looks like we have an error exited with code equals one all right people well that's your first c program in the next video we'll cover escape sequences and comments i'll post this code to the comments section down below and pin it to the top if you would like a copy for
yourself but yeah that is your first c program hey you yeah i'm talking to you if you learned something new then help me help you in three easy steps by smashing that like button drop a comment down below and subscribe if you'd like to become a fellow bro [Music] all right everybody welcome back in this video i'm going to show you all how we can compile and run a c program using command prompt in my text editor i have a simple c program that prints i love pizza it's really good what we'll need to do
is open command prompt now before we begin we should make sure that we have a gcc compiler and to check that just type gcc minus minus version and it looks like i have one so if you're missing a gcc compiler check the first video in the series and i'll show you how to download one now step one to compiling a c file is that we need to change our active working directory so that it's pointing to the folder containing our c file an easy way to change that is that we need the file location so
i'm going to right click on my c file go to properties copy this location and within command prompt i will type cd to change directory and then paste that location so our current active directory is pointing to that folder containing our c file and to compile a c file you type gcc the name of the file and mine is hello world dot c then hit enter so nothing appears to happen and that's good so let's take a look at the c folder again this is the file that we compiled it is an executable and all
we have to do is run that so that is the third step a exe enter i love pizza it's really good so yeah that's how to compile and run a c file in command prompt first make sure that you have a gcc compiler that would be i guess step zero step one is to change the active working directory to the folder containing your c file compile the c file with gcc the name of the file and then run the compiled file a.exe so yeah that is how to compile and run a c file with command
prompt if you found this video helpful please be sure to smash that like button leave a random comment down below and subscribe if you'd like to become a fellow bro hey y'all what's going on everybody it's you bro hope you're doing well and in this video i'm going to explain to both comments and escape sequences in c so sit back relax and enjoy the show all right welcome back so we have to discuss comments and escape sequences so a comment is some text that is ignored by the compiler that is used as an explanation description
or a note for yourself or anyone else reading over your code so try to comment you will type two forward slashes then anything afterwards is considered a comment and will be ignored by the compiler this is a comment blah so if i was to run this this text will be ignored by the compiler and we do not see that as output i tend to use a lot of comments when explaining things so this is something you'll see fairly often in my videos now if you need a multi-line comment this is only for a single line
comment if i was to type this again without those forward slashes this is a comment well our program thinks that this is some sort of code if we need a multi-line comment you will instead type forward slash asterisk then anything after is considered a comment you can see that this is all green now anything up to a asterisk and forward slash will be a multi-line comment this is a multi-line comment and again this is ignored by the compiler so if you need to write a note description or explanation for yourself or for somebody else you
can write that within a single line comment or a multi-line comment and i use a lot of these for teaching purposes because i have a lot of explaining to do right okay let's move on to part two of this video we have escape sequences an escape sequence is a character combination consisting of a backslash followed by a letter or combination of digits they specify actions within a line of text otherwise known as a string so we learned in the last video that we can end our printf statement with a backslash n to create a new
line this is the escape sequence for a new line and within a string of text a line of text and within a string of text we can add a new line wherever we want and as many as we want let's say that after each word within my line of text i would like to add each word to a new line so i can use the escape sequence for new line after each of these words so that would look like this i like pizza but you may have to work on the spacing though that's a little
bit better so wherever you place a backslash n that will create a new line character another escape sequence is backslash t for a tab so let's say i have a few numbers here one two three and i would like to create even spacing between these numbers i can just add an escape sequence for a tab character one backslash t two backslash t and these numbers are spaced evenly or i can get really fancy and add a new line character then maybe a four tab five tab six new line character then maybe a7 tab 8 tab
and then a 9. so now we have a grid of numbers all spaced evenly so that is the new line escape sequence and the tab escape sequence you can use them wherever and however many you want within a string of text within a printf statement what if we need to display quotes like we're quoting somebody i like pizza this is a quote from abraham lincoln probably i need to place quotes around i and pizza so if i were to write it like that well our program doesn't know where our string of text begins and ends
it's kind of confused if we need to literally print double quotes we will add an escape sequence backslash then double quote and then add that here as well so this allows us to literally print some quotes as i'll put i like pizza abraham lincoln probably or if you need to display single quotes backslash single quotes so that's how to display single quotes and if you need to display a backslash that would be double backslashes this will literally print backslashes so yeah those are just a few escape sequences here's a list of a bunch of them
but a lot of these really aren't going to be relevant to us so yeah those are comments and escape sequences and see if you found this video helpful please be sure to destroy that like button drop a random comment down below and subscribe if you'd like to become a fellow bro hey yeah it's you bro hope you're doing well and yeah we're doing stuff with variables today in c so sit back relax and well enjoy the show welcome back to another video so variables variables are allocated space and memory to store a value we refer
to a variable's name to access the stored value that variable now behaves as if it was the value that it contains but to create a variable we first need to declare a name for a variable and then precede it with the type of data that we are storing creating a variable is done in two steps declaration and initialization so we need to first declare a variable to allocate some space in memory to store a value so we need to precede our variable name with the data type of what we plan on storing within this variable
if i need to store a whole integer we would precede our variable name withint int for integer and let's say that this is variable x so this step is declaration we are creating space and memory to store a value and to actually store a value that step is initialization so we would take our variable name x in this example and set it equal to some value so we declared that this variable is an integer we can only store whole integers maybe the number one two three so this is initialization or you could combine these steps
together and let's create into y into y equals 3 2 1. this is both declaration and initialization so creating and storing a variable takes two steps declaration and initialization and in order to create a variable you have to precede the variable name with the data type of what you plan on storing within that variable int for a whole integer but there's other data types too let's create some more variables what about int age with variable names you're not limited to only just x and y you can really name it whatever you want within some limitations
but make sure that the variable name is descriptive of what it does so age is going to store an edge let's say that i am 21 years old so this is an integer a whole number if we need a number containing a decimal portion that would be a float for floating point number so one example of a variable that could contain a floating point number is a gpa grade point average let's say that my grade point average is a 2.05 so this is a floating point number it's a number that contains a decimal portion we
can also store single characters with the char data type like you're pronouncing charizard and this will be a letter grade let's say now to store a single character we have to place it within single quotes when we initialize it with my grade variable what about a c like my average grade is a c remember everybody c's get degrees so char stores a single character now c isn't an object-oriented language so there is no string data type because strings are technically objects so if we would like to store like somebody's name we need a series of
characters so we can create what is called an array and to create an array we would follow our variable name with a set of square brackets and then assign this equal to some string of text some series of characters place your series of characters within double quotes and we can store more than one character so this data type would be technically an array of characters i'll create a whole separate video on arrays this is basically how you can emulate a string it's really just a whole combination of single characters there's still a lot more data
types than just these four i thought i would cover just some of the more basic data types just because in this video we're going to focus more on variables than data types i'm planning a separate video just dedicated to data types because there's way more data types than just these four there's bytes there's doubles there's longs etc now how can we display the value stored within a variable within a printf statement here's how we have to use what is referred to as a format specifier let's say we have a printf statement and i would like
to display my age within a message so let's create some text you are age years old if i would like to display the value contained within my edge variable wherever i would like to insert that value i will place a format specifier which is represented by a percent sign and then follow this with a secret character that represents the data type of what we're inserting so if i need to display my age variable i will use a percent sign as a placeholder followed by d for decimal and then after my string of text outside of
the double quotes add comma then the name of the variable you would like to insert at this placeholder so at this location i will insert age and then let's try this you are 21 years old so let's try that again with a different variable let's say let's go with name i'll add a second printf statement print f and then let's say hello and i would like to insert my name here so use a percent sign as a placeholder it's a format specifier then to display a character array that would be s for string and then
add comma name oh then we may need to add a new line character to the end of these because i forgot let's try that again hello bro you are 21 years old okay let's display our grade printf then within quotes your average grade is then to display a character variable that would be percent c for character then outside of our double quotes add comma the name of the variable we would like to insert at this location so comma grid i think i'm just going to space these out a little bit okay then i will add
a new line character to the end of this okay hello bro you are 21 years old your average grade is c then to display a float that would be percent f print f your gpa is percent f then i'll add a new line character so follow this with comma the name of the variable gpa okay your gpa is 2.05 so later on we'll discuss more about format specifiers there's ways that we can format how our variables are displayed i just realized that i misspelled average twice so yeah those are variables they are allocated space and
memory to store a value we refer to a variable's name to access the stored value that variable now behaves as if it was the value that it contains but to declare a variable we have to state what type of data that we are storing within that variable so yeah those are variables if this video helped you out help me out by smashing that like button leave a random comment down below and subscribe if you'd like to become a fellow bro all right what's going on people let's discuss more about data types we discussed a few
in the last video but there's a few more that you should be made aware of so chars they store a single character and use the percent c format specifier to display a single character there's an array of characters which can store one or more characters then to display that you use percent s as the format specifier floats they will store a decimal number and we use the percent f format specifier to display a floating point number and then we have integers which only store a whole integer there is no decimal portion and we use percent
d to display an integer now along with floats we have doubles doubles have double the precision of a float we can store even more significant digits floats use four bytes of memory they have 32 bits of precision and we can store between six to seven significant digits doubles they have eight bytes of memory double that of floats and they have 64 bits of precision and we can store between 15 to 16 significant digits with my float and my double i'm storing the first several digits of pi i'm going to attempt to display as many digits
of pi as i can with a float so i'm going to display these so to display a float use percent f and lf for a double which means long float now by default when i use printf to display a floating point number or a double this will only display the first six to seven digits but we can actually change that we'll discuss more about these in the next video on format specifiers if i would like to display even more digits after the decimal i will add zero point and the amount of digits i would like
to display so i would like to display 15 digits after my decimal and i'll do that for my double as well so after the percent signed 0.1 f then add lf and let's take a look at these numbers okay after my two which is i believe the sixth digit after the decimal we actually lose our precision these numbers are not the same but our double will actually retain these numbers so point being a double is even more accurate than a floating point number there is more precision but it uses more memory a double uses eight
bytes of memory because of this reason we tend to use doubles a lot more than floats just because they're more precise we don't want to lose our precision next up we have booleans to work with booleans and c include this at the top std bool.h booleans store true or false so they work in binary one represents true and zero represents false so when you need to declare a boolean variable you type bool then a variable name and you set it equal to true or false technically we only need one bit to represent true or false
one for true and zero for false but this still uses up one byte of memory and then to display a boolean you can use percent d so if i was to display this boolean variable i would use percent d so one corresponds to true and zero corresponds to false although there are some tricks that we can do in the future where we could display the word to true or the word false but for now we're going to stick with percent d as the format specifier so these work in binary one for true zero for false
now another thing that we can do with chars is that we can store a whole integer between the range of negative 128 to positive 127. so in this example we have char f and i will store the integer number 100 we can display this number as either a decimal an integer or a character so if i was to display this number as a character we will use the ascii table to convert this number to a character representation the ascii table has a range between 0 to 127 so if i was to display this number as
a decimal using the percent d format specifier of course this will display as 100 but if i was to convert this to a character using the percent c format specifier this has a corresponding character and that would be lowercase d so i'm actually going to change this to something else what about i don't know uh 120 so let's see what the character representation of that number is and that would be a lowercase x so you can use chars to store more than single characters you can also use them to store a whole integer however the
range is between negative 128 to positive 127 because they have one byte of memory now there is a keyword unsigned so when you declare a variable that is unsigned we disregard any negative numbers so effectively this doubles our range with our positive numbers so if we have unsigned char we can store a number between 0 to positive 255 because we know we're not going to store a negative number so then if you need to display an unsigned character we can use just percent d i'm going to store 255 within my unsigned chart and that would
be of course 255. however if we go beyond this range this will overflow and go back to zero so if i was to display this we have a warning unsigned conversion from int to unsigned chart so then this resets back to zero so if you go beyond the maximum range this will reset all the way back to zero whatever the beginning is so if you add this keyword unsigned you can effectively double the range of positive numbers that you can store within a variable by default most data types are already signed but we don't need
to explicitly type that so point being with chars you can store more than a single character you can store a whole integer between ranges negative 128 to positive 127 if it's signed if it's unsigned you can store numbers between 0 to 255. you can display them as an integer by using the percent d format specifier or you could convert them to a character using the ascii table by using the percent c format specifier next we have short hints short ins use two bytes of memory they can store a number between negative 32 768 to positive
32 767 because while they use two bytes of memory they can only store a number so large and if it's an unsigned short int the range is instead between 0 to 65 535 and we use the percent d format specifier to display a short in so within my printf statement i'm going to display these two numbers so i will display variable h and i h is a short integer and i is an unsigned short integer so these are the maximum values for a short integer and an unsigned short integer and like i discussed with chars
if we go beyond this range we will encounter an overflow so i'm going to change this short end to 32768 and let's see what number displays so this will overflow and reset this value back to the minimum value which in this case is negative 32 768 and if you do the same thing with the unsigned short integer that would be zero because that's the minimum value for an unsigned short integer so those are short integers they use two bytes of memory and they can store numbers between these ranges depending if it's signed or unsigned oh
and another way of writing these you don't necessarily need to declare these with the word and you could just say short and that would do the same thing people usually just call them shorts instead of short ants so those are what shorts are now with integers we kind of discussed this in the last video just briefly integers store a whole number between just under negative 2 billion to just over positive 2 billion because they use 4 bytes of memory and we use the percent d format specifier to display a signed integer if that integer is
unsigned the range changes from 0 to just over positive 4 billion however there is a different format specifier to display an unsigned integer you instead use percent u so then let's display these percent d for a signed integer and percent u for an unsigned integer and these are the maximum numbers and then if i was to exceed the range this again would cause an overflow and reset these numbers back to their minimum values so those are standard integers they use four bytes of memory so they can store numbers between these ranges depending if they're signed
or unsigned all right the last data type we're going to talk about for this topic is a long long integer now the reason that we have long twice is that with standard integers these are already considered longs but we don't need to explicitly type long for standard integers so to represent a really large number we can use a long long integer and these use eight bytes of memory the effective range for a signed long long integer is just underneath nine quintillion to just over nine quintillion and the format specifier for a long long integer one
that is signed is percent lld now if it's unsigned that changes the range between zero to just over positive 18 quintillion and the format specifier is percent llu then let's display these so for a signed long long integer that is lld and if it's unsigned that is llu now we'll encounter a warning so this warning applies to our unsigned long long integer integer constant is so large that it is unsigned so one way in which we can prevent that warning is after our number within our unsigned long long integer add a u to the end
of this so then we can display this number with no warning so since long long integers use so many bytes they can store a gigantic number we tend to not use long long integers very often because well we don't really have a need for this large of a number but in certain circumstances you might perhaps you're dealing with the speed of light or something you may need to use a long long integer but commonly we use standard integers a lot more well yeah everybody those are even more c data types we likely won't be using
most of these but you should still be made aware of their existence i would say that we're going to focus on chars array of chars doubles booleans and integers so pay attention to those ones but you should still be made aware of the existence of other data types just in case you encounter them if you found this video helpful please smash that like button leave a random comment down below and subscribe if you'd like to become a fellow bro all right welcome back everybody in this video i'm going to show you while a few extra
things that we can do with format specifiers using a format specifier within a printf statement we can define and format a type of data to be displayed to use a format specifier you use a percent sign then follow that percent sign with a certain character depending on the type of data you would like to display let's say that we have three variables maybe we have an online store or something like that so let's say that these are of the float data type and we'll have three items for sale item one and make up some price
let's say that the first item is five dollars and seventy five cents and we have item two and this will be ten dollars even and then we have item three and this will be one hundred dollars and ninety nine cents so let's display item one item two in item three with a print f statement print f and within a string let's say item one colon space then i'll add a dollar sign wherever you would like to insert a value or variable you will use that format specifier the percent sign so after my dollar sign i'll
add item one so that would be percent then for floats you need f and then after the string add comma item one then let's just make sure that this works so we're going to be formatting this output what if we don't want all the zeros we can set the decimal precision of a float or double after the format specifier add a dot and the amount of digits you would like to display if i would only like to display two digits after the percent i will add point two and this will only display two digits for
the amount of cents that we owe okay now let's do the same thing for items two and three so item two item two item three item three okay then let's add a new line character because i forgot so new line new line and new line much better another thing that we can do with format specifiers is that we can set a minimum field width so just add a number after the percent sign let's say that i would like to allocate eight spaces worth of room to display my number so after the percent sign but before
the decimal add how many spaces you would like to set for the minimum field width let's say eight and let's see the new output okay there we go however it's all right aligned if you would like this left aligned you would use a negative sign after the percent to left align all this this would be negative whatever number you would like to allocate so the number is left justified but we still have all of this room after so that's what a format specifier is it defines and formats a type of data to be displayed so
place a format specifier within a string use a certain character for the type of dad you would like to display you can set decimal precision for floats and doubles you can set a minimum field width to display your output if you would like to line things up like you can see here and you can left or right align your output so yeah those are format specifiers if you found this video helpful please be sure to smash that like button leave a random comment down below and subscribe if you'd like to become a fellow bro hey
everyone so i'm going to attempt to explain constants in about a minute a constant is a fixed value that cannot be altered by the program during its execution i have a variable pi pi equals 3.1415 but what if we accidentally or somebody else changes the value of pi it's an important number pi now equals 420 69. since this value was changed this will alter the result of our program to prevent a variable or value from being changed we can turn that variable into a constant by preceding the data type with this keyword const and a
common naming convention with constants is that you make all the letters uppercase although it's not necessary but it's considered good practice so if i attempt to take our constant and assign this a different value we'll run into an error error assignment of read-only variable pi that is what a constant is it's a fixed value that cannot be altered by the program during its execution and it provides a little bit of security so if you found this video helpful please be sure to smash that like button leave a random comment down below and subscribe if you'd
like to become a fellow bro well well well welcome back so we need to talk about arithmetic operators because well this wouldn't be a full course without them so as you probably know arithmetic operators are well addition subtraction multiplication division and there's a few others too unique with programming such as modulus increment and decrement so let's go over a few let's say that we have int z and if we need to add two numbers we could say x plus y equals z and then display the sum which of course is seven so subtraction is well
minus five minus two is three multiplication is an asterisk five times two equals 10. okay now pay attention to this with division so 5 divided by 2 equals 2.5 right well that's where you're wrong it's 2 because we're storing the result within an integer and with integers we can only store whole numbers so we will lose that decimal portion it will be truncated there's a few things we'll need to change first we'll need to store the result within a float or a double and then let's display this percent f for a float okay another thing
that we need to change too and that involves integer division if we're dividing by an integer we'll truncate that decimal portion there's one of two things we can do we can either change our divisor to a float or a double and that will solve that problem 2.5 or if we would like to keep this as an integer we can convert this integer to a float or double by preceding the divisor with float or double either one so if i would like to keep y as an integer and we divide x by y we will convert
2 into a float so 2.0 and store the result within float z and the result is 2.5 so if you're performing division with any integers you need to pay attention to integer division and you may need to cast your divisor as a float or as a double now we have modulus modulus gives you the remainder of any division 5 does not divide by 2 evenly int z equals x modulus y and if we display z so make sure to change your format specifier if you didn't the remainder of five divided by two is one if
this was four four divides by two evenly and the result is going to be zero modulus gives you the remainder of any division it's actually pretty helpful to find if a number is even odd all you do is say modulus 2 or some variable containing the value of 2 either way and then we can increment or decrement a number by 1. if i need to increment x for some reason you'll see this when we get to the video on loops i could say x plus plus and then let's display x x incremented by one would
be six and then let's decrement y y minus minus and y decremented by one equals one so yeah everybody those are a few arithmetic operators a lot of these are fairly simple you know addition subtraction multiplication and division do pay attention to integer division because that can throw off your program then there's also modulus increment and decrement if you found this video helpful please remember to smash that like button leave a random comment down below and subscribe if you'd like to become a fellow bro hey welcome back everybody here's a super quick video on augmented
assignment operators they're used to replace a statement where an operator takes a variable as one of its arguments and then assigns the result back to the same variable now what the heck does that mean okay so let's say that we need to increment the value of x by one without using an increment operator we could say x equals x plus one so writing this out can be somewhat redundant there is a shortcut by using an augmented assignment operator whatever variable you would like to perform an operation on you will list that variable use an arithmetic
operator equals and then some value so writing this would increment x by one so let's go over a few examples we have into x equals ten so i could write x equals x plus two to increment x by two right or i could say as a shortcut x plus equals two and that will do the same thing and that's twelve now let's try minus x equals x minus three using the augmented assignment operator that would be x minus equals three which is seven what about x equals x times four well that would be x times
equals four x times four is forty and division x equals x divided by five the augmented assignment operator of this equation is x divided by equals five which is two and lastly modulus so what about x equals x modulus two that would be x modulus equals two x modulus two equals zero well yeah everybody those are augmented assignment operators they're basically a shortcut they're used to replace a statement where an operator takes a variable as one of its arguments and then assigns the result back to the same variable it's a shortcut if this video helped
you out you can help me out by smashing that like button leave a random comment down below and subscribe if you'd like to become a fellow bro hey uh welcome back in this video i'm going to show you all how we can accept user input in c now if you're using vs code we need to switch from using our output tab to terminal and one way in which we can make that change is by going to file preferences settings search for code runner and then check this run in terminal so then when we run our
code it will now display in terminal which accepts user input output doesn't because well it's only for output and you can ignore this this is a powershell command that will compile and run your c program but if you prefer instead of powershell you can use command prompt but you would need to manually compile and run your code since i'm using windows that would be a gcc the name of your c program hello world dot c that will compile your program into an executable named a dot exe then just type that to run it but i'll
stick with using powershell just to kind of simplify things okay now how can we accept user input let's declare a variable age but not yet assign it next we're going to create a prompt to ask the user for their age and we'll ask how old are you to accept user input we can use the scan f function it's kind of the inverse of printf printf is used to display something as output scanf is used to read input what we're going to place within our scanf function is the format specifier of the variable we will insert
a value into if we need to accept a number an integer as input the corresponding format specifier is percent d then add a comma the name of the variable but precede the variable name with an ampersand that is the address of operator let's print a message that contains the value stored within our variable edge u are percent d years old so this is our format specifier it functions as a placeholder and i would like to display the value contained within my edge variable so things are getting a little bit difficult to read i'm just going
to precede this with a new line okay let's try that again how old are you let's say that i'm 21 not anymore but let's pretend that i still am you are 21 years old that's basically how to accept user input you use the scanf function use the format specifier of the variable list the variable appreciated with the address of operator let's try this again but instead accept a string from a user like a name we need to declare an array of characters and set asides so let's create a character array named name now with character
arrays we can't change the size of the array after the program is already running let's set a max size of maybe 25 bytes for this array if we go over this limit this will cause a buffer overflow and let's ask a user for their name so we'll create a prompt printf what's your name and i again will use scanf list the appropriate format specifier for character arrays which is percent s then our variable name and use the address of operator then at the end we'll display our name printf hello percent s how are you then
comma name and before we run this i'm just going to add some new line characters just to make everything easier to read okay let's try it what's your name i'll type in just my first name not including any white spaces how old are you 21 hello bro how are you you are 21 years old so now this time let's type in a first and last name because this is going to act a little bit bizarre what's your name bro code and this is separated with the white space hit enter hello bro it did not include
my last name how are you you are zero years old so using the scan f function we will read up to any white spaces so if your user input is going to include a white space we need to use a different function and that is the f gets function f gets parentheses and there are three things we will list within the fgets function the name of the variable and we do not need the address of operator that ampersand for this then we need to set an input size i will set this to 25 to match
the size of our array and then std in which means standard input so using this function we can read any white spaces what's your name i'll type in a first name and a last name how old are you 21 hello bro code and notice that our output is actually being displayed on the next line that's because when you use the f gets function it will include the new line character when you hit enter if you need to get rid of that new line character at the end so that it's not included with your input here's
what we can do it's a little advanced but we'll cover this in future videos we'll include this import include string dot h so using this import we can work with strings all we're going to do is edit our string and get rid of that newline character at the end what i'm about to show you will look a little bit advanced but it's going to make more sense when we get to the video on string functions type the name of the variable followed by a set of straight brackets type str len this gets the length subtract
one and we will set the sequel to backslash zero that will get rid of the new line character so again this is a little bit advanced for us but it'll make more sense in future videos when we get to the video on string functions and let's try this one last time what's your name type in a first name and a last name hit enter how old are you 21. hello bro code how are you you are 21 years old if you need to accept a string from a user that includes white spaces like a first
name and a last name you'll want to use fgets in place of scanf because scanf can't read those white spaces it stops right there but it will include that new line character when you hit enter so you can do some string formatting just to get rid of that new line character and like i said this statement here will make more sense when we reach the video on string functions but yeah basically that's how you can accept user input you can use the scanf function if you need to accept a string of characters that includes white
spaces you'll want to use fgets instead so yeah that's how to accept user input and see if you found this video helpful please be sure to smash that like button leave a random comment down below and subscribe if you'd like to become a fellow bro hey what's going on everybody so in this video i'm gonna show you some useful math functions in c now if we include this math header file this contains a lot of the useful functions i'm about to show you one useful function is the square root function let's say that we have
a bunch of variables we declared them but we have not yet assigned them i will assign a the square root of nine so after including this math header file i have access to a square root function so type sqrt then add a set of parentheses and within the parentheses we can find the square root of a number let's find what the square root of nine is and then display it with a printf statement so the square root of nine is three so let's move on we can raise a base to a given power by using
the pow function the first number is the base let's raise two to the power of four and then display it two to the power of four is 16. we can round a number and i will store this within an integer let's round 3.14 oh and then make sure you use the appropriate format specifier for ins 3.14 rounded is 3. now by using the seal short for ceiling function we can always round a number up 3.14 rounded up is 4. likewise there's a floor function where we will always round down 3.99 rounded down is 3. we
can find the absolute value of a number that's how far a number is away from zero so it will take any negative numbers and make them positive the absolute value of negative 100 and that would be positive 100 if you're familiar with logarithms we can find the logarithm of a number log 3 is 1.098612 and if you know some trigonometry there's various functions for sine cosine and tangent so what's the tangent of 45 that is supposedly this number 1.619775 so yeah everybody those are a few math functions that you might be interested in to use
these just include this header file at the top math.h if you found this video helpful please be sure to smash that like button leave a random comment down below and subscribe if you'd like to become a fellow bro hey everyone here's a quick program that we can make to calculate the circumference of a circle i thought this would be good practice for us now that we know how user input works let's declare all of the variables that we'll need i'm going to create a constant variable named pi and it's going to be of the double
data type pi equals 3.14159 the reason that i'm making this a constant is that i don't want anybody else to be able to change the value of pi and let's declare but not assign a radius quite yet we'll have the user type that in and double circumference this will be calculated and displayed so we will need to prompt the user to enter in a radius i'll proceed this with a new line enter radius of a circle and then i will use scanf to accept some user input we need to list the format specifier of doubles
which is lf comma address of operator radius then the formula for radius is 2 times pi times radius and then we will display our circumference using printf circumference then we need a format specifier we're displaying a double so the format specifier is lf comma circumference and let's run it enter well the radius of a circle uh let's say that our radius is 10 maybe this is 10 i don't know meters all right our circumference is 62.83 meters now why not take this a step further let's also calculate the area of the circle i wasn't planning
on taking it this far but hey let's calculate that as well for practice so let's declare a double variable named area and we will calculate what area is the formula for the area of the circle is pi times radius squared pi times radius times radius then let's display the area so area we're using the double format specifier and area then let's add some new line characters to separate everything enter the radius of a circle let's say 10 meters the circumference is 62.83 meters and the area is 314 meters all right everybody that is a small
program to calculate the circumference of a circle and i guess the area as well just because well why not so yeah if you found this video helpful please be sure to smash that like button leave a random comment down below and subscribe if you'd like to become a fellow bro alright welcome back everybody in this video we're going to write a small practice program to find the hypotenuse of a right triangle we'll need the help of our math.h header file because we'll need access to some useful math functions more specifically the square root function let's
declare all of the variables that we'll need we'll need sides a b and c and these will be of the double data type a b c we'll ask the user to enter in sides a and b print f enter side a and then we will use scanf so the format specifier for a double is l f then i would like to insert a value within a so i need to use the address of operator then our variable a okay let's do the same thing for side b enter side b and store the user input within
variable b the formula to find the hypotenuse of a right triangle is the square root of a squared plus b squared so we will set c equal to the square root function and within the parentheses we will say a times a plus b times b and then we will display c side c and the format specifier for a double is l f and we are displaying c and well let's try it so side a let's say is three side b is four that means side c is five so yeah i thought that would be a
good practice program for us to get used to accepting user input if this video helped you out help me out by smashing that like button leave a random comment down below and subscribe if you'd like to become a fellow bro hey let's talk about if statements if statements are used to add some choices to a program let's take the small program for example we have a variable edge and we'll ask a user to enter in their edge what if i would like to check their edge maybe they're signing up for a credit card or something
so to check some value we can write an if statement if parentheses then a set of curly braces if some condition that we specify is true we will execute some block of code some subsection of code what sort of condition should we write let's check to see if age is greater than or equal to 18. so there's different comparison operators there's greater than or equal to greater than less than less than or equal to or you could check to see if two values are equal by using double equal signs this is the comparison operator if
you use just one this is the assignment operator and this would be the same as assigning age equal to 18 so if you need to compare if two values are equal use the comparison operator which is double equal signs but what i would like to do is check to see if age is greater than or equal to 18. if this condition evaluates to be true we will have our program do something so let's print a message since we're signing up for a credit card let's say you are now signed up and let's run it end
to your age let's say that i'm 21 i hit enter boom you are now signed up but what if this condition is false let's say that i'm 12 years old and i'm attempting to sign up for a credit card well we skip this if statement if this condition evaluates to be false we will skip this block of code and continue on with the rest of the program ignoring it or we could do something else by using an else statement if this condition is false we will skip this subset of code and instead perform this let's
print a different message instead you are too young to sign up and let's try that again and to your edge i am 12. you are too young to sign up you can check more than one condition before reaching your else statement by using else if blocks and that is by using else if statements we can check another statement before reaching our else statement so let's check to see if age is less than zero so obviously somebody's messing with this program then because you can't be under zero years old right you haven't been born yet so
after running this program if i say that i'm negative six you haven't been born yet so we will check our if statement first if this condition is false we will move down to the next block and then check this else if condition if all above statements evaluate to be false we will execute this else block as a last resort so to say and with these else if blocks you can add more than one let's check something else just to demonstrate else if what about age is equal to zero and we will print you can't sign
up you were just born and to your age i am zero years old you can't sign up you were just born if one of these conditions evaluates to be true we will skip all of these statements that come after then with our else block if all above statements evaluate to be false we definitely execute whatever's within here so yeah those are if statements they add some choice to a program you can check to see if some condition is true if not you can check something else using else if statements you can perform whatever is within
an else block and that's optional so yeah those are if statements and see if you found this video helpful please be sure to help me out by smashing that like button leave a random comment down below and subscribe if you'd like to become a fellow bro all right welcome back people switches a switch is a more efficient alternative to using many else if statements it allows a value to be tested for equality against many cases here's an example of where a switch would be useful i have a small program we will tell a user to
enter in a letter grade and depending on their grade we will print a custom message if grade equals a will print perfect else if grade equals b will print a different message so on and so forth so it's considered bad practice to use a lot of else if statements a better alternative is to use a switch here's how we can create one type switch parentheses curly braces whatever value you would like to examine for equality placed within the parentheses i would like to examine my grade and now we need to write some cases case and
then some value you would like to test for equality so i am comparing characters i will write the character a colon then if these values match we will execute some subset of code kind of like an if statement let's print perfect and then add a break afterwards then you can add another case so case b you did good casey you did okay case d at least it's not an f case f you failed now you can add a default case this functions like an else statement if no other cases match we will execute whatever's within
our default case so that means there are no matching letter grades so let's print please enter only valid grades and let's test it enter a letter grade a this will print perfect whatever's within our matching case let's try it again b you did good see you did okay d at least it's not enough f you failed and if there are no matching cases we will execute our default case uh how about w for win please enter only valid grades the reason that we add breaks after each case is so we can break out of our
switch and exit let me show you what this looks like if we do not have any breaks now let's say that we have a c letter grade you did okay at least it's not enough you failed please enter only valid grades so the reason that we have breaks is to exit out of our switch if we have a matching case and there are no breaks we will continue executing each case that comes after so it is important to have those breaks if you want to exit out of your switch well yeah that's a switch everybody
it's a more efficient alternative to using many else if statements using a few elsif statements is okay but it's considered poor practice to use a lot of them so yeah those are switches if this video helped you out you can help me out by smashing that like button leave a random comment down below and subscribe if you'd like to become a fellow bro hey uh everybody it's bro hope you're doing well and in this video we're going to create a small program where the user will type in a temperature and we can convert that temperature
from fahrenheit to celsius or celsius to fahrenheit so sit back relax and enjoy the show now before we begin this video make sure that you include these two imports at the top we'll be working with string functions and many of them can be found within this import see type dot h so let's declare the variables that we'll need char unit unit will be either c for celsius or f for fahrenheit and float temp short for temperature let's prompt the user to enter in some user input printf is the temperature in f or c and then
we will accept some user input so we will be accepting a character so use the appropriate format specifier for characters and we will use the address of operator which is an ampersand unit and then let's use an if statement to check to see if unit is equal to the character c else if unit is equal to f we will use the formula to convert fahrenheit to celsius if it's c celsius to fahrenheit and we should probably add an else statement as well okay let's actually test these right now okay this will only be temporary i'm
going to print a message the temp is currently in celsius and with fahrenheit the temperature is currently in fahrenheit so if the user did not type in c or f well then what the heck did they type in so within our else statement let's yell at the user let's say that whatever they entered in is not valid input so format specifier c is not a valid unit of measurement and then we will display whatever the user typed into our unit variable so let's test this is the temperature in f or c so f the temp
is currently in f let's try it again is the temperature in f or c see the temp is currently in c okay this time we will not type in f4c how about the word pizza this only accepts the first character p is not a valid unit of measurement here's one situation that we may run into c programs are case sensitive if i type in lowercase f or lowercase c well technically neither of these conditions would be true for example if i type lowercase t c is not a valid unit of measurement to avoid that problem
i can take my user input and use the two upper function to make it uppercase or you could set these conditions to check for lowercase characters instead and use the two lower function so let's take our unit variable and i'm going to reassign it after using the to upper function and then pass in our unit to make it uppercase and now if i type in lowercase c or lowercase f this user input will be made uppercase the temp is currently in c so this is optional but i thought it'd be a good thing to add
to this program now what we'll work on next depending on the unit there's going to be a different formula a different calculation now we will need the user to enter in the current temperature so let's begin with our if statement if unit is equal to c celsius enter the temp in celsius this time we are accepting a floating point number we will use scanf the format specifier for floating point numbers address of operator temp and then we need to calculate the new temperature after it's converted from celsius to fahrenheit and we will reassign it into
the same variable temp temp equals and here's the formula temp times 9 divided by 5 plus 32 and then let's print the temperature printf the temp in fahrenheit is and i'm going to use a format specifier percent f but i would only like to display one digit after the decimal so i will add dot one and then we will insert our temperature temp okay let's try this enter the temperature in f or c currently we only have the celsius portion set up so see enter the temp in celsius how about zero degrees celsius the temp
in fahrenheit is 32.0 okay so we know that it's working let's fill out our else if statement else if unit is equal to f and let's copy some of this enter the temp in fahrenheit we will reassign our temperature variable temp equals and here's the formula temp minus 32 times 5 and we will divide all of this by 9. [Music] then let's display the temperature in celsius the temp in celsius is our format specifier then the temp variable is the temperature in f or c this time it is in fahrenheit enter the temp in fahrenheit
so 32 degrees in fahrenheit should translate to zero degrees celsius which it is so yeah everybody i thought that would be a useful practice program for us to get used to accepting user input i'll post all of this code from this program in the comments section down below if you would like a copy so if you found this video helpful you can help me out by smashing that like button leave random comments down below and subscribe if you'd like to become a fellow bro hey yeah what's going on everybody i thought in this video we
could create a simple calculator program in c for practice let's begin by declaring all of the different variables that we'll need we'll need a character to store an operator so are we going to add subtract multiply or divide we'll need double num1 double num2 and double result let's ask the user what type of operation they would like to use enter an operator so we can use addition subtraction multiplication or division and we will use scanf to accept some user input if we're accepting a character the format specifier is c and we will use the address
of operator the name of our variable we would like to store some user input into then let's accept num1 enter number one then scanf the format specifier for a double is lf num1 okay do the same thing with number two replace one with two then to examine our operator let's use a switch switch and we will examine our operator for any matching cases let's add a default case because i might forget to add this later so if a user does not enter in anything that has a matching case one of these four symbols let's print
a message let's say that our operator is not valid our first case will be edition so case addition result equals num1 plus num2 and let's display our result result and the format specifier for a double is lf and then at the end of your case you should break to break out of the switch then we can copy this paste it and then change any plus to minus then do the same thing with multiplication and lastly division and that is it so let's try this enter an operator i would like to add enter number one 4.20
plus 3.14 that is 7.34 and you can limit the amount of digits after the decimal that is displayed if you would like to adjust that with the format specifier with result type dot than the amount of digits you would like to display so i'm just going to go ahead and change that real quick okay so by adding 0.2 to our format specifier this will only display it two digits after the decimal but you can keep it the original way if you'd like okay let's subtract so minus 4.20 minus 3.14 is 1.06 okay multiplication 3.14 times
4.20 is 13.19 and lastly division 3.14 divided by 4.20 is 0.75 and we do have a default case if there are no matching cases let's type in a character besides one of these four symbols how about i don't know a dollar sign unfortunately we still need to enter into numbers and then this states our operator is not valid so yeah everybody that is a very simple calculator program in c if you would like a copy of all this code i'll post a copy in the comment section down below so this calculator can add subtract multiply
and divide there are four cases but you can expand upon this if you'd like so yeah everybody that was a very simple calculator program in c hey yeah what's going on people logical operators there are three logical operators we will discuss in the series and or and not but in this video we're going to focus on and first the and logical operator which is represented by two ampersands checks to see if two or more conditions are true here's an example we're going to create a program that will check to see if a given temperature falls
within a range so let's say we have a floating point number named temp temp short for temperature and this will equal some number in celsius let's say 25 to begin with so using an if statement let's check to see if temp is greater than or equal to zero if that is true then we will print something the weather is good else the weather is bad okay so temp is 25 therefore the weather is good okay what if our temperature is something extreme like 1000 degrees celsius so technically this condition would still be true the weather
is actually not good it's fairly catastrophic so let's check to see if another condition is also true by using the and logical operator we're checking to see if temp is greater than or equal to 0 and some other condition such as temp is less than or equal to 30. so if temp is at 1000 then the weather is bad this condition is true but this one is false using the and logical operator both conditions must be true in order to execute this statement now if our temperature was 25 degrees well then both conditions are true
and we will execute this statement the weather is good now you can add more than one condition let's throw in another variable let's say that we have a boolean variable named sunny let's say that it's cloudy outside now if we're working with booleans include this header file at the top stdbool.h then let's add another condition and let's check to see if sunny is equal to true if you're checking the value of a boolean variable you don't necessarily have to type out equals true you can say sunny is equal to one or you can just say
sunny because this would contain true or false so this time we are checking to see if temp is greater than or equal to zero and temp is less than or equal to 30 and sunny is true the temp is 25 but sunny equals false therefore we do not execute this statement these first two conditions are true but this one is false and using the and logical operator all conditions must be true now if i set this to be true well then all three of these conditions are true and we will execute this statement the weather
is good so yeah that is the and logical operator it is represented by two ampersands it checks to see if two or more conditions are true and one example we used is to check to see if our temperature falls within a certain range so yeah that is the and logical operator in the next video we will discuss the or logical operator so if this video helped you out you can help me out by smashing that like button leave a random comment down below and subscribe if you'd like to become a fellow bro hey again it's
me so we're gonna talk about the or logical operator the or logical operator which is represented by two vertical bars checks if at least one condition is true let's take the small program for example it's kind of similar to the last video so we have a variable named temperature for temperature we will first check if temp is less than or equal to zero if that's true we will print the weather is bad else if temp is greater than or equal to 30 the weather is bad else the weather is good so you know this program
does work the weather is good but another way of writing this is that we can use the or logical operator and we can check to see if at least one of two or more conditions is true so let's take this condition get rid of this else if statement so we will check to see if temp is less than or equal to zero or temp is greater than or equal to 30. so if our temperature is negative 1000 degrees celsius then the weather is bad this is true but this is false and using the or logical
only one of these conditions needs to be true if both are true that's fine as well or our temperature could be positive 1000 degrees celsius the weather is also bad this is false and this is true and only one of these conditions needs to be true but if our temperature is 25 well neither of these conditions are true at least one condition needs to be true in order to execute the statement so yeah that is the or logical operator it checks to see if at least one condition is true and you can check more than
one condition by adding another set of vertical bars for the ore operator so if you found this video helpful please be sure to help me out by smashing that like button leave her in a comment down below and subscribe if you'd like to become a fellow bro hey yeah let's discuss the notch logical operator which is represented by an exclamation point its purpose is to reverse the state of a condition let's write a small program let's say that we have a boolean variable named sunny and this will be either true or false let's say it's
true to begin with so to work with boolean variables include this header file at the top and we will write an if-else statement to check to see if it's sunny outside and print a custom message so if sunny is equal to true then we will print it's sunny outside else it must be cloudy outside so this does work it's sunny outside another way of writing this is that we could say sunny is equal to one because true represents one false represents zero this would also work or you could just say sunny this would work as
well so by using the not logical operator this will reverse the state of condition by using the not logical operator we're checking to see if something is not true so if i try this again this program states it's cloudy outside so i think it would be better if we were to switch these print statements around now what we're checking is if it's not sunny if it's not sunny then we will print it's cloudy outside else it's sunny outside it is sunny outside and if i change this to be false well then it's cloudy outside so
yeah that's the not logical operator you can just precede a condition or a boolean variable with the not logical operator and that gives you a few more options in the way in which you can write a program so yeah that is the not logical operator if you found this video helpful you can help me out by smashing that like button leave random comments down below and subscribe if you'd like to become a fellow bro hey yeah what's going on let's talk about functions a function is a small section of code that is executed whenever we
call it also known as invoking a function when we compile and run a c program we begin with invoking the main function so here's our task we need to sing three verses of happy birthday for some reason if we are only using the main function we could write it like this this will be the first verse of happy birthday and if i need to sing three verses i could just copy and paste this one section and then paste it two additional times then i'm just going to add a new line character at the end technically
this would work but it's considered poor practice to repeat code more than once if you don't have to wouldn't it be better if we write this code once and then simply reuse it well we can by using a function so let's delete two of these verses and we will create a new function so outside of the main function let's declare a new function so for now we're going to type void and then a unique name for this function let's say that it's the birthday function followed by a set of parentheses and then a set of
curly braces so i'm going to take any code i would like to repeat and place it within this new birthday function and if i need to invoke this function all i have to do is type the name of the function followed by a set of parentheses i like to think of the parentheses as a pair of telephones talking to each other that's one trick i used to remember that's how to call a function so follow the function name with the set of parentheses and when i invoke this function once we will execute any code within
this function once if i need to repeat this code three times i will just have to call this function three times we are calling our birthday function three times and there we go we have invoked this birthday function three times and we have accomplished our goal of singing three verses of happy birthday so basically that's all what a function is it's some subsection of code that is executed whenever you invoke it also known as calling a function a benefit to using functions is that if you think you're going to use some code more than once
you can stick it within a function and then to repeat that code you just call the function as many times as you need so yeah those are functions if you would like a copy of this code i will post this to the comments section down below and in the next video we will discuss arguments and parameters so yeah that's the basics of functions in c hey yeah what's going on people so let's talk about arguments and parameters i have a function named birthday which we discussed in the previous video this will print two lines of
text happy birthday dear x you are y years old what i would like to do is replace x with a user's name and y with a user's age so here's how we can write a program like that so let's begin by within the main function declaring two variables a character array named name and assign this your first name and an age and this will be of the int data type and let's say that this will be age and make up some age i like to think that i'm still 21 years old okay so if i
try and display a name and age you think this would work right so i'm going to use a format specifier then s to display a string and then i will display our name variable and with y let's display our age so let's use d for our format specifier to display an integer and we will display age now here's the problem you can see that we have some red underlines name is undeclared as well as age here's the deal functions can't see inside of other functions our birthday function is unaware of our name and age variables
one way in which we can make our birthday function aware of these is to pass them as arguments when we invoke the birthday function so based on the last topic on functions i mentioned that when we call a function we type the function's name followed by a set of parentheses i like to imagine the set of parentheses as a pair of telephones and these two functions are talking to each other our main function needs to make our birthday function aware of our name and age variables so what we can do is pass these variables as
arguments so between the parentheses we can add our variables separated with a comma so let's pass name and age so anything that you're passing to a function are known as arguments but we need a matching set of parameters within the function declaration so between this set of parentheses we will list our name and age variables but precede each with the data type that we're working with so we have name and age so age is an integer so precede the variable name with int and name is a character array so we're going to precede name with
char and then add a set of straight brackets after so these are parameters parameters are what this function needs in order to be executed so this does work happy birthday dear bro you are 21 years old so with parameter setup you can only call this function if you pass a character array as well as an integer if i were to remove these arguments we can no longer call this birthday function error too few arguments to function birthday so when you call a function you can pass some arguments but you need a matching set of parameters
and the names of these parameters don't necessarily have to be the same what's important is the order of the arguments and the data type so let's say name is x and age is y so let's replace that here as well and that would work too so yeah those are arguments and parameters arguments are what you're sending a function parameters are what a function expects when it's invoked and the benefits of arguments and parameters is that these functions can talk to each other because functions can't see inside of one another so if you have some variables
within a function you can pass them to another function as arguments so yeah those are arguments and parameters if you would like a copy of this code i will post this in the comments section down below and well yeah those are arguments and parameters in c hey what's going on people so the return statement the return statement returns a value back to a calling function here's an example i have a function named square square is going to accept one argument a double it's going to square that double and return the result back to the calling
function so here's an example let's say we have double x and i'm going to call the square function and then pass in some value let's say 3.14 so when we call a function we can also return a value back to the spot in which we call a function so within our square function let's set double result equal to x times x effectively squaring it so to return a value back to the calling function we will use this return keyword followed by some value or variable i would like to return result however we need to list
the data type of what we're returning within the function declaration right now it's void so if we're returning a double we will list double here if this was an integer we would return int if it was a character we would return char you kind of get the idea so result is a double so we need to change this from void to double and we will return this result back to the calling function so we're effectively stating that double x equals 3.14 squared and then let's print the result so printf the format specifier for a double
is lf and we will print x and 3.14 squared is 9.859 now you could shorten this too we could just say return x times x instead of declaring a local variable return x times x and that would work the same so yeah that's basically the return statement you can place it within a function and return a value or variable back to the calling function and the spot in which you invoked that function but if you're going to return a value or variable within the function declaration you need to change void to the data type of
what you're returning so yeah that is the return statement and you may have noticed within our main function we're returning zero zero is the exit status if this program runs successfully so instead of void with our main function declaration we have int because zero is technically an integer so yeah that's the return statement if you would like a copy of this code i will post this to the comments section down below well yeah that's the return statement in c hey sup people the trinary operator also known as the conditional operator it's a shortcut to using
an if-else statement when assigning or returning a value here's the formula we write a condition followed by a question mark if this condition is true we return some value if true or if that condition is false we return some other value here's an example first we'll use an if-else statement and then later we'll switch to the ternary operator so let's create a function that will find the maximum of two integers and i'm going to assign that to int max and we will invoke a function find max but we'll still need to declare it so let's
pass in two integers maybe three and four and then i'm going to display whatever max is okay so let's declare this function so we're returning an integer the name is find max and let's set up some parameters into x and int y so if we're using an if else statement if we need to return x if it's larger we can check to see if x is larger than y if so then return x else return y so this does work so the max between three and four is four so if i switch three to five
well then the max is five so a shortcut to writing an if else statement like this if we're returning or assigning a value is that we could instead use the tenary operator so let's return and then we have a condition so this is our condition is x greater than y then we add a question mark then the value we're returning if true so if x is greater than y let's return x colon then our value if this condition is false and here within our else statement we're returning y and we no longer need this if
else statement and that's all there is to it so we cut down on all that code and now just have one line of code so it's kind of like a shortcut and this works much the same so the maximum between five and four is five and if i change five back to three well then the max is for so yeah that's the ternary operator it's a shortcut to using an if else statement when assigning or returning a value you write some condition add a question mark like you're asking a question then list some value to
return if this condition is true and then some other value if this condition is false so you just follow this formula so yeah that's the trenary operator if you would like a copy of this code i'll post this to the comments section down below and well yeah that's the canary operator nc hey everybody so let's discuss function prototypes a function prototype is a functional declaration without a body before we declare the main function it ensures that calls to a function are made with the correct number and type of arguments it has some benefits which we'll
discuss later basically this is another way in which we can declare and define functions in the last few topics when we were declaring functions we were doing so before the main function so let's say void and we have a function named hello and there will be two arguments and ray of characters named name and int age and what i would like this function to do is print a message using our name and age so hello name you are age years old so what we're going to do is now move this function from before the main
function to after the main function and let's declare some name and age variables so char name use your first name and int age make up some age now i'm going to invoke my hello function but pass in an incorrect number of arguments now here's one of the benefits of a function of prototype it's going to ensure that we have the correct number of arguments when we invoke a function so the correct arguments for our hello function are an array of characters and an integer what if i'm missing one of these arguments let's say we only
pass in a name and then invoke this function so this is going to result in unexpected behavior and we do have a warning here conflicting types for hello but this program will still compile and execute so here's the result hello bro you are million five hundred twelve thousand three hundred and fifty two years old and if i run this again this will probably be a different number so this will result in unexpected behavior we're not ensuring that calls to a function are made with the correct arguments one way in which we can do that is
to add a function prototype before the main function and to add a function prototype to a given function we will declare that function but not give it a body before the main function and then we will later add a body and define what this function is going to do so before the main function we will type the return type of this function void the name of the function hello and then add the data type and the order of arguments so we have a character array and an integer then end it with a semicolon so this
is a function prototype it ensures that calls to a function are made with the correct arguments so now if i attempt to call the hello function with only one argument when two are required instead of a warning we'll receive an error and it states that there are too few arguments to function hello so this program will not compile and run successfully which is what we want because we made a mistake and if i were to add the correct arguments now well then this program is going to compile and run fine so here's some important notes
regarding function prototypes many c compilers do not check for parameter matching that's why this program was still able to compile and run without a function prototype even though we were missing arguments and that can result in unexpected and unwanted behavior such as saying that i was over a million years old so a function of prototype causes the compiler to flag an error if arguments are missing you can write the functions before the main function that's okay too but a few advantages of using a function prototype is that it's easier to navigate a program when the
main function is at the top of your file it also helps with debugging and it's commonly used in header files which is something we need to discuss in a future topic so yeah that's basically a function prototype we're going to define any functions after the main function now and before the main function we will declare a function prototype one function prototype for each function we have besides the main function and this ensures that we have the correct number and type of arguments which will prevent any unexpected behavior it's basically just another way to declare functions
that you may run into in the future so yeah those are function prototypes if you would like a copy of this code i will post this to the comment section down below and well yeah those are function of prototypes in c hey everybody so now that we know how functions work i thought this would be a good opportunity for us to learn about some useful string functions so there's a lot of string functions that are already written for us just include this header file at the top include string dot h so create two strings one
named string one and the other named string two string one will be your first name string two will be your last name and then at the end of this program i am just printing string one using a printf statement so let's begin the first useful string function is string lower so whatever string you pass in as an argument this function will convert a string to lowercase so the first letter in my name is uppercase it's capitalized so after passing in string1 into this function my name is all now lowercase otherwise there's string upper that will
convert a string to uppercase and my name is uppercase stringcat will concatenate as in append string2 to the end of string1 so we will append the second argument to the first argument so if i pass in string one then string two this will append my last name to my first name and these strings are now combined or i could append a given amount of characters from string two to string one so the third argument is a number if i append one character from string two to string one then this will take the c from my
last name and append it to the end of my first name so that is the string and cat function there's also string copy and this one is actually fairly common so this will copy string two to string one if i print string one well it now displays code instead of bro this will remove the contents from string one and replace them with string two or you could copy a given amount of characters from string two to string one uh let's say that i'm going to copy the first character over so i'm copying the first character
from my last name to my first name and my first name is now crow or i could set this to two and this will copy the first two letters over coo all right here's a few more so string set will set all characters of a string to a given character i'm going to set all of the characters from string 1 to a question mark all of the characters within my name are all question marks and string and set will set the first and characters of a string to a given character so i'm going to set
the first character of my first name to an x so my name is now x bro and string reverse will reverse a string so if i reverse string one my first name is now orb so this next set of functions will return an integer so i'm going to declare a variable int result and this function is really common string length this returns the string length as an integer if i pass in string one this string has a length of three characters and then i'm going to print my result and this is an integer so the
length of my first name is three characters this is a fairly common function the string compare function will compare all of the characters within two strings if they're the same they will return zero if they're different they will return a number beside zero so here's an if statement if result is equal to zero we will print these strings are the same else these strings are not the same so my first name is not equal to my last name these characters are different so this code will print these strings are not the same and let me
get rid of that printf statement okay now if i make the strings the same then result is going to be zero these strings are the same and you can compare a given amount of characters too so currently i have these strings set to be the same characters so this will compare only the first character these strings are the same even if i change the other characters the first characters will still be the same so this function will return zero there are two additional versions of string compare and string and compare they are string compare i
and string n i compare so these will do the exact same things except they ignore case sensitivity so yeah everybody those are just a few useful string functions there's still a lot more located within this header file but we would need to understand how things like pointers work which we have not discussed yet but i thought i would at least cover some of the basics so yeah those are a few useful string functions in c if you would like a copy of all these notes i'll post them to the comment section down below and well
yeah those are a few useful string functions in c hey yeah welcome back so we have to talk about for loops a for loop repeats a section of code a limited amount of times here's an example let's say that we would like to count the numbers 1 through 10. so we can actually write a for loop to do that for us and here's how to create one type four a set of parentheses then a set of curly braces anything within this set of curly braces we can repeat a limited amount of times but before we
do so there's a few statements we have to add to our for loop there are three the first is that we need some sort of counter or index and we can actually declare that within the for loop so we will declare an index int index and set the sql to some number let's say one so we will start at one and count to ten and then finish the statement with a semicolon now a common convention is that a lot of people will shorten index to i because it's easier to work with so this is the
first statement there's two more and the second statement is a condition how long should we continue repeating this code so let's continue this for loop as long as i our index is less than or equal to 10 and then add a semicolon at the end so that is the second statement and the third statement is that we can increment or decrement our counter so let's take i and increment it by one after each iteration by using i plus plus so let's just test this so printf i'll just print the word test so this should print
the word test ten times uh then we should add a new line character at the end that's much better okay now let's replace test with a format specifier we're displaying an integer and let's display i our index and this should count from one to ten yep just like that one through ten so with this third statement we can increment or decrement by one or a greater number so this time let's count by two so we can set this to i plus equals two and we will now count up by two starting from one one three
five seven nine or how about three one four seven ten you can also decrement this time let's count from ten to one so let's set i to equal 10 and we will continue this as long as i is greater than or equal to 1 and we will decrement i minus minus so this will count from 10 to 1 and then stop or we could count down by two i minus equals two then we have ten eight six four two or even three or a greater number so yeah that's a for loop it repeats a section
of code a limited amount of times there's up to three statements that we can add we can declare an index a counter so to say some condition that we check after each iteration and then some way to increment or decrement our index and then place any code you would like to repeat within a set of curly braces so yeah that's a for loop if you would like a copy of this code i will post this to the comment section down below and well yeah those are for loops in c all right we're back at it
again so let's talk about while loops a while loop will repeat a section of code possibly unlimited times we will continue some section of code while some condition remains true and it's possible that a while loop might not execute at all depending on what our condition is so here's an example let's create a program that will ask a user for their name if they attempt to skip that prompt then we will keep on asking them for their name indefinitely so here's how we can write a program like that using a while loop we'll need to
begin with a character array let's say name and this will be 25 bytes and we will create a prompt using printf what's your name we can use scanf for user input but with names that may contain spaces i'm going to use fgets instead refer to the video on user input to learn more about fgets so i would like to assign my variable name set the size of the user input 25 to match what we have then type stdn for standard input then we just need to get rid of the new line character at the end
of our user input so we can write something like this set our character array of name and within the straight brackets we will use the string length function pass in name -1 and we will set this equal to a null character and then at the end we will display the user's name printf let's say hello and then use a format specifier for strings which is s and we will display a user's name okay this is what this looks like currently what's your name i'll type my name hit enter and it says hello bro now what
if i don't type in anything like i just hit enter what's your name i'm going to hit enter hello and then there is no name here how can i force a user to type in something well i could use a while loop and that will prompt a user to enter their name indefinitely so here's how to create a while loop type while parentheses curly braces and we need a condition what are we going to check we will continue this while loop while some condition remains true our condition to check to see if we have an
empty string we could use the string length function pass in name and check to see if this is equal to zero if it is zero that means that somebody just hit enter without typing in anything so let's print a message to yell at them you did not enter your name and then let's copy this section of code and paste it to reprompt the user to type in their name and that's all there is to it so while this condition remains true we will execute this code forever so let's try it again okay what's your name
i'm going to hit enter you did not enter your name what's your name no no no no okay i give up hello whatever your name is so yeah that's basically a while loop it repeats a section of code possibly unlimited times there's a lot of overlap where you could use either a for loop or a while loop and we execute some body of code while some condition remains true however a while loop might not execute at all if this condition is false to begin with so if the user actually does type in something well this
condition is false and we do not execute this body of code so yeah that's a while loop it repeats a section of code possibly unlimited times if you would like a copy of this code i will post this to the comment section down below and well yeah those are while loops in c hey everybody so let's talk about do while loops a do while loop is a variation of a while loop so a while loop first checks a condition then it executes a block of code if that condition is true so we may not even
execute that block of code at all if that condition is false from the get go a do while loop always executes a block of code once and then we checking condition at the end if that condition is true we will continue another loop so here's what i'm thinking for a demonstration we'll create a small program where we will have a user type in as many numbers as they want as long as it's above zero and then we will find a sum so if we're writing a program like that we can first declare two variables int
number i'll go ahead and assign these some values right away so we'll set number to zero and int sum equal to zero as well to keep track of the sum we'll first begin by creating a while loop so we will use a while loop and our condition is if number is greater than zero then we will continue to ask the user to type in some numbers if that number is zero or less then we stop so let's ask a user for a number enter a number above zero and then using scanf we will accept some
user input and store this within number and let's check to see if number is greater than zero if it is we will take sum set this equal to sum plus number but you can just shorten the statement to plus equals number that's fine too and then at the end we will print whatever the sum is sum we're displaying an integer and we are displaying some so with our number i set this to zero and since our while loop is checking the condition first we're not actually going to execute this body of code so our program
skipped this while loop and went straight to the printf statement so a while loop checks a condition first a do while loop will check a condition last so to change this to a do while loop we will take our condition and move it to the end just after the last curly brace and add a semicolon and then before the first curly brace we will add the word do so we will do this once and then check the condition to see if we would like to continue so now if i run this we get that prompt
enter a number above zero and i can type in as many numbers as i want so one two three four five so we check the condition at the end so our condition is that if our number is greater than zero we will continue this loop so if i type in negative one we will exit and our sum is 15. so that's the major difference between a while loop and a do while loop a while loop checks a condition first then executes a block of code if that condition is true a do while loop always executes
a block of code once then checks a condition if that condition is true then we continue again so yeah that's a do while loop it's a variation of a while loop and if you would like a copy of this code i'll post this to the comments section down below and well that's the do while loop in c hey welcome back so nested loops a nested loop is a loop inside of another loop when you'll encounter them it's really situational so i don't really have one good example but what i'm thinking we'll do is use a
nested loop for an exercise what i'm thinking is that we'll let a user type in a number of rows and columns and a symbol and print a rectangle of that given symbol but the user is going to specify a number of rows and columns so let's begin by declaring all of the different variables that we'll need intros and columns and char symbol we'll let the user type in a number of rows and columns enter number of rows then use scanf to accept some user input we are accepting an integer so use d for the format
specifier address of operator rows then do the same thing with columns enter number of columns let's create our nested loops you can use either for loops or while loops it's just the concept of one loop inside of another so let's use for loops for our outer loop and inner loop the outer loop is in charge of keeping track of the rows the inner loop will be in charge of keeping track of the columns so i need this outer for loop to iterate once for every row that we have so we could write something like this
int i set this equal to one i need to continue this for loop as long as i is less than or equal to rows and then increment i by one after each iteration so now let's create a nested for loop we will declare a loop inside of another loop and this inner for loop is in charge of the columns we should probably not reuse our index of i so let's create a new index and a common naming convention for an inner for loop is to use j because j comes after i in the alphabet so
i will set int j equal to one we will continue this as long as j is less than or equal to columns then increment j by one for the time being until we let a user type in a symbol let's just print our index so let's use printf we're displaying an integer and let's display j and let's take a look at this okay enter number of rows how about 3 rows and five columns so here's our output we have the numbers one through five three times so to make this more of a rectangle a grid
i'm going to add a new line character whenever we finish a row so printf newline character let's try that again enter number of rows three number of columns five so we have three rows and five columns basically speaking to complete one iteration of our outer loop we have to escape our inner loop first once this condition is no longer true then we will escape the inner loop and complete one iteration of the outer for loop but then once we begin in the next iteration of our for loop we're stuck back within our inner for loop
again so that's kind of the concept now this time let's let a user type in a symbol and we will create a sort of rectangle enter a symbol to use then scanf we are accepting a character so use the c format specifier address of operator our symbol variable now we're going to replace j with our symbol and the format specifier for a character is c then let's try this again so how about three rows and six columns okay here's the issue so we have all of this empty space now when we entered our number of
columns after hitting enter we have the new line character within our input buffer so our next scana function actually picked that up so what we need to do is clear our buffer and one simple way of doing that there's a couple different ways is that we can just use scanf again and we will read a character and that's one way to do it basically with this line we're just getting rid of the new line character after the last time we use scanf because that's still within our buffer okay let's try this one last time what
about four rows and five columns enter a symbol to use uh how about the dollar sign there we go here's our rectangle it has five columns and four rows so yeah that's basically a nested loop it's a loop inside of another loop and when you'll encounter them it's really situational i thought this would be good practice to understand how they work to complete one iteration of the outer loop you have to first escape the inner loop and that may involve completing all iterations of the inner loop so yeah those are nested loops if you would
like a copy of this code i will post this to the comment section down below and well yeah those are nested loops in c hey people i have a super quick video for you today on the differences between the continue and break statements so when using either statements within the context of a loop a continue statement will skip the rest of a section of code and force the next iteration of a loop a break statement will exit out of a loop entirely another place where you see break statements is when used within a switch after
each case so here's an example let's say that we would like to count the numbers 1 through 20 but i would like to skip the number 13 because 13 is considered an unlucky number so if i were to write a program like that that would look something like this so let's use a for loop and i will set an index of i equal to one continue this as long as i is less than or equal to 20 and then increment i by one then let's print our index so printf we're displaying an integer and let's
display i i'm just going to add a new line character after each iteration when we use a printf statement okay so this is what this looks like we have the numbers 1 through 20. so if i would like to skip the number 13 i can use a continue statement but we need to check to see if i is equal to 13 we can use an if statement so if i is equal to 13 then we will continue and let's take a look so we have the numbers 1 through 20 but we are missing 13 so
a continue statement will skip the rest of a section of code and force the next iteration of a loop now if this was a break statement this will break out of our loop entirely so once we reach 13 then we will exit out of this loop entirely so here we only have the numbers 1 through 12 and then we break we exit out of the loop so that's a quick demonstration of the differences between continue and break the continue statement will skip the rest of a section of code and force the next iteration of a
loop a break statement exits out of a loop entirely so yeah that's a super quick video on the differences between the continue and break statements if you would like a copy of this code i'll post this to the comments section down below and well yeah those are the major differences between the continue and break statements in c hey everybody let's talk about arrays an array is a data structure that can store many values of the same data type here's an example let's say i have a variable named price and i have the price of maybe
one item in a fictional store of ours so by using an array we can actually store more than one value but it has to be of the same data type so i can turn this variable price into an array and i can do that by following the name of the variable and add a set of straight brackets and then any values i would like to add to this array i will surround with a set of curly braces and there we go we have turned our variable price into an array but i'm going to change the
name to prices because i think it would be more descriptive because we can store more than one value now so we can add multiple values each separated with a comma so let's say we have another price that is 10 15 25 and maybe 20. now you may have noticed some parallels when we create a string it's really an array of characters so if i need a name we would say the data type is char and we will create a name array followed by a set of square brackets and i will set this equal to some
amount of characters a string is really just an array of individual characters and with my name here i have three individual elements three individual values now if i need to access one of these values i need to use an index number so let's print one of these numbers so printf i'm going to use the format specifier for a double and i'm going to list my array name prices then follow this with a set of straight brackets then i need an index number so each spot within an array is known as an element so we have
five elements within our array and to access one of these elements i need to list an index number the first element has an index number of zero because computers always start with zero so if i display prices at index zero this contains the number five i'm actually going to format this let's display it two digits after the decimal and i'll precede this number with a dollar sign much better all right so then if i display prices at index one that is technically our second number of ten dollars so prices at index two is fifteen three
is twenty five and four which is our last element is twenty so arrays they have a fixed size we can't change the size after we compile and run our program another thing that you can do too if you do not know what values you would like to initialize your array with you can always just set a size let's say i would like a size of five elements but then i'll assign some values later so later on in our program we can say prices at whatever index let's say index zero i'm going to assign with five
and i'll do the same thing for the other elements so prices at index one is maybe ten prices at index two is fifteen three will be twenty five and 4 will be 20. that's another way in which you can initialize an array you can always set a size and then add elements later another option is that you could combine the two we could set a size right away so maybe prices will have a size of 10 and we can right off the bat assign some values right away so we have five elements that are currently
filled but then the other five are empty so there's a few different ways in which you can initialize an array so yeah that's basically an array it's a data structure that can store many values of the same data type initializing an array is much like creating a variable except you will add a set of straight brackets after and then you can either add some values right away or later on in your program but you need to list an index number of where you're placing a value within the array and then to access a value within
your array you type the array name followed by an index number kind of like a parking spot number so yeah those are arrays in the next video i'm going to show you how we can iterate over the elements in an array using a for loop if you would like a copy of this code i will post this to the comments section down below and well yeah that's an introduction to arrays in c hey welcome back everybody in this video i'm going to show you how we can loop through and print the elements of an array
so i have an array of doubles named prices and i just made up some fictional prices to display one of these elements i can use a printf statement i will use the appropriate format specifier for the elements displayed within this array since this array contains doubles i will use the format specifier for a double then to access one of these elements i will type the name of my array followed by a set of straight brackets then an index number so the first element in an array is zero because computers always start with zero then if
i need to display the other elements well i would have to manually type prices at index zero then one two three four so on and so forth so this does work if you have a couple elements but what if you have hundreds this method is not going to be practical a better solution is that we could make a for loop and this for loop will iterate once and display each element of this array so let's create a for loop for parentheses curly braces and we'll need an index int i i'll set this equal to zero
then we'll need a condition for the time being let's set i less than five but later on we're going to replace five with something else and i'll explain that later and then we will increment i by one so then during each iteration let's use this print statement again and make one change instead of setting an index number let's use our index instead then i'm just going to add a new line character after each printf statement so here we go this for loop should iterate five times and it will display the elements within our array so
we have 5 10 15 25 20. maybe i'll add a couple extra things to this format specifier let's display two digits and a dollar sign that's much better so this kind of resembles maybe a receipt of some sort like somebody just bought a bunch of items okay now here's one situation what if we add or remove elements from this array let's say that a user purchases one more item for thirty dollars now the way that this for loop is written it's not going to display this last element because we set this for loop to iterate
as long as i is less than or equal to five it's not going to display this last element so we would need some way to update this condition a better solution instead of using a number here is that we could calculate the amount of elements within our array and loop that many times and one way in which we could do that is to use the size of operator so let me demonstrate the size of operator real quick it will return the size of an operand in bytes so let's print this so this will be an
integer and we will use the size of operator and pass in our array of prices so this size is going to be in bytes so the size of our ray in bytes is 48 bytes we have six elements made up of doubles each double uses up eight bytes so six times eight is 48 so now let's use the size of operator instead size of prices but we are going to divide the size of our array by the size of one of these elements they're all going to be consistent because they all have the same data
type so we will take size of prices divided by the size of one of these elements let's say prices at index zero so 48 divided by eight equals six we will iterate through this for loop six times and here's our array we have 5 10 15 25 20 30 and we can add or remove elements freely and there's no need to update our code because we may not remember to do that later on so yeah that's one way to loop through and print the elements of an array you can use a for loop then use
a printf statement and for the index of your array you can use the index of your for loop then if you would like your for loop to calculate how many times it's going to iterate through this array you can use the size of operator pass in prices divided by the size of one of the elements and that will calculate how many elements are within your array so yeah that's one way to loop through the elements of an array if you would like a copy of this code i'll post this to the comment section down below
and well yeah that's how to loop through and print the elements of an array in c hey everyone two dimensional arrays it's an array where each element is an entire array it's useful if you need a matrix grid or table of data let's begin by creating a simple one-dimensional array of maybe some numbers so the data type is int the array name will be numbers and let's initialize this array with a few numbers 1 two and three something simple so if i would like to store a grid or matrix of data these elements will be
the first row and i can add a second row so separate each row with a comma then another set of curly braces and then you can add more values so let's say four five and six and we'll stop here with these separate arrays we will surround with a set of curly braces and preceding the first set of straight brackets we will add a second set of straight brackets so this is now a two dimensional array however with a two dimensional array we have to specify a maximum size of elements within each of these arrays let's
say that each of these arrays will have a maximum size of three elements a piece so within the second set of straight brackets i will list three and you can although it's not necessary set a maximum amount of arrays within your two-dimensional array so let's say two because we have two separate arrays within our two-dimensional array now to better visualize how this is more or less a table of data i'm going to rearrange these so this may be a better visualization this first set of straight brackets is for the number of rows and the second
set of straight brackets is for the number of columns so we have two rows and three columns within our two-dimensional array now you can declare a two-dimensional array but not assigned values quite yet but you'll need to set a maximum size so right now i'm just going to turn this into one giant comment and let's declare a two-dimensional array with two rows and three columns and here's how to assign some values we will type the name of the array followed by two sets of straight brackets we need a row number and a column number so
the first column within the first row is going to be zero zero because computers always start with zero and let's assign this a value of one the second column within the first row would be zero one and let's assign two there then zero two and that will be number three so the first column within the second row would be numbers one zero and this will be four then we will follow the same pattern so where five was that would be one one and six is one two so this is another way to initialize an array
you can set a maximum size and then assign some values later or you could assign all of the values right from the beginning if you know what they are okay now how can we display the elements of a two-dimensional array we'll have to use nested loops so let's create a for loop and i will declare an index of i set this equal to zero and for the time being i'm going to say i is less than the number of rows that we have so right now we have two rows but we're going to change this
value later to something that's more flexible that will calculate the amount of rows that we have and then i will increment i by one now let's create a nested loop that's in charge of keeping track of the columns and let's use an index of j because we do not want to reuse i so set j equal to zero we will continue this as long as j is less than however many columns we have three a maximum of three and then increment j by one so during each iteration of the inner for loop let's display one
of these elements so we will use the format specifier for an integer d is fine followed by our array numbers and then we have two indices so the row is going to be i and this will begin at zero and the columns is j this will also begin at zero so after each iteration of the inner for loop we will increase j when we finish the inner for loop we will increment i by one so by using nested for loops we can iterate over all of the elements of this array so i'm just going to
add a space after our number and we should probably add a new line after each row so i'll add a new line let's test this here we go we have our table of two rows and three columns now there's one situation that we may run into what if we change the amount of rows and columns that we have so let's say that we add one more row our 2d array of numbers will have three rows and three columns row two column zero equals seven row two column one will equal eight and row two column two
will equal nine so if i were to run this again well this last row is not going to be displayed so it would be better if we can calculate how many rows and columns are within our two-dimensional array and here's one way to do so i'm going to declare two new variables int rows and into columns and i will set the condition of the outer for loop to be as long as i is less than rows and the inner for loop will be j is less than columns now we just need to calculate what these
numbers are going to be to calculate rows we can use the size of operator and then pass in the entire size of our two-dimensional rib and we're going to divide this by the size of one of our rows they're all going to have the same size so we can pass in our rain numbers and then specify one of the rows let's say the first row they're all going to be the same okay so that's how we can calculate the number of rows that we have now to find the number of columns we can copy what
we have here and then just make a few changes so we will say the size of the first row row 0 divided by the size of one of the elements found within the first row so we can say zero zero and let's print the amount of rows and columns that we have just to test it so we have rows and columns i'm just going to add a new line character real quick okay so we have three rows three columns and here's our table three rows with three columns a piece so yeah that's basically a two-dimensional
array it's an array of arrays where each element is an entire array it's useful if you need a matrix grid or table of data and in this example we made a table of integers just the numbers one through nine so there's a couple different ways in which you can initialize a two-dimensional array but you'll need two sets of straight brackets it's optional to set a maximum number of rows but it is necessary to set a maximum number of elements within each row and then to access one of the elements you use two indices one for
the row one for the column so yeah those are two dimensional arrays if you would like a copy of this code i'll post this to the comment section down below and well yeah those are two dimensional arrays in c hey everyone in this video i'm going to show you how we can create an array of strings let's say we will have an array named cars so we will need a two-dimensional array so we need two sets of straight brackets and within the second set of straight brackets we will specify a maximum size for each of
these elements let's say maybe 10 characters so a string is already an array of characters let's add our first string maybe we have a mustang so to add a second element we would separate the next one with a comma then we can add another string let's say we have a corvette and then one more how about a maybe camaro okay so with all of these different strings i'm going to surround with a set of curly braces and here we go we have an array of strings it's basically a 2d array of individual characters except each
element is a string now one important difference with an array of strings is that we can't directly change one of the values let's say car's at index zero equals a tesla and then i'm going to try and run this so we can't directly assign a new value one way in which we can do so is to use the string copy function so if you're going to use the string copy function include this import string dot h okay so to update one of the values i will use string copy pass in my array and an index
number followed by a string so let's say a tesla and this would work now to display an array of strings we can use a for loop and there's no need for a nested loop so we will create an index i set this equal to zero i would like to continue this as long as i is less than and we will calculate how many elements are within our array so we will use the size of operator pass in our array divided by one of the elements size of cars and maybe the first element of zero and
then increment i by one during each iteration so then during each iteration let's display one of these elements using a printf statement let's display a string i'll add a new line after each printf statement and let's display our array cards at index of i so this should display tesla corvette and camaro in that order tesla corvette and a camaro so yeah that's an array of strings it's really a two-dimensional array of characters but it involves less steps because each of these strings is already an array and if you need to update or edit one of
the values you can use the string copy function so yeah that's how to work with an array of strings if you would like a copy of this code i'll post this to the comments section down below and well yeah that's how to work with an array of strings in c all right what's going on people so in this video i'm going to show you how we can swap the values of two variables now you may be wondering why the heck do we need to know this so swapping variables is actually very common within sorting algorithms
and when we reach the next topic on sorting arrays we'll need to learn how to do this so let's begin i have two variables x and y x contains the letter x y contains the letter y and let's print these values i'll use a printf statement let's display x and y x equals x y equals y so how can we swap these let's try x equals y and see what happens within both x and y the value is y what about y equals x well then both variables contain the character x so what can we
do it seems like we're stuck what we could do is that we could introduce a third variable let's say char and let's name this temp because it's a temporary variable so we have a third variable to work with as temporary storage for some value so let's assign temp is equal to x and then we will assign x equals y and then lastly y equals temp and this should work let's try it yep x equals y and y equals x now this is a little bit different if you're working with strings so let's say these are
character arrays and we'll pretend that these are maybe glasses holding some fluid x contains water and y contains maybe lemonade and let's make temp a character array as well but we need to declare a size let's say 15. okay so this isn't gonna work we're already receiving problems expression must be a modifiable l value so when working with arrays it's not enough to simply assign values we could use the string copy function so let's get rid of these and we will use string copy oh also make sure that you include this header file okay so
we will copy the contents of x over to temp and it's the same procedure as before string copy y over to x and string copy temp over to y and then make sure you change these format specifiers to strings x did contain water now it contains lemonade y did contain lemonade and now it contains water when swapping variables i like to imagine my variables as glasses and they contain some fluid if we pour the contents of one glass into the other well then the contents will be pushed out and overflow so it would be wise
of us to introduce a third glass that's empty to hold one of these fluids so then we can pour the contents of one variable into the other now here's one issue that you may run into when using the string copy function if the length of the second argument is less than the first argument this can lead to unexpected behavior i'm going to replace lemonade with soda and let's see what happens so x doesn't contain anything but y contains water one solution is that we can make these character arrays the same size let's say that they're
both 15 and that should solve that issue so that's something you may need to take into consideration when using the string copy function if you're going to swap strings so yeah everybody that's how to swap the values of two variables if you would like a copy of this code i'll post this to the comment section down below and in the next video i'm gonna show you how we can sort the elements within an array and well yeah that's how to swap the values of two variables in c hey uh what's going on people so in
this video we're going to write a small program to sort the elements of an array let's begin with an array of integers and then later we'll create an array of characters the data type will be int and let's name this array and assign some values make sure that they're not in order just make up some numbers that's fine looks good to me now let's calculate the size of our array because we'll need to know how many times we're going to iterate through our array so int size i will set this equal to the size of
operator pass in our array this will calculate the size of our array in bytes and to find the number of elements we can divide this by the size of just one element so size of array divided by the size of array at index of zero size will equal the amount of elements within our array and just to keep this code more organized let's declare a function to actually sort all of this for us so we don't have to do that within the main function so let's declare a sort function the return type is void we're
not returning anything and let's name this sort and there will be two parameters an array of integers and integer size and let's invoke this function we're invoking sort and then we need to pass in two arguments our array and a size within the sort function we'll need nested loops we can use four loops so the outer for loop will be int i set this equal to zero and we will continue this for loop as long as i is less than the size of our array minus one and then increment i by one and then we
need an inner for loop so let's copy our outer for loop paste it and make a few changes so the index for the inner loop will be j and we'll continue this as long as j is less than the size of our array minus one then j plus plus here's what we're doing within our array so we will begin at our first index we're checking to see if the element on the left is greater than the element on the right if so we're going to swap these two values and we'll need the help of a
temporary variable much like what we learned in the last topic so let's check to see if the element on the left is greater than the element on the right if it isn't we do nothing so we need an if statement if array at index of j is greater than array at index of j plus one we're adding plus one because we're checking the element directly next to the one that we're currently examining so if the number on the left is greater than the number on the right we will perform a basic variable swap so let's
declare a variable in temp to temporarily store some value and i will set the sequel to array at index of j now i need to move the element on the right over to the element on the left array at index of j equals array at index of j plus one and then lastly whatever's within temp i'm moving that to the element on the right so array at index of j plus one equals temp and that's it so if you would like to optimize this you can set size minus i minus one basically this is a
bubble sort so depending on the size of this number it's going to find a final resting place since 9 is going to be the largest it's going to be pushed all the way to the right because we will examine 9 against each of these numbers so once 9 is pushed all the way to the right all these other numbers that are less than 9 will be on the left so it's already partially organized and now we just need some way to display the elements of our array so let's declare a print function void and let's
name this print array and these will have the same parameters an array of integers and into size and this is a basic for loop so for and i set this equal to zero we will continue this loop as long as i is less than the size of our array and increment i by one and i would like to display each integer and maybe i'll separate these with the space and we are displaying our array at index of i and all we have to do is invoke the print array function and then pass in our array
and our size and let's take a look fingers are crossed oh yeah there we go our array is now sorted now if you would like this in descending order all we have to do is switch this if statement around from greater than to less than and our array is sorted in reverse order and we could sort an array of other data types too this time let's sort an array of characters so let's declare an array of characters this time and make up some characters so then to sort an array of characters let's change the data
type of our array to characters and then when we display each character make sure that we're using the c format specifier because we were using d before and this should now be sorted yep so that's currently in reverse order so then to switch that around just change the sign all right there you go so yeah everybody that is a simple program to sort the elements of an array this is a basic bubble sort and if you're interested in learning more about sorting algorithms i do have a playlist on data structures and algorithms if you would
like a copy of this code i'll post this in the comments section down below and well yeah that's how to sort a simple array in c okay everybody so let's talk about structs a struct is short for structure think of it as a collection of related members kind of like variables they can be of different data types unlike with arrays structs are listed under one name in a block of memory in order to refer to that struct we can refer to a variable name and then we have access to that block of memory that contains
related members and lastly structs are very similar to classes in other languages if you're familiar with more than just c you'll probably know what a class is but there are no methods within a struct it's only members so we can actually use structs to mimic real world objects let's say that maybe we're playing a game and we need two players each player will have a name and a score these will be the members so to create a struct outside of our main function we will type the keyword struct followed by a tag name let's say
we are working with players then we need a set of curly braces then end it with a semicolon so any members think of these like variables so let's say we have a character array named name and i'll give this a size of maybe 12. so we will declare these but not assign them we'll do that later and we have an int named score so each player is going to have a name and a score kind of like we're playing an arcade game now to assign some of these values we're going to create a type of
variable and a player is going to be kind of the data type so we will type struct then the tag name which was player and then a variable name let's say we have player 1 and player 2. so with these structs you can reuse them so we have struct player player 1 and struct player player 2. so we can assign values to these members however if we have an array of characters we're going to use the string copy function so let's use the string copy function then to access one of the members you will type
the name of that struct so let's say player one and then follow this with a dot the dot is a member axis operator so after typing the dot we have access to a name and score member so let's set the player's name equal to whatever your first name is now if you're not working with an array of characters such as an integer you can just access these directly so let's set player one's score two equal maybe four points and we also have player two but we have not assigned values to its members so this time
let's assign player two's name and score so we can just copy what we have but change player 1 to player 2. player 2 let's say is bra and player 2's score is 5. now if i would like to display these members i can do so with a print statement so printf let's display our name first so i will use the s format specifier player one dot name and then i'll add a new line then to access player one's score well that's an integer so i will use the d format specifier player one dot score and
then let's do the same thing with player two so player two dot name and player two dot score so we have our player one strucks name member as bro and score member set to four and then our player two struct has a name member of bra and a score member of five so yeah that's basically a struct it's a collection of related members think of these kind of like variables they can be of different data types unlike arrays and they are listed under one name in a block of memory so in this example we have
player 1 and player 2. player 1 and player 2 refer to different blocks of memory which contain their own unique members if you're familiar with other programming languages they're very similar to classes but they cannot contain any methods so yeah those are structs if you would like a copy of this code i'll post this to the comment section down below and well yeah those are structs in c all right typedef typedef is a reserved keyword that gives an existing data type a nickname here's an example let's create a character array of 25 bytes and we'll
say that this is user one so character user one and the size is 25 bytes and then make up some username okay so writing some of the syntax can be somewhat tedious what a lot of c programmers will do is that they will use this type def keyword to give some data type a nickname let's use this type def keyword to give a character array of 25 bytes some nickname so i'll do this outside of the main function we will type type def then our data type so this is a character array of 25 bytes
and we need some sort of nickname so let's say that a character array of 25 bytes will be known as a user now i don't need all of the syntax now i can type my data type user and then some variable name let's say user one from this point forward if i need a character array of 25 bytes i can call that a user that's my nickname now one place where you see this used a lot is with structs this time let's create a struct at first we won't use the typedef keyword and then i'll
show you the benefits later so let's say this is a struct and the tag name is user users will have let's say three members a character array named name of 25 bytes a password of 12 bytes and int id like an id number so to create a struct we would have to type struct then the tag name user and a variable name and let's assign some of these values i'll assign a name password and id looks good to me okay then if i need to create user two i would type again struct user some unique
variable name and make up some values okay so with a strut if i would like to use the typedef keyword i will precede the struct keyword with typedef and i don't necessarily need this tag name and after the last curly brace here i will add my nickname i'll call this a user if we need to create a user struct we no longer need to use the struct keyword we can remove this and this should work so let's print some of these members and here are the two users that we created yeah so in conclusion typedef
is a reserved keyword that gives an existing data type a nickname and it's mostly used for convenience if we use the typed up keyword when declaring a struct we no longer need to use that struct keyword to create a struct we can just use this nickname as the data type and then come up with some unique variable name so yeah that is the typedef keyword if you found this video helpful please be sure to give this video a thumbs up leave a random comment down below and subscribe if you'd like to become a fellow bro
hey everybody so in this video i'm going to show you how we can create an array of structs let's say we're working with students and we need to print each student's name and gpa so let's create a struct outside of our main function type struct and then a tag name for the struct let's say student so each student will have a name and a gpa so let's create a character array named name i'll set a maximum size of maybe 12 characters and a gpa that could be a float so float gpa now let's initialize some
structs we type struct followed by the tag name and then some variable name to identify each struct so let's say we will have four students overall and i'll go ahead and assign some values right away when we initialize the struct so we need a name and a gpa so the first student let's say is spongebob and spongebob has a gpa of 3.0 so we can copy this and create a few more students so student one student two student three and student four next we have patrick patrick has a 2.5 then sandy sandy is smart so
she has a 4.0 and squidward squidward has a 2.0 so we have four students now we will create an array so the data type of our array what it's containing will be struxx it will be struct student it's kind of like the data type so with an array you have to declare what you're going to be putting within the array struct students and then we need an array name so this will be students and then specify a maximum size if you need one but i'm just going to initialize this array with some students so let's
add student 1 student 2 student 3 and student 4 and there we go we have an array of structs now if i would like to display each student's name i can use a for loop to loop through our array so for curly braces we will create an index into i set this equal to zero we will loop through this as long as i is less than and then we need to calculate how many elements are within our array so we have four elements but we can do that by using the size of operator passing our
array and then divide this by the size of one of these elements size of students and then pick maybe the first element of zero after each iteration we will increment i by one so then within our for loop let's print each student's name so let's use the s format specifier to display a string and we will display our array at index of i whatever our counter is and we will use the member axis operator of dot so follow students at index of i with a dot then we have access to a name and a gpa
so let's display each student's name and then i'll add a new line after each printf statement so there we go we have spongebob patrick sandy and squidward now let's display each student's gpa so let's copy this line we are displaying a float so the format specifier for a float is f students at index of i dot gpa then i'll get rid of that new line character and let's take a look to see what we have okay we can see each student's name and gpa but we may want to format this so after each student's name
i'll add a tab and i'll allocate maybe 12 characters to display each student's name and then left justify it and then with our gpa let's display two digits after the decimal so i will add dot 2 so this should look better yeah that's much more organized so we have spongebob with the gpa of 3.0 patrick with 2.5 sandy with 4.0 and squidward with a 2.0 so yeah that's how to create an array of structs if you would like a copy of this code i'll post this to the comment section down below and well yeah that's
how to create an array of structs in c well well well welcome back so enums short for enumerations they are a user-defined type of named integer identifiers a benefit is that they help make a program more readable either for us or for somebody else that's looking over our code so here's how to create some enums you can either declare these within the main function or outside of the main function let's do so outside of the main function so to create some enums type the keyword enum followed by a unique identifier let's say we're working with
days of the week so let's say day curly braces and then end this with a semicolon so enums are constants and let's declare some constant names let's say the seven days of the week so separate each constant with a comma and we will just go through the days of the week here are the enumerations that we declared the days sunday through saturday the days of the week now each of these constants has an associated integer so beginning with your first constant this will have a value of zero then the next will have one then two
then three then you continue on in that pattern but you can give these a unique value let's change it sunday to one because it's the first day of the week then monday will be two and then we will just continue with these now to use one of these enums we would type enum then our identifier name day it's kind of like a data type and then some variable name let's say today and then you can set the sequel to one of these constant names let's say that today is sunday so an important note with these
enumerations they're treated as integers and not strings if i need to work with one of these enums we're going to treat them as if they were an integer so just for an example i'm going to print the value contained within today so this is going to be an integer so we will use the d format specifier and we will display today so since today is equal to sunday this has an associated integer value of one and if i display that this will print the number one if i change this to saturday well then it will
print the number seven so an important note is that enums are not strings but they can be treated as integers now how does this make a program more readable so let's write an if-else statement that's going to check what today is first we'll begin with using the associated integer value so if today is equal to 1 or today is equal to 7 then that means it's either sunday or saturday and let's print a message let's say it's the weekend party time else we will print something else i have to work today so today is set
to saturday that means that saturday has an associated integer of seven so if today is equal to one or seven well then we will execute this if statement it's the weekend party time i think i'm just going to add a new line real quick now if i set this to a different day of the week let's say monday well then i have to work today so the way that this is written now it's not too readable so instead of using an integer value let's use the associated name with each of these constants so let's replace
one with sunday and seven with saturday and i'll change this to maybe sunday so this is a lot more readable especially if somebody else is reviewing your code they may not understand why today is equal to one or today is equal to seven but this makes a lot more sense oh so if today is equal to sunday or if today is equal to saturday then we print it's the weekend party time so that's a huge benefit with enums is that they help make a program more readable so to declare enums you type enum then an
identifier and then you can list as many constants as you would like and you can give them an associated integer value too so yeah those are enums if you'd like a copy of this code i'll post this to the comments section down below and well yeah those are enums in c hey uh what's going on everybody so in this video i'm going to show you how we can generate some random numbers in c just as a disclaimer these are pseudorandom numbers they are a set of values or elements that are statistically random so don't use
these for any sort of cryptographic security now before we begin include these two header files at the top stdlib and time the first thing that we're going to do is use the current time to generate a seed which we need for random numbers so we can use the s rand function s for seed rand for random and then we will pass in the current time time function pass and zero so we will use the current time as a seed for random numbers and then the function that you need to generate a random number using this
seed is the rand function so let's store our number within a variable maybe number one int number one and i will set the sequel to then invoke the rand function now the rand function will give you a random number between 0 and 32 767. so i'm guessing we probably don't need a number that large so depending on the range of numbers that we need we can use modulus and then the maximum number that you would like so if i'm rolling a six sided dice i can say modulus six so the modulus operator gives you the
remainder of any division so technically this gives us a random number between zero and five because computers always start with zero but you can add an offset so if i need the numbers one through six i can just add plus one to the end and then maybe i'll surround this section with a set of parentheses just to make this more readable so generate a random number between zero and five add one that gives us a random number between one and six and let's just test that theory so i'm going to use printf and we are
displaying an integer and let's display number one so we should have a random number between one and six and our random number is two and if i run this again this will be a different number probably yup six okay now if i need to generate a couple different random numbers i can just use this rand function again so let's say we are rolling three dice number one number two and number three and then i'll print these as well so number one number two and number three and i'll add a new line character after each of
these print statements okay so this will give us three random numbers between one and six one three one three five six now it is important that we're generating a random seed let me show you what happens when i take this out so this will give us the same numbers over and over again six six five six six five and six six five so that's why it's important that we use a seed for random numbers now another thing too if you need a larger number you can just change this number for example i play a lot
of dungeons and dragons so i may need to roll a 20-sided dice so i can just set this to 20. so 288 and let's try this again 12-5-4 so yeah that's how to generate some random numbers in c if you would like a copy of this code i'll post this to the comment section down below and well yeah that's how to generate some random numbers in c hey y'all what's going on everybody it's you bro hope you're doing well and in this video we're going to create a number guessing game in c so sit back
relax and enjoy the show if you find this video helpful please remember to like comment and subscribe your support will help keep this channel running hey everybody so now that we know how to generate some pseudo-random numbers in c i thought this would be a good opportunity for us to create a number guessing game if we're working with pseudorandom numbers be sure to include at least these three header files at the top of your program so let's generate two constants min and max const int and a naming convention for constants is to make all of
the letters uppercase so minimum will be the minimum number that we will generate when we generate a random number so let's pick a number between maybe one and one hundred so min will be one and max will be 100 but feel free to take the liberty to choose some other numbers and we'll need int guess to store a user's guess int guesses to keep track of the guesses and int answer okay now if we're working with random numbers we'll want to create a seed and to do that we can actually use the current time so
use the s rand function and pass in time pass in zero so this uses the current time as a seed to generate some random numbers and if we need a random number between these two constants min and max this is what we can do so we will assign answer set this equal to call the rand function and use the modulus operator and set this to max and then we will add min as an offset so this will generate a random number between these two constants 1 and 100 or some other numbers if you have something
different so this line of code will generate a random number between min and max now before we actually move on let's test this just to be sure that everything's working so let's print whatever the answer is so we're displaying an integer we are displaying answer and let's see what this is so my answer this round is 73 if i run this again it is 93. now if i change these values we will adjust the range in which some random numbers will generate so if i set min to 100 and max to 1000 that should change
the range of numbers and this time i have 334 but i'll change this back to 1 and 100 okay so we know that we're generating a random number so let's move on let's create a do while loop so it's going to take at least one guess in order for somebody to guess the correct answer so do curly braces we'll add while and check a condition at the end and the condition is guess does not equal answer so let's create a prompt and ask the user to enter a guess enter a guess and we will use
scanf to accept some user input so this is an integer and we are storing this within guess so address of operator guess now that we have our user's guess let's compare it to our answer so we'll use an if statement and check to see if guess is greater than answer so that means a user guessed a number that was a little too high so let's print a message to let the user know to hi and then we can use an else if statement else if guess is less than answer well then their guess was too
low print too low so if our guess is not greater than the answer or less than the answer that means they must have got it right so within an else block let's print correct so then after our if else statements let's increase guesses by one guesses plus plus the very best possible score a user can get is one if they guess it on the first try so before we finish a while loop we will increment guesses by one so then once we escape our while loop let's print the user's final score so we will print
the answer this is an integer and we are displaying answer and we will display the guesses it took so guesses and display the value found within guesses and this part isn't necessary but i like to add some text decorations so maybe i'll add a bunch of asterisks to make it look nice let's run it enter a guess i'll guess something right in the middle between so maybe 50. so that guess was too low so maybe 75 okay that was too high so our numbers between 50 and 75 how about 62 that's too low so it's
between 62 and 75 how about 69 that's still too low so between 69 and 75 maybe 72 that's still too low so it's between 72 and 75 73 all right that was the right answer i'm just gonna fix one thing real quick uh let's add a new line here okay let's try this again okay until i guess i'll try 50 again that's too high maybe 25 that's still too high what about 12 2 low maybe 18 2 low 21 that's still too low 23 too low 24 and 24 was the correct answer all right everybody
so i thought that would be a fun guessing game we could create for practice if you would like a copy of all this i'll post this to the comment section down below and well yeah that is a simple number guessing game in c all right people so now that we know how to create an array of strings i thought this would be a good opportunity for us to create a quiz game so before we begin make sure to include these two header files at the top of your program so let's begin with a 2d array
of characters and these will store our questions and i'm going to set a maximum size for each question to 100 bytes and we can go ahead and initialize this array with some questions so remember with strings each string is its own array so let's ask maybe three questions but feel free to pick any amount that you like and come up with any questions you would like as well or you can copy me i don't care what year did the c language debut then separate each string with a comma then just to make this more readable
i'm going to go down to the next line so this is question two now who is credited with creating c and one more question what is the predecessor of c so now we have some questions we'll need some options this could be a separate 2d character array char options and i'll copy the dimensions from questions and we'll create four sets of options for each question this is the first set of options for the first question and then let's add a second set of options for the second question and a third set now we'll create an
answer key this will be a one-dimensional array so char answers and the size will be three and i will set this equal to my answer key so the correct answers for my quiz are b a b so these will be individual characters all separated with a comma b a b so let's calculate the number of questions that we have so i will declare int number of questions and set this equal to sizeof operator pass in our two-dimensional array of questions and divide this by one of the elements because they all have the same size questions
at index zero and let's declare char guess to store our guess and int score to keep track of the player's score so now let's begin this i will print the title quiz game then add a new line okay now we need to loop through all of the questions so let's use a for loop so we will have an index of i set to zero and i would like to loop through this as long as i is less than the number of questions that we have then increment i by one and to test this let's print
our questions so printf we're displaying a string so use the s format specifier questions add index of i and then i'll add a new line character after each printf statement okay let's at least test this so we should cycle through our questions okay here are my questions what year did the c language debut who is credited with creating c what is the predecessor of c and this part isn't necessary but i'm going to add some text decorations i'll just display a bunch of asterisks i'll do that before and after the question and let's try that
again oh then add a new line character that's a little bit better after our question let's display the possible options so we will need a nested for loop so four now this part's gonna be a little bit tricky we need to begin our for loop at every fourth string within our for loop let's set int j equal to i times four so during the first iteration i will be zero so zero times four is zero but during the next iteration of the outer for loop i is going to equal one so one times four is
four so that way we will begin the inner for loop with every fourth string within our 2d array of options and the condition is going to be j is less than i times 4 and then we would like to display four strings this for loop will cycle four times beginning at every fourth string and then we need to increment j by one now let's print every option so this is a string i'll add a new line and we are printing options at index of j and let's test this just to be sure that it works
okay so we have our question followed by four possible options now let's accept some user input after the nested for loop currently our program isn't going to wait around for any user input that's why i displayed all the questions and options okay we will create a prompt to have a user type in a guess guess and we will use scanf to accept some user input we are accepting a single character and use the address of operator guess now let me show you what happens when we run this real quick so i'm just going to type
in anything let's say a okay so we skipped question two that's because after using scanf when we accept a character we have that new line character within the input buffer so we need to clear that so one way in which we can clear that is to use scanf again use the c format specifier and that's it so this will clear the new line character from input buffer so this should no longer just skip question two okay let's say a b c okay so we know we can accept some user input now now here's one thing
what if somebody types in a lowercase character i think that should still count even though we're looking for an uppercase character so let's take our guess and use the two upper function to make it uppercase guess equals to upper then pass in guess so basically we're passing in our guess making it uppercase and reassigning it to our guess and let's write an if else statement to check our guess if it's equal to our answer so if else our condition within our if statement if guess is equal to answer at index of i remember that we're
still within the for loop the outer for loop so we have that index oh that's answers plural if a user's guess is equal to the answer then let's print correct and then give them one point so printf correct and then increment our score score plus plus else we will print wrong and you can give the correct answer if you would like just do that within here now once we cycle through all of the questions we can display a user score so be sure to do that outside of the for loop the outer for loop that
is so let's use printf and display final score so i'm going to display two values so the first will be the player score divided by the number of questions so we have two integers to work with and we are displaying score and number of questions and then if you want you can add some text decoration to make it look cool so i'm going to run through this quiz once and intentionally get one question wrong so what year did the c language debut that would be 1972 that's b who is credited with creating c uh let's
say doc brown so d and what is the predecessor of c that would be b okay and my final score is two out of three so let's try that again and this time i will try and get one hundred percent so the correct answer is b a dennis ritchie and b and my final score is three out of three so yeah i thought that would be a simple quiz game in c if you would like a copy of this code i'll post this to the comment section down below and well yeah that's a simple quiz
game in c hey everybody let's talk about bitwise operators these are special operators used in a bit level programming knowing binary is important for this topic so if you don't know how binary works i would recommend skipping to the next topic but if you're comfortable with binary well this video is for you so let's begin i'm going to discuss five different bitwise operators and or exclusive or left shift and right shift let's create three variables x y and z x will equal six y will equal twelve and z will store our result and we will
set that to be zero so i'm going to give you the binary representation of each of these numbers so six is this number so we have eight bits that's a byte and this is the binary representation of the number six 12 would be this binary number and zero zero is easy that would be all zeros so let's use the and bitwise operator so what we're going to do is set z equal to x and y so imagine this imagine that we're aligning all of these bits in columns using the and bitwise operator we're going to
look at our operands x and y if both of these are a one we will assign one to our result and let's begin with the first column on the right both of these are zeros so our result will stay at zero and with the next column we have one and zero and using the and bitwise operator both of these need to be 1 in order to assign one to our result so we will skip this column now with our third column these are both 1 so we will assign 1 to our result the next column
is zero and one we skip it and the rest are just zero so this binary number is the binary representation of the number four so let's test that z equals x and y and let's print z and equals we're displaying an integer i'll add a new line and we are displaying z and let's see if this is for yep our result z is equal to four now let's move on to or so let's set this back to zero and we will set z equal to x or y or is represented by a single vertical bar
and we will print or let's try and guess what z is going to be before we actually display it with the or bitwise operator only one of these bits needs to be one in order for us to assign one to the result so since these are both zero this will stay at zero this bit is one this one's zero so this would be one and for the next column of bits these are both one so that counts as well and we have a one in here so that is one and the rest are just zero
so this is the binary representation of the number fourteen and let's see if z is equal to fourteen yep we got that right so let's set this back to zero now with exclusive ore that is represented by a carrot with exclusive ore only one of these bits can be won if neither or both of these bits are one we don't assign anything so both of these bits are zero they will stay a zero we have one of these bits as one and not the other so that counts as one now with this next column both
of these are one and using exclusive ore only one of these can be one so since these are both ones we do not assign anything so we keep that as zero and with the next column only one of these is one so we will set this to be one within the result and this is the binary representation of ten and let's test that z equals x exclusive or y and we will print exclusive or equals z and let's see if that's ten yep z is equal to ten now here's left shift we will shift these
bits so many spaces to the left using left shift so we will set z equal to x and then left shift which is represented by two left angle brackets a number of spaces let's begin with one so we have x equal to six what we're doing is shifting these bits one spot to the left and then adding zero at the end and this is the binary representation of the number 12. actually it's the same as y currently these binary numbers are the same and let's print that so shift left and z should equal 12 yep
and if i shift left twice well then we are just moving these bits one more space and now this is 24. there you go so you probably noticed that there's a pattern every time we shift a binary number to the left it effectively doubles now let's right shift so let's copy this paste it and we will use two right angle brackets and this is shift right and let's set this to 6. if we're right shifting we shift these bits one spot to the right and this is the binary representation of the number three and if
i print this after shifting right once our result z is three every time we shift right we're effectively cutting our number in half now if i shift right again we will shift these bits one more spot to the right and we are going to truncate this one at the end and this will give us one that is the binary representation of the number one so technically half of three is 1.5 but we can't store that 0.5 portion so it just gets truncated all right everybody those are just a few bitwise operators they are special operators
used in bit level programming there's five that we discussed today but there is another known as the complement operator but that's a little bit more complex and i might save that for another video so yeah those are bitwise operators if you would like a copy of this code i'll post this to the comments section down below and well yeah those are some bitwise operators in c all right everybody so let's talk about memory memory is an array of bytes within ram and a memory block is a single unit in bytes within memory they're used to
hold some value and a memory address is the address of where a memory block is located within ram i like to think of memory as a street with a bunch of different houses and each house is a memory block which can hold some value kind of like they're storing a person and a memory address is the house address on that street where that memory block is located so this would be a street address like one two three fake street so when we declare variable let's say we have char a when we declare a variable we
are setting some amount of memory blocks aside to store some value so the memory block that this variable is using up has some memory address and if i assign this variable a value let's say maybe x well then if i was to go into my computer's memory and look for this address i would find this character so imagine we're walking down the street and we are looking for somebody's address so we're going house to house and we find a matching address if i were to open their front door i should probably knock first at least
then i will find the character x so that's kind of an analogy i like to use when thinking about memory so let's declare a couple other characters we have char b i'll give this a value of y and char c and i'll give this a character of z okay so let's find the size of each of these characters so i'm going to use a printf statement i'm going to display an integer and the size of each of these characters is within bytes so i'm going to use the size of operator and pass in one of
my characters so i'm going to pass in a and i'll do the same thing with b and c so the size of each of these characters is one bite and i think i'm just going to add a new line here much better okay now we can actually access the address of each of these variables so each of these variables is using one block of memory a single block of memory is a byte so within a printf statement i would like to display an address so the format specifier is p and i will use the address
of operator then the name of one of my variables so i'll display the address of variables a b and c and then display each on a new line so here are the memory addresses for these three variables these addresses are in hexadecimal these are the street addresses of each of our memory blocks on our fictional street hey uh so this is bro from the future just a quick crash course on hexadecimal values with standard decimal values they use the numbers 0 through 9 but with hexadecimal you use the numbers 0 through 9 as well as
a through f so that gives you a total of 16 different values for each digit so that's why there's a mix of numbers and letters so each of these variables uses one memory block they use one byte of memory so beginning with variable a this has this street address but if we go down to the next memory block you can see that there is just one change f goes down to e and then with variable c this address goes down by one so f e d these are contiguous memory blocks they're all next to each
other but now if we switch to a different data type like a short we haven't used these in a long time well shorts use two bytes of memory as we can see here so these hexadecimal addresses are now going down by two e d c b a so each of these variables are using two memory blocks we need an even larger house even more memory blocks and they use up two memory addresses and then if i change these two integers well they're going to use up even more memory so integers use four bytes memory and
these are the street addresses of these three variables and doubles use double the size of an integer doubles use eight bytes of memory and these street addresses are decrementing by eight if this was a fictional street with houses well doubles use up eight bytes memory so think of these like mansions they're using up a lot of space now what happens with an array i'm going to declare char a and declare an array this will be an array of characters to begin with so let's say character array b and i'll give this a size of one
so i'm going to print the size of a and the size of b as well as their memory addresses our single character a uses one byte and this is the street address of this variable and our array b also uses up one byte and this is the street address of where this array begins if i set the size of this array to 2 well then my array is going to use 2 bytes and now it has a different address to accommodate the increased size of the array and if i change this to 3 it now
uses 3 bytes of memory and it has a new address and if i change the data type of the array we'll have to take that into consideration so a short uses two bytes memory and we need three elements so that's a total of six two times three is six and if i change this to int and int uses four bytes so four times three is twelve and a double is eight so eight times three is twenty four so yeah that's kind of the basics of memory so memory is an array of bites within ram think
of it like a street and a street contains houses each house is a memory block that can hold some value think of each value as a person living in that house and in order to find a person we have to know their address like a street address c refers to these variables by their street address but that's difficult for us to understand so we just refer to this memory address as a variable name because that's easier for humans to work with so yeah that's some basics of memory and c and in the next video we're
going to discuss pointers so if you would like a copy of my notes here i'll post them to the comment section down below and well yeah that's the basics of memory in c hey yeah it's you bro hope you're doing well and in this video i'm going to explain the basics of pointers in c so sit back relax and enjoy the show if you wouldn't mind please like comment and subscribe one like equals one prayer for the youtube algorithm oh yeah we finally made it to pointers we're only about 40 topics in a pointer is
a variable like reference that holds a memory address as a value to another variable array etc some tasks are performed more easily with pointers and here's a comprehensive list of a few of the benefits in this video we're going to more or less focus on building a solid foundation with pointers and understanding how they work so let's say we have a variable int edge and i'll give this some value a variable has a value and an address and let's display the value and the address of this variable using two print statements so first i'm going
to display the address of this variable address of age then i will use the p format specifier to display an address in hexadecimal and we are displaying the address of age and ampersand is the address of operator address of age and i would also like to display the value of age value of age and this is an integer and we will display age so variables have a value and an address this is the address of this variable and the value at this address as you know there's tons of different things we can do with a
value of a variable but there are things that we can do with an address as well so we can actually store this address within a separate variable a variable like reference and that is called a pointer so to create a pointer we will make sure these are of the same data type as the variable we're pointing to age is an integer so we will declare this pointer of the integer data type and the next step to declare a pointer is that we will use an asterisk this is the in direction operator and a common naming
convention for pointers is that you type lowercase p the name of the variable you're going to point to but make the first letter uppercase and i'm going to set this equal to the address of age so the address of age and the value at this variable are the same and let's test that theory so this time i'm going to display the address of age and the value of ph and this will display an address so change the format specifier from d to p and i'm going to turn this line into a comment for now okay
so these addresses should both be the same the address of age as well as the value stored within ph so our pointer has its own address but the value stored within it is an address and we can access the value at this address by using the indirection operator so this time i'm going to print the value of age and the value at stored address and to dereference a pointer you will type the pointer name ph appreciated with the indirection operator as my own personal nickname for the indirection operator i call it the value at address
operator that's not any official name that's just how i think about it so we're extracting a value at the given address within this pointer so if i display the value of age and the value at the stored address using the indirection operator well both of these are going to be the same so we have 21 stored within our edge and after dereferencing this pointer we're extracting the value at this given address so you use the indirection operator when you declare a pointer as well as when you want to access a value at the stored address
so with the data types of the pointer you'll want to make sure they're consistent c is a strongly typed language so if i change the data type of my pointer to char using my compiler i'll receive a warning initialization of char from incompatible pointer type int now the actual data type of a pointer is the same they use eight bytes to store an address so i'm going to print the size of our variable as well as our pointer so i'll change this data type back to what it was originally and this time i'm going to
print the size of our age variable as well as the size of our pointer size of age and we're displaying an integer and this will be in bytes size of age size of pointer age and then i'm going to display a new line okay so the size of our age variable is 4 bytes it's an integer integers use 4 bytes so even though we declared our pointer as an integer the actual size of our pointer is going to be 8 bytes that's enough to store a hexadecimal address so just as good practice since c is
a strongly typed language you'll want to be sure that the data type of your pointer is consistent with the variable that it's pointing to now here's one thing that we can do with pointers we can pass a pointer as an argument to a function so outside of my main function i'm going to declare a function void let's say print age first we'll do this with passing and integer so int age and i will display the value of age you are age years old and i will display my age variable then at the end we will
pass in our variable print edge and i will pass in age for now i'm just going to turn all of these into comments okay so you know this works you are 21 years old you could also pass in a pointer too so i'm going to this time pass in pointer age and we need to change the parameter from an integer to a pointer so precede the parameter name with the indirection operator and i'll rename this parameter as ph in order to access the value of the address stored within my pointer i need to de-reference so
i will use the indirection operator then type my pointer name ph and this will do the same thing as before so yeah those are pointers oh and before i forget you can declare and initialize a pointer in two steps but it would be good practice if you're declaring a pointer to assign a value of null since we already declared this pointer we do not need to use this indirection operator again when assigning a value so p h equals the address of age so it's considered good practice to assign null if you're declaring a pointer and
not yet assigning a value so yeah that's basically a pointer it's a variable like reference that has a memory address as value to another variable array etc some tasks are performed more easily with pointers and to declare a pointer you use the indirection operator and if you need to access a value stored within a pointer you type the pointer name preceded with the indirection operator so yeah that is a quick intro to pointers if you found this video helpful please give this video a thumbs up leave a random comment down below and subscribe if you'd
like to become a fellow bro all right let's do this here's how we can write to a file in c let's create a file pointer the data type is file and i'll name this pf it's a pointer to a file and i will set this equal to then invoke the f open function we will pass in a name we would like to give our file let's name this test.txt but if you would like this to be a different file extension such as html well you can change it to that then uh we'll keep this as
a plain text file just to keep it simple and to write to a file there is a second argument a mode so this could be w for right a for append r for read but we are looking for w for now so it is good practice at the end of your program to close any files that are open so we will use the f close function and pass in our pointer p f make sure to not dereference it now to write a line of text to our file we can use f print f pass in
our pointer p f do not dereference it and then some string of text let's say spongebob squarepants so this file will be created in the same folder as my c program so after running this we have a new text file within the same folder and it says spongebob squarepants what if i run this again and write something different like patrick starr so if the mode is w then we will actually overwrite any existing data already within this file if we need to append a file we can use the a mode for append so this time
let's append some text to the end of our document spongebob squarepants and you have to keep track of any new lines that you add too so if i run this again and this time i am appending some text well patrick starr is still there and we appended spongebob squarepants to the end of our file now if you would like to delete a file here's how i'm going to turn all of this into one giant comment let's use a little bit of file detection let's check to see if our file does exist within our if statement
let's invoke the remove method and we will pass in the name or location to our file test.txt if we remove this file successfully it will return zero so if after invoking the remove function if this returns zero that's its exit code that means that file was deleted successfully let's print a message to let the user know that file was deleted successfully else we will print a different message printf that file was not deleted okay let's try this so here's my file within the same folder if i run this that file was deleted successfully and that
file is no longer within the same folder you can see here that this says deleted and if i run this again we will not be able to locate that file because it's not there now you can write a file to a different location let's say i would like to write a file to my desktop i can set a relative file path or an absolute file path i'll use an absolute file path i'm going to get the file location of my desktop so i'm just going to click on one of these folders go to properties and
copy this location so with my file name i'm going to precede this with an absolute file path then any backslashes might need to be double backslashes so this time if i write a file then this file will appear at this location on my desktop and here's that file test.txt and it says spongebob squarepants well alright everybody that is how to write append and delete files in c if you found this video helpful be sure to help me out by smashing that like button leave a random comment down below and subscribe if you'd like to become
a fellow bro alright people so in this video i'm going to show you how we can read the contents of a file someplace on your computer you can either place this within the same folder as your c program or someplace else i think it would be cool if we read a file from our desktops so i'm going to create a new file and this is going to be a plain text file and i'll write a poem i'll name this poem.txt here's my beautiful poem are red violets are blue booty booty booty booty rockin everywhere okay
i'm going to save and then i'll need the file location of where this is located i'm going to right click go to properties and copy this file path and save it for later now to read a file on your computer we'll need to create a pointer the data type is file and i'll name this p f and i will set the sql to then invoke the f open function pass in your file mine is poem.txt so if this file is not within the same folder as your c program you'll need a relative or absolute file
path since this file is on my desktop i could use an absolute file path so preceding my file name i will paste that location and then each backslash may need to be a double backslash because that is an escape sequence for a backslash character okay the second argument is the mode this time we are going to read a file so pass in r for the second argument then it's good practice at the end of your program to close any open files we will invoke the f close function pass in our pointer do not dereference it
and we will need one more thing a buffer a buffer is going to act as a container an array of characters to hold one line of our text document one line at a time so let's declare an array of characters named buffer and i'll set the size to 255. our buffer is going to hold one line of our file one line at a time and to read a single line from our file we will use the f gets function and there are three arguments our buffer this is what we're inserting a line of text into
a maximum input size i'll set this to be 255 to match our buffer and then a pointer to the file that we're opening and again make sure to not dereference it so this will read a single line of text and then let's print our buffer so we're printing a string and we are displaying whatever is currently within our buffer so after running this this will read a single line of text whatever's at the top roses are red now if i need to read all of the contents of my file i can place this section of
code within a while loop so with our condition i'm going to move the f gets function within the condition if we reach the end of a file f gets will return null so let's continue this while loop while f gets does not return no if we do not return null then we will print whatever's within our buffer now if i run this this will display all of the lines from my file roses are red violets are blue booty booty booty booty rocking everywhere and if you would like you can add a little bit of file
detection so before we reach our while loop let's check to see if that file even exists before we attempt to open and read it so let's check to see if our pointer equals no if it is null that means we could not locate this file so i'm going to print unable to open file and we'll create an else statement else let's read and print the contents of this file okay so let's say i get the file extension wrong let's say i'm looking for an html file named poem and i try and read this unable to
open file but if we are able to locate this file we will open it and read the contents and then close this file so yeah everybody that is how to read the contents of a file line by line if you found this video helpful please be sure to help me out by smashing that like button leave a random comment down below and subscribe if you'd like to become a fellow bro oh yeah what's going on everybody it's you bro hope you're doing well and in this video we're going to create a game of tic-tac-toe so
sit back relax and enjoy the show if you find this video helpful please remember to like comment and subscribe your support will help keep this channel running all right let's begin so the first thing that you're going to need is to include these files at the top of your c program and we will create seven different function prototypes so the return type of this first function is void and the name of this function will be reset board our board is going to be a 2d character array and our second function is void print board which
will print our 2d character array then with this next function this has a return type event and this will check free spaces if after invoking this function this function returns zero that means the game is over there's no more places to move and we will need void player move when it's the player's turn to move void computer move when it's the computer's turn to move char check winner so we have a few different win conditions to check and void print winner and there is one parameter a single character soap char so these are function prototypes
we tend to declare these before the main function because they help with readability after the main function we will give each of these a body so copy and paste those functions and then give each a body and with the parameter for print winner the parameter is char winner now let's head back to the top of our program and there's a few global variables that we're going to declare we could declare these as local variables within the main function but this program is going to get really complicated then if we have to pass around pointers to
a two-dimensional array so just to keep this simple i'm going to create some global variables there are some downsides to global variables so i tend to not to like to use these so we have a 2d array of characters named board it's our game board and let's create two constants constant char player a naming convention for constants is to make all of the letters uppercase and i will set this to a character of my choice i could be oh or i could be x or something else maybe i could be a dollar sign whatever uh
i'll set myself to be an x and then let's create a constant for the computer constant char computer and computers will be o so within the main function we will declare a local variable char winner and i'll go ahead and set this to an empty space so if our winner is in empty space that means there currently is no winner if player wins then that would be an x if computer wins that's a no within our main function this is acting as a driver for our code so the first thing we'll do is reset our
board so we are going to initialize all of the different characters within our two-dimensional board so let's head to this function so with our reset board function we need nested loops the outer for loop is for the rows the inner for loop will be for the columns int i set this equal to zero and i need to iterate this for loop three times one for each row that we have and then we need an inner for loop so change the index to j and for each index within our 2d array at index of i and
j i will set the sequel to an empty space so when we call the reset board function each element within this 2d array of characters will be an empty space effectively clearing it so back within the main function after resetting our board let's print our board and fill in this function so you can get creative with this here's one thing that i'll use so i'm going to print a space a character a space a vertical bar space character space vertical bar space character these three format specifiers are placeholders the first character i'm going to display
is our board at index of zero zero that is row zero column zero followed by board index zero one then board zero two and with the next printf statement let's display something like this a new line three dashes a vertical bar three dashes another vertical bar three dashes then a new line okay so let's copy these paste it once and we need to change these indices so with this third printf statement these indices will be one zero one one one two and then do this again so copy paste two zero two one two two then
at the end i'll add a new line printf new line oh let me fix one thing okay so this is what it should be all right now back within our main function we're going to create a while loop and we'll surround our print board function within this while loop so our condition is if winner is equal to an empty space that means there currently is no winner and after invoking the check free spaces function the value returned does not equal zero so let's fill in this check free spaces function within the check free spaces function
let's declare a local variable int free spaces and i'll initially set this to nine then we need a nested for loops and i equals 0 we will continue this as long as i is less than 3 i plus plus then create an inner for loop change the index from i to j and within the inner forward loop we're going to write an if statement and we are checking to see if our 2d array of characters bored at index of i and j does not equal an empty space if whatever spot we're on is currently occupied
we will take our free spaces local variable and decrement it by one then outside of our for loops we will return free spaces if we return zero that means the game is over there's no more places a player can move so heading back to our main function it will be let's say the player's turn to move first so invoke the player move function and we'll need to fill this in with the player move function we will declare two local variables intex into y and we will ask a user to enter in a row number and
a column number of where they would like to move to so using a printf statement we will enter row number one through three and then use the scan f function to accept some user input so this will be an integer and use the address of operator x so a user is going to enter in numbers one through three for which row that they need but with arrays they always begin with zero but a user is not going to know that so with whatever the user types in we will decrement x by one so this gives
us rows zero through two technically then do the same thing with our columns enter column number one through three address of operator y then decrement y we will check to see if the coordinates that the user gave are occupied or not so using an if statement we will check to see if our board at index of x and y does not equal an empty space that means that this spot is currently occupied by another character so let's print something to let a user know invalid move else that spot is open so take our board at
index of x and y set this equal to our player character so we're going to take all of this code and place it within a do while loop so write do while place your code that you just wrote within there and our condition is if our board at index of x and y does not equal an empty space if the spot that the player would like to place their character is currently occupied then we will ask them again to enter some coordinates uh then within our else statement we need to break out of this while
loop okay so that is everything for the player move function so then heading back to the main function after the player moves we will check to see if there's a winner winner equals then invoke the check winner function and we will fill in this function next so find the check winner function and we need to check all of the different win conditions so first we will check each row using a for loop so this section of code we will check our rows we'll need a for loop to iterate three times one for each row int
i equals zero continue this as long as i is less than three increment i by one so this if statement is going to get a little bit funky we need to check each set of horizontal elements so let's begin with board at index of i and zero so that would be the top left element and we are checking to see if the character here is equal to this character so board at index i and one and we're checking to see if board at index of i and zero is equal to board at index of i
and two so here we're checking to see if this element is equal to this element and this element is equal to this element if they're all consistent we have a winner so we will return whatever character is within one of these elements let's say this one so return board at index of i index of zero return whatever character is within here this section of code will check all of the win conditions for each row but now we need columns so check columns and we can copy most of this so copy it and paste it then
we just need to change these indices around so if board at index 0 i is equal to board at index of one i and board at index of zero i is equal to board at index of two i then we will return whatever character is within board index of zero index of one so this section of code will check for any column when conditions then next we have diagonals there's only two check diagonals so let's copy this section of code paste it so our indices are 0 0 is equal to 1 1. 1 1 is
in the middle and board at index of zero zero is equal to board at index of two two if so then return zero zero then we have one more diagonal so copy this paste it and here are the elements if board at 0 2 is equal to board at 1 1 so 0 2 is the bottom left 1 1 is the middle and board at zero zero equals board at two zero that is the top right corner right here so if we have a diagonal we have a winner so return board at zero 2 let's
say if after checking all of these different win conditions there is no winner then let's return an empty character that means there currently is no winner so then head back to the main function after invoking the check winner function let's write an if statement to see if the game is over so our condition is if winner does not equal an empty space that means there is a winner or after invoking the check free spaces function and the value returned is zero then we will break out of this while loop this is everything done for the
player now we need to create a section of code within our while loop for the computer so copy this section of code and paste it and this time it will be the computer's move invoke the computer move function and we will need to fill in the computer move function within the computer move function the computer's move will be randomly generated and to generate some random numbers we'll need a seed so to create a seed to generate random numbers invoke the s rand function pass in time invoke it pass in zero and we will declare intex
and into y we will generate two random numbers between zero and two now before we generate some random numbers let's check to see if we even have any free spaces available so our if statement is going to be check free spaces invoke it then if this is greater than zero then we will generate some random numbers and we'll do so within a do while loop so within this do while loop we will generate two random numbers between 0 and 2. x equals invoke the rand function modulus three then y equals invoke the rand function modulus
three with our condition let's check to see if the spot generated is even open so board at index of x and y does not equal an empty space so we will keep on generating random numbers until there is an open space then escape this while loop so if we find an open space let's take our board at index of x and y set the sequel to our computer player this is all within an if statement else if there are no more spaces available we will invoke the print winner function and pass in an empty space
this means that there is no winner it's a draw now let's fill in this print winner function this function is fairly easy if winner is equal to player then we will print you win else if winner is equal to computer then we will print you lose else if there is no winner then it's a tie it's a draw it's a tie within the main function we just have a few more things to add so outside of our while loop we will print our board and print the winner print board and print winner there is one
argument whoever the winner is so let's run this once enter row numbers one through three uh let's say one and one so i moved here and the computer moved to row three column two uh let's say row three column three okay so i moved here and the computer is up here so i moved to row three column three and our computer is at row one column three uh then i'll move to the middle two two and it looks like i won this round so let's try this again and we will intentionally lose so one one
two one one two two two and unfortunately it looks like i lost this time let's attempt to tie and it looks like it's a tie so it looks like this game is working so what if we would like to ask the user if they would like to play again we can easily place our code within a do while loop so within our main function let's create char response and we will create a do while loop so take all of this code after the do while loop beginning with reset board copy it delete it and then
paste it within the do while loop at the top of our do while loop let's reset winner and response winner equals an empty space and response equals an empty space then heading to the bottom of our do while loop let's ask if the user would like to play again so after displaying the winner let's create a prompt printf would you like to play again y for yes and for no and i'm just going to clear our buffer by using scanf and accepting a character just in case there is a new line character within our buffer
then we will use the scanf function and accept a character after clearing our buffer and we will use the address of operator response now just in case somebody types in lowercase y i would still like to count that as yes so i'm going to take our response set this equal to invoke the to upper function pass in response and with this condition we will continue playing while our response is equal to the character y and at the end let's print thanks for playing okay let's run this one last time all right i win would you
like to play again i'll type in y for yes and we have a new game all right it looks like i win so this time i will exit by typing n thanks for playing so yeah everybody that is a game of tic-tac-toe if you would like a copy of this code i'll post this to the comments section down below hey if you found this video helpful you can help me out by smashing that like button leave a random comment down below and subscribe if you'd like to become a fellow bro