- Back to Home »
- How to Program in C
Posted by : Unknown
Step 2: The Parts of a C Program
Now that you have an idea of how to get around in bash it's time to learn about C programming. Let's begin by looking at that program I wrote in the bash tutorial video and break it down into it's separate pieces.
The "#include" statement is used to access lots of useful functions already written by other programmers for use in your own program. In this case the standard I/0 library is included. This is an essential library for most C programs because it deals with all the inputs and outputs of your program.
The declaration of the main function right after that has four parts:
1. int, which I will explain, is a variable type and is what the function main returns when it completes.
2. main which is the name of the function.
3. () means that it is not necessary to take in any inputs from the bash command line when the program runs. You can take in arguments here if you want to give users more options from the beginning.
4. Finally, the bracket signals the beginning of the main function's code. You will notice there is a closing bracket at the bottom that shows the end of the code block.
The printf() line in the code is what is called a function call. This is what it looks like when you use a function that is separate from your main function, either that you wrote or someone else wrote in a library. In this case printf() is a function from the stdio library and can handle lots of different arguments between the parentheses. "Hello!\n" as the argument results in printf() displaying on the screen Hello!
The \n part is a special character and it means newline. This makes sure the next thing displayed is on it's own line. I'll get into more detail of what you can give printf() as arguments later.
The return statement is required for all functions that have a type declared before the name like int main(). An int is an integer variable type. A whole number in other words. For main() returning an int 0 is signaling the programs completion to the OS. It technically is not required that you have this in main() because most compilers will compile your program correctly without it but in all other functions with a return type it is required that they return something.
Also notice that there is a semicolon at the end of every line of code. This is required so that the compiler clearly sees the end to each individual statement.
The "#include" statement is used to access lots of useful functions already written by other programmers for use in your own program. In this case the standard I/0 library is included. This is an essential library for most C programs because it deals with all the inputs and outputs of your program.
The declaration of the main function right after that has four parts:
1. int, which I will explain, is a variable type and is what the function main returns when it completes.
2. main which is the name of the function.
3. () means that it is not necessary to take in any inputs from the bash command line when the program runs. You can take in arguments here if you want to give users more options from the beginning.
4. Finally, the bracket signals the beginning of the main function's code. You will notice there is a closing bracket at the bottom that shows the end of the code block.
The printf() line in the code is what is called a function call. This is what it looks like when you use a function that is separate from your main function, either that you wrote or someone else wrote in a library. In this case printf() is a function from the stdio library and can handle lots of different arguments between the parentheses. "Hello!\n" as the argument results in printf() displaying on the screen Hello!
The \n part is a special character and it means newline. This makes sure the next thing displayed is on it's own line. I'll get into more detail of what you can give printf() as arguments later.
The return statement is required for all functions that have a type declared before the name like int main(). An int is an integer variable type. A whole number in other words. For main() returning an int 0 is signaling the programs completion to the OS. It technically is not required that you have this in main() because most compilers will compile your program correctly without it but in all other functions with a return type it is required that they return something.
Also notice that there is a semicolon at the end of every line of code. This is required so that the compiler clearly sees the end to each individual statement.
Step 3: Variables
If you are new to programming then let me quickly explain what a variable is. A variable in programming is a chunk in the computer memory that you can name almost whatever you like where you will store a value to be used later. In C there are a few different variable types. For example a char is the smallest chunk of memory being only a byte (or 8 bits in size) Note: this is where knowing how a computer works can come in handy but if you don't understand this part you will be fine learning the basics. A char is typically used to represent a character or letter. Although technically it is just a number in memory it is represented by a character using the ASCII standard. Again you don't necessarily need to know this. There is also Int, short, long, float and double.
A variable declaration (in other words naming and reserving the chunk of memory for the variable) looks like:
<Type> <Name>;
or
<Type> <Name> = <Initial Value>;
where type is int, char, short...
A variable declaration (in other words naming and reserving the chunk of memory for the variable) looks like:
<Type> <Name>;
or
<Type> <Name> = <Initial Value>;
where type is int, char, short...
Step 4: If Statements
If statements are the way a programmer tells a computer to make a decision based on given conditions. This is one of the most powerful tools in programming. They can be used in limitless ways whether you are evaluating user input or checking if another process is done or you want to perform different actions based on the value of a single variable.
The syntax, or format, is:
if(<condition>){
}
if the <condition> between the parentheses is evaluated by the computer to be true then everything between those brackets after the if statement will be executed. Otherwise it will be skipped.
If you want to do something specific in the case that the condition is false you can do an else statement:
else{
}
Useful things to know for conditions:
the condition can simply be a number. In this case C evaluates a 0 to be false and anything else is true.
you can use special operators to make conditionals:
a == b means is variable a equal to variable b
<some condition a> && <some condition b> means condition a and condition b both have to be true in order for the whole conditional to be true. (condition a and condition b)
<some condition a> || <some condition b> means only one of the conditions has to be true (condition a or condition b)
"!" means not. you can use this like a != b which translates to a not equal to b.
also you can use <,>,<=,>= which has the meaning less than, greater than, less than or equal to, and greater than or equal to.
The syntax, or format, is:
if(<condition>){
}
if the <condition> between the parentheses is evaluated by the computer to be true then everything between those brackets after the if statement will be executed. Otherwise it will be skipped.
If you want to do something specific in the case that the condition is false you can do an else statement:
else{
}
Useful things to know for conditions:
the condition can simply be a number. In this case C evaluates a 0 to be false and anything else is true.
you can use special operators to make conditionals:
a == b means is variable a equal to variable b
<some condition a> && <some condition b> means condition a and condition b both have to be true in order for the whole conditional to be true. (condition a and condition b)
<some condition a> || <some condition b> means only one of the conditions has to be true (condition a or condition b)
"!" means not. you can use this like a != b which translates to a not equal to b.
also you can use <,>,<=,>= which has the meaning less than, greater than, less than or equal to, and greater than or equal to.
Step 5: Loops
Loops are another very powerful tool in your programming arsenal. They are used when you want to repeat an action a certain number of times but you don't want to type out all the code. There are basic loops called while loops and for loops. While loops are a little easier:
while(<condition>){
}
All the same rules for conditionals apply here.
For example you could type while(1) and this would always be true and is called an infinite while loop.
for loops have three parts. a variable initialization, a condition and then an increment or decrement of that variable you initialize:
for(i=0;i<20;i++){
}
The increment of i you see in the last part is something I haven't mentioned yet. You can type any variable name, then ++ or -- to add 1 to the value or subtract one from the value.
while(<condition>){
}
All the same rules for conditionals apply here.
For example you could type while(1) and this would always be true and is called an infinite while loop.
for loops have three parts. a variable initialization, a condition and then an increment or decrement of that variable you initialize:
for(i=0;i<20;i++){
}
The increment of i you see in the last part is something I haven't mentioned yet. You can type any variable name, then ++ or -- to add 1 to the value or subtract one from the value.
Step 6: Printf()
Unlike the picture above printf() has nothing to do with actual printers. It is the function that prints messages to the user's screen not paper. I used this in the first example and now I will explain further how to use it. As well as printing out a simple message in quotes like the first example, one can also put variables in the print statement:
printf("The value of num is: %d\n", num);
%d is a placeholder in the print statement for an integer and whatever is put after the comma will have it's value inserted there. There are other placeholers like %c for char type. You can put as many as you want as long as there are enough variables after to fill them in and they go in order.
printf("%d %d %d", num, num1, num2);
printf("The value of num is: %d\n", num);
%d is a placeholder in the print statement for an integer and whatever is put after the comma will have it's value inserted there. There are other placeholers like %c for char type. You can put as many as you want as long as there are enough variables after to fill them in and they go in order.
printf("%d %d %d", num, num1, num2);
Step 7: Scanf()
You guessed it, the scanner pictured above also isn't related to the scanf() function. This is another useful function given to you through the stdio library. It is helpful for reading user input. It's syntax is very similar to printf():
scanf("%d", &num);
The "&" is important and you have to have it in front of your variable for the value to be stored in it. This is due to a more advanced topic in C that I won't cover in this tutorial called pointers. This code looks for an integer entered and takes the first one and stores it in num. You can again put as many placeholders and variables as you like.
scanf("%d", &num);
The "&" is important and you have to have it in front of your variable for the value to be stored in it. This is due to a more advanced topic in C that I won't cover in this tutorial called pointers. This code looks for an integer entered and takes the first one and stores it in num. You can again put as many placeholders and variables as you like.
Step 8: Your Own Functions
You've seen all these functions. Now how do you write your own? Well the first thing you should know about your own functions is that they must either be written above the main function or if they are below, which is common practice, then they need to be declared above the main function. Like so:
void myFunction(int arg1, int arg2);
^ ^ ^
type name parameters
returned
void actually is a keyword that means this function doesn't actually return anything.
An example function would be:
char capitalize(char a){
return a-32;
}
this works due to the fact that char a is still a number and the ascii representation of it's capital letter is 32 away from it.
You can call this in your main function simply by typing:
capitalize(letter);
letter being a char variable in your main function.
void myFunction(int arg1, int arg2);
^ ^ ^
type name parameters
returned
void actually is a keyword that means this function doesn't actually return anything.
An example function would be:
char capitalize(char a){
return a-32;
}
this works due to the fact that char a is still a number and the ascii representation of it's capital letter is 32 away from it.
You can call this in your main function simply by typing:
capitalize(letter);
letter being a char variable in your main function.
Step 9: Arrays
Arrays can be very useful. They are chunks in memory in which to store multiple variables right next to each other. The picture shows one way to initialize one if you know all the values you want to put in it. It also shows the array index below each value. To access a specific value later you type:
array1D[2] and this would be equal to 25. Notice the size of the array is 3 but the last element has an index of 2 because array indices start at 0. And of course you can have other type arrays like char. Char is very useful as an array because what you have then is a word or message.
array1D[2] and this would be equal to 25. Notice the size of the array is 3 but the last element has an index of 2 because array indices start at 0. And of course you can have other type arrays like char. Char is very useful as an array because what you have then is a word or message.
Step 10: Comments and Documentation
The last thing I want to say about programming is that commenting and/or documenting your work is very important both for you and anyone else that may look at your code. To make a comment in your code which is text that will be ignored by the compiler you type:
//whatever comment
"//" will give you the whole line to make a comment. If you want multiple lines then:
/*
comment
comment
*/
This is very useful if you come back to some piece of your code and you can't remember how it works. The plain english comment can help a lot.
//whatever comment
"//" will give you the whole line to make a comment. If you want multiple lines then:
/*
comment
comment
*/
This is very useful if you come back to some piece of your code and you can't remember how it works. The plain english comment can help a lot.