![]() |
C tutorial
INTRODUCTION
This tutorial is for beginner programmers who want to learn C. I assume that you do not have any experience programming, just that you know how to navigate your way around windows. If you are an experienced programmer you probably just want to skip this tutorial because I made this more or less for the people who do not know how to program and are asking for tutorials. To run through this tutorial with me you will probably want to have a c/c++ compiler (either of these would work for c). I would suggest buying visual c++ if you can afford it, but that is pretty expensive so I dont expect too many people to go out and buy it. There are some pretty good compilers for free on the internet. There is one I particularly like called dev-c++. I've forgotten exactly where you can get that from but if you go to www.zdnet.com you will most likely find it. I also assume you are running Windows and know the basics of it. I have tried to set this up as easy as possible to read. I will make all of the code and other examples I put in this tutorial in code tags to make sure you know when it's code, and when it's actually part of the tutorial. Once you have gotten your c/c++ compiler you can open a new c/c++ source file and clear anything already there. Then copy and paste the following code: PHP Code:
hello world It should create a .exe version of your file where you saved your source code. If all this works you are now set to go. |
Chapter 1
Introduction Section 1.1 All c programs are comprised of functions which contain statements. Each function has its own name which it is identified by. A function is simply a set of statements which the computer executes. A statement is the actual command to your computer. Every C statement ends with a semicolon. A function consists of several parts shown below: PHP Code:
Return Types Section 1.2 In the above example Return-type declares what type of value a function returns. I will show you in a little bit the different return types in C and exactly what it means to return a value. The nameOfFunction is the identifier tagged on to this function. The name can be more or less whatever you want although there are some rules. First of all it can only contain letters of the alphabet, the numbers 0-9 or a underscore. Furthermore a digit cannot start a function name. Another important thing to keep in mind is that the C language is case sensitive. That means that Function1() and function1() are entirely different functions altogether. Arguments are information that can be passed to a function from the main body of a program. For example, refer back to the hello world program in the introduction. In the function printf(), "hello world" is an argument. Printf takes this argument, runs some processes on the computer, and finally outputs your argument onto the dos screen. Also take note of the curly braces. A function statement list begins with your opening curly brace { and closes with the closing curly brace }. Main Function Section 1.3 A C program can contain as many functions as you want it to, but it must include main() (at least for all the examples covered in this tutorial. If you ever decide to learn windows programming you will find main() is replaced by winMain().) The main() function is where everything takes place. Every function you write, or every statement must be called within the main() function for it to be executed. At the end of the main function your program will exit. Variables Section 1.4 A variable, in c, is a named location in memory that holds some data. Each variable you use must be declared. The purpose of a variable decleration is to tell the computer what type of data you will be using, how it should interpret it, and how much memory it should set aside for a specific variable. You only have to declare a variable once to be able to use it within the block of code you are working in. A variable decleration looks like this: PHP Code:
PHP Code:
char int float double void A char variable stores characters (i.e. a, d, 4, $). An int variable can hold a whole number. Floats and doubles both hold fractional numbers represnted by decimal points. The main difference between a float and a double is that the double variable can have twice the precision of a float variable. Void is a special variable-type and this will be explained later in the tutorial. For example if you want to declare an integer variable named someInteger you would declare it as such: PHP Code:
You can also initialize a variable. Intilization of a variable means give it a certain value when you declare it: PHP Code:
In C the equal sign assigns the variable on the left to whatever value is on the right. Basically if we were to say: PHP Code:
PHP Code:
Arithmetic Operators Section 1.5 A major part of any computer programming language is altering variables and making calculations with them. C has 5 basic arithmetic operators. Addition is the + sign. Subtraction is the - sign. Multiplication is the * sign. Division is the / sign. Finally % is the modulus. Addition, subtracion and multiplication work the same as they do in normal arithmetic. The division works fine with floating point numbers but with integers, if the two numbers do not divide evenly, it will give u the value of however many whole numbers can go into the divisor. For example if you did 7 divided by 2 it would give you the value of 3. This is why we have the modulus. Modulus only works for integers. It returns whatever the remainder is. 7 % 2 would give you 1. While performing arithmetic, multiplication, division, and modulus take precedence over addition and subtraction much the same as it is in algebra. You can add parenthesis around your operations to have the computer calculate in the order you want it to. For example 7+2*5 entered into the computer would give you 17, but (7+2)*5 would give you 45. This order of operations also applies to variables. Preprocessor Directives Section 1.6 You might be wondering what a line such as #include <stdio.h> means. The #include is a preprocessor directive. The #include directive is common to most c programs. stdio.h is a header file which is included in your program. A header file stores functions, and stdio.h has many you will be using. The preprocessor is not really a part of a c program, but it's more like directions to the compiler. For now the only preprocessor directive we will need to use is the #include. Later I will show you another one. Comments Section 1.7 Many programmers like to add comments to their code. Comments help clarify what their code does. Comments are not compiled, they are simply in your code as documentation for you or whoever might be reading your program. Their are two types of comments, the line comment and the block comment. The line comment is started with two forward-slashes. Anything on that same line in your code will not be compiled. The block comment is started with a forward slash and an asterisk and ended with an asterisk followed by a forward slash. Anything in between is not compiled. A block comment can take up as many lines as you would like. I have demonstrated both type of comments below: PHP Code:
Functions explained Section 1.8 If you are planning to make a c program that is not trivial you will want to write your own functions. In C their are two parts to writing a function: The function prototype and the definition of the function. The function prototype declares a function much like declaring a variable. It consists of three parts and is put before the main function. The first part of the function is your return type. The return type of your method will be whatever the function returns. For example lets say you have a function that calculate the sum of 2 numbers, and you want to assign the value of the sum to variable x. You would have a statement as such: PHP Code:
The next part of the function prototype is the method name itself. Continuing with our previous example of the function sum you would simply type the name sum. If a function simply performs a set of statements and does not need to return anything you would declare that function as void. The last part of a function prototypes is its arguments. If you need to pass some information to a function for it to do it's computations you must do so through an argument. Arguments are declared the same way as variables. Again, using our previous example we would declare the arguments as int x, int y. If you plan on using more than one argument you must seperate each argument with a comma. You can also have arguments of different types. If you wanted to do int x, double y you could do so. Functions do not require arguments. If no information needs to be passed to a function you can just type void inside the parenthesis of the function prototype. The whole function prototype of sum put together looks like this: PHP Code:
PHP Code:
You should now have a good understanding of how a c program is program is written and its elements. You should understand the concept of preprocessor directives, the main function, and how a function is written. If you have any questions pm me and I will try to help you as best as I can. Any feedback would be appreciated. If you caught me saying something wrong, please let me know. I'm not by any means a master at C, so please excuse me if I have screwed anything up. Also, expect chapter 2 in 1-2 weeks. |
Chapter 2: Input/Output and type castes
Introduction Section 2.1 Last chapter you learned many of the components of a c program. I walked you through some basic programs and tried to describe how they worked. Obviously the examples above are pretty simple. A major part in most programs is I/O. I/O stands for input/output. Input is any information that a user of a program passes to the computer and output is anything that the computer passes to the user. Most programs that you have used probably allow you to give some user-input whether it be through entering data in a database or a simple click of a mouse. This chapter I will show you how to get user input through some of C's built in functions. I will also teach you a couple of output functions. Character Input Section 2.2 In C separate functions are used to take input from a user. The code to get input for each variable type differs slightly from other variable types. This means that the function to take in an integer value would differ slightly from the function used to take in a double value which would differ from the function to take in a character. In this section I will show you two functions you can use for character input from the keyboard. First function is getchar() and it's format looks something like this: PHP Code:
Thankfully there is a solution to this problem. Under the library conio.h there is a function called getche(). It's usage is identical to that of getchar(), the only difference is that once a character is pressed it automatically continues with the program instead of waiting for the user to hit enter. Numeric Input Section 2.3 Many times, when you write a program, you require that the user enter a numeric value instead of a character value. In this case there is a function called scanf(). scanf() is a powerful and flexible function. It can take input for any of the numeric data types, and in fact it can also take character input. For now, I will only show you how to get input for an integer, double, float variable. To get integer input, use the scanf() function like this: PHP Code:
If you want to get a float from the keyboard, simply change "%d" to "%f", and if you want to get a double from the keyboard, all you need to do is use "%lf" in place of "%d". Output Section 2.4 Until now, you've been using printf(), but I haven't really told you to much about it. Well, it's finally time to go into depth about printf(). I've already covered the simplest form of printf(), which is: PHP Code:
\n next line \t tab \" double quotes \' single quote \\ backslash \? question mark You put these escape sequences into printf() like you would anything else. Let me demonstrate how to use escape sequences by a two simple programs. PHP Code:
line one line two line three Now, if we were two use the \n escape sequence to make a newline, it would look something like this: PHP Code:
line one line two line three Recall earlier, where I said that an escape sequence is a character, and that it can be assigned to a char variable. You do this by putting the escape sequence within single quotes. PHP Code:
I've now shown you how to output something that is hard-coded, but lets say you wanted to output the value of a value of a variable. printf() allows this to be done by using format specifiers. A format specifier begins with a % and determines how the argument it is referring to will be displayed. As far as I know, printf() can take an unlimited amount of arguments. Here is a list of the format specifiers that you will be using the most (I will add more as the tutorial progresses): %d integer %c character %f float %% percent sign I guess those are it for now. Here is a short, trivial program which demonstrates how to use those format specifiers correctly: PHP Code:
Here is the output: 6 f 6.00 Notice how that printf() statement is set up. The format specifiers are within the string that is supposed to be displayed, and the variables that correspond to each format specifier are then listed after the string, separated by commas. The string is one argument, and the other variables are separate arguments. Recall from Chapter 1 that each argument in a function is separated by a comma. A call to printf() can have virtually an infinite amount of format specifiers and/or escape sequences. Data Type Modifiers Section 2.5 You already know the 5 basic data types in C: char, int, float, double, and void. All of those data types, except void can be modified so that they better suit what you want to do with them. Each modifier does different things depending on what type of variable you associate the modifier with. The modifiers are: long short signed unsigned Long can be associated with ints or doubles. When associated with ints, the long modifier can have varying effects which is determined by the environment you are using and the compiler that you are using. Check your compiler's documentation if you want to know the exact effects that long will have with your ints. When associated with doubles, the long modifier basically doubles its precision. I believe that short is only associated with ints, and its effects vary as well. Again, you will have to check your compiler's documentation. The signed modifier makes an integer signed, but since integers are signed by default, it's usually pointless to use signed with integers. Signed is usually used with chars. Unsigned is used with ints or chars as well. As the name implies, using this modifiers means that the values your variables hold can't be negative. Here is an example of how to declare a variable using a data type modifier: PHP Code:
One thing that you should know is that the char data type and int data type are basically interchangeable in C. This is because a character variable actually holds a number. This number, once referenced as a character by the %c specifier, is then outputted as whichever character corresponds with that number on the ASCII table. Similarly, when you input a character with scanf(), it stores a number which corresponds on the ASCII table with the character that you entered. Try the following statements in a program: PHP Code:
PHP Code:
Type casts Section 2.7 The C programming language allows you to temporarily transform a variable type into another variable type by using type casts. Lets say you have a floating point variable that you want displayed as an integer. This can be accomplished using type casts, although you would lose the numbers precision. It could work the opposite way as well. An integer could be type casted into a float as well. The general form of a type cast looks like this (this is not actual code): PHP Code:
PHP Code:
PHP Code:
If I have done a good job teaching, you should have learned basic input/output, type casts, and data type modifiers in this chapter. If you have any questions PM me, or just post them here. As an exercise, try writing a program which prompts a user to enter a character, get the character using getche(), and then write a function to convert the character to its ASCII value. I'll post all the answers to my exercises at the very end of my tutorial, but since that can take a while if you want the answer sooner, PM me. As always, I look forward to any feedback. |
Chapter 3: Loops and Conditionals
Introduction Section 3.1 So far all the programs that we've written have gone in a straight line. By that, I mean that each and every program has had a preselected path that it went through once, and that was it. After that the program would end. These types of programs are rare in real life applications. Most programs have to do one thing if the user acts one way, and do another thing if the user were to act a different way. Also, many times a program has to do a certain command, or a group of commands multiple times. You could write the statements over and over again, but this can get rather tedious, and after a while you would get fed up of doing so. In this chapter I will show you how to tell the computer to make a choice based on a variable, and how to tell the computer to run a set of statements multiple times in a not-so tedious manner. Loops Section 3.2 There are three types of loops I will show you: the for loop, while loop, and do loop, but before you can use these you must know what they are. A loop executes a set of commands multiple times. The general contents of a loop are a set of statements, a test variable or control variable, a condition, and usually an increment or decrement. The test variable holds a value which is tested against the condition. As long as the condition is met, the loop will continue executing the statements within. Generally, after all the statements in the loop are executed, the test variable is either incremented or decremented, and is tested against the condition again. Once the condition is not met, the loop is exited, and the computer will then go on with the rest of the program. This might presently seem complex to you, but once I show you how it works it will become a lot easier to understand. The format of a loop is as follows (this is not actual code): PHP Code:
Now, you might be wondering how the condition is tested. The condition is tested using a relational operator. There are 6 relational operators that you need to know: > greater than < less than >= greater than or equal to <= less than or equal to == equal to != not equal to The "greater than" operator, and "less than" operator, are just as you would see and use them in basic algebra. The "greater than or equal to" operator, and "less than or equal to operator", look slightly different than what you would see in basic algebra, but have the same concept. The "equal to" operator can get slightly confusing. Many times, a new programmer will confuse it with a single equal sign, or assignment operator. A single equal sign is used to assign a value to a variable, and the double equal signs are used for comparisons. The not equal to sign is pretty self explanatory. I will give you examples of how to use these in the next section when we actually use real loops. The other thing you need to know about is the increment. An increment looks something like this: PHP Code:
There is a shorthand for increments and decrements. PHP Code:
There is another shorthand, but this only works if you want to increment or decrement by one. PHP Code:
While loop Section 3.3 The first loop you will learn is the while loop. It looks something like this (not actual code): PHP Code:
PHP Code:
Within main, we declare the control variable, calling it "controlVariable", and initialize it with the value of one, since we want to print the numbers one through ten. On a side-note, the control variable doesn't have to be called "controlVariable'. I called it that hear for clarity. In reality, it can be called anything that any other variable could be called. The next line declares that a while loop will proceed as long as the condition in the parenthesis is met. In this case, the condition that needs to be met for the loop to start is that control variable must be less than or equal to 10. If that condition is met, then the statements inside the curly braces will then be executed. In this case, it prints out the value of controlVariable, and then increments controlVariable by one. You must remember to increment or decrement your control variable or you will be stuck in an infinite loop, which is a loop which goes on forever. Another thing to remember is you can put the increment anywhere you want in the loop. It doesn't necessarily have to be at the end of the loop. After the increment, it tests controlVariable against the condition again. This process occurs over and over until the condition is not met, in which case the loop is exited, and the rest of the program goes on. Once the loop has exited, the value of controlVariable is 10, not 1 like it was originally. For loop Section 3.4 The for loop is syntactically different from the while loop, but it will get the job accomplished just as well as a while loop, and is in fact the loop that I use most in my code. Its general format is (not actual code): PHP Code:
Here is the same program we wrote for the while loop, except using a for loop: PHP Code:
PHP Code:
The next part in parenthesis, the condition, is just about identical to what it would be in the while loop. Remember to separate your control variable and your condition with a semicolon. The same applies for you condition and increment. The increment is a little funny in this loop. Recall how I earlier told you that there is a slight difference between ++x, and x++. That difference comes in hear. If you were to use x++, then the loop would run through all statements and then increment the control variable, but if you were to say ++x, it would increment the variable before it ran all the statements. The loop runs similar to the while loop. It tests the condition, and then, depending on how you have decided to increment your control variable, it either increments the control variable and then executes all the statements, or it executes all the statements first, and then increments the control variable. If we were to say ++controlVariable instead of controlVariable++, then this program would output the number two through eleven, and not one through ten. Do loop Section 3.5 The final loop I will tell you about is the do loop. This loop deviates from the others, because the condition is tested at the end of this loop. This means that this loop will always be executed at least once. Here is it's general format: PHP Code:
We'll use the same program again as an example. PHP Code:
Just to clarify, the process that this loop takes is it runs through all the statements and increment, and then tests. So, on its first pass through the loop, it prints out one to the command line, and then increments controlVariable to two. When the test is performed, it tests whether two is less than or equal to 10. Conditionals Section 3.6 What if you wanted the program to perform a certain set of statements if one condition were met, and a completely different set of statements if a different condition was met? Do to this, you use conditionals. In the following sections, I will attempt to familiarize you with the if/else and the switch. You will see conditionals in just about any real world program. If Section 3.7 The if statement is more flexible, and in my opinion, more convenient to use out of the two conditionals that I will be showing you. It works by testing a variable against a condition, much the same way as the loops you learned about earlier in the chapter. It uses the same relational operators, in a similar format. One thing you should know about values produced by relational operations is that anything that is true returns as 1, and anything false return 0. The if statement's general format is as follows: PHP Code:
PHP Code:
You can add as many if statements as you want in a program. Not only that, but you can add as many if statements as you want for one variable. I will rewrite the program above to where it prints, "you picked one," if one was entered at the keyboard, and "you picked two" if two was entered at the keyboard. PHP Code:
Before I continue to teach you more about the if statement, I must teach you about logical operators, which can help relational operators. Here are the logical operators: && and ! not || or If you use the and operator, then condition one, and condition two must be met for the entire condition to be true. If you use the or operator, then only one condition has to be met for the entire condition to be true. Remember learning about order of operations in junior high? Well, it's back. Logical and relational operators also have an order of operation. Keep in mind, that just like arithmetic, you can explicitly override the order by using parenthesis. I have listed the order of operations from highest to lowest: not greater than, greater than or equal to, less than, less than or equal to equal to, not equal to and or The not operator is slightly hard to explain, so I will demonstrate how it is used in a few moments, and attempt to explain it from there. First, an example of the and operator. I will rewrite our program above, so if the user enters 1, then the program outputs, "you picked one," if the user enters two, the program will output "you picked two," and if the user enters any other number, the program will output "you picked a number other than one or two." PHP Code:
Now for the not operator. The last if statement in the previous program could be rewritten as: PHP Code:
else Section 3.8 The else statement really has two forms: else, and else-if. The else statement really expands the if statement. It cannot be used unless an if statement has just been used. First we'll cover the else-if statement. Instead of using multiple if statements, like we did above, we could simply use an else if statement. The else-if statement is used if the programmer wants to test additional conditions after the initial one, which is in the original if statement, has been tested. Here is the general format: PHP Code:
Now, doing it this way is a lot more efficient than doing it by only if statements. Lets say, for example, that the second statement is true. Once it reaches this statement, the program will not test condition 3, and condition 4. It will just skip those conditions and continue with the rest of the code. Were these all if statements, each condition would have to be tested before normal execution of the program would ensue. Lets take the program we wrote before for the if statements, and properly change the if statements into if-else statements. PHP Code:
Now, if the else statement stands alone, it is used as a last resort. If none of the conditions in the ifs or if-elses are met, then the statements that are associated with the else statement are executed. So, the general format would look something like this: PHP Code:
PHP Code:
Switch Section 3.9 The switch statement is another conditional. It can only test integers and characters, and it can only test for equality. Its syntax is slightly different than what you saw for the if statement. The switch statement doesn't use any of the relational operators, since it can only test equality. Its general format is like this: PHP Code:
hen, you type the keyword case, followed by a value. This value is what the variable will be tested against. If the value that is by the case keyword matches the value in the variable, then all the statements in that are below that case are performed. Remember, that only integers and characters can be tested. If you test characters, you must enclose the value that you are testing against (the value next to the case) in single quotes. The default, which is below the third case statement, executes if none of the values next to the cases matches the value held by the variable that you are testing. A default is not mandatory. If you choose to not use a default, and no match is found with the values that are associated with the cases, then nothing happens in the switch statement, and the execution of the program continues as normal. Now, in this program you are presented with a new statement, the break. It has many uses, but here, it is used to signal the end of a particular case. This is mandatory, otherwise your program will be buggy. Once a match between the value a variable holds, and the value next to a case, then it executes all statements inside that case until a break is found. If a break is not found it goes on to the next case, and proceeds to execute its statements. It keeps going in this manner until a break statement is found. A break is not required under default. Now, as usual, for an example. Lets use the same program we have been using for conditionals so far, and change it to where it uses the switch statement, instead of the if-else statements. PHP Code:
Nested Loops/if statements section 3.10 Loops and if statements can be part of a separate loop, or if statement. These are called nested loops, or nested if statements. First thing you need to know is that loops can be within if statements, and if statements can be inside loops, and the program would run just as you would expect. It would be no different than placing a set of statements inside the loop, or if statement. Here is an example of a loop within an if statement: PHP Code:
If an if statement is within the curly braces of another if, else, or else if statement, then it is said to be nested in the original if statement. The way a nested if statement works is that the outer if statement (the if statement that is declared first) is tested. If the condition is true in the outer if statement, it then goes into the inner if-statement, and tests that. There can be virtually an unlimited number of nested if statements, but you should check your compiler's documentation for more information. Here is the general form of a nested if-statement: PHP Code:
The principal of nested loops is based upon the same idea as nested if-statements. There is an outer loop, and an inner loop (or multiple inner loops if you desire). Any type of loop can be nested, but for the purpose of this article, I will only demonstrate with for loops, and you can experiment with other loops later. The way a nested loop works is, once the outer loop is initiated, it goes into the inner loop and makes one complete round through the inner loop until the control variable no longer meets the condition needed to make the inner loop run. Then, the control variable for the outer loop is incremented, and the cycle repeats itself. It keeps going until the control variable in the outer loop does not meet the conditions required for the loop to keep cycling. Here is the general format of a nested loop: PHP Code:
PHP Code:
Break/Continue Section 3.11 There are two statements which allow you to expand the control you have over a loop. These two are the break and continue statement. Both statements would be placed inside the loop as needed. The break statement exits the loop altogether, and continues on with the rest of the program. The continue statement, on the other hand, exits only the cycle, and begins the next iteration of the loop, as long as the control variable still meets the condition. It doesn't execute any code in between itself and the end of the loop. In while loops, and do-while loops, the continue statement simply goes to the beginning of the loop without performing doing anything else. In the case of a for loop, it will perform the increment, and then start the next iteration of the loop. Here is a little program that adds numbers forever, unless explicitly told to exit by the user. PHP Code:
The program begins by starting the outer loop as soon as we enter main. A for loop with nothing inside means that there is no control variable, no condition, and since there is no control variable, there is no increment. It is an infinite loop, which continues forever, or until it hits a break statement. The outer loop asks for two integers, adds them, and outputs their sum. After that, an integer variable, test, is declared. The test variable is the one which holds the value of whether the user wants to perform another calculation or not. Once we are in the inner loop, the computer asks the user to press one if they want to perform another operation, or two if they want to exit. It uses an if statement to perform a different set of statements for the two choices. If the user inputted one, the break command exits the inner loop. It then goes into the outer loop, and sees that the first command is another test. It once again tests if the variable test holds the value "1". If it does, it uses the continue command. This causes the next iteration of the outer loop to be initiated. If the user selected to exit the program by inputting "2", the inner loop is once again exited using the break command. Again, once in the outer loop, it sees that the first command tests the variable test against one. This will not be true, so it will go on to the else statement, where it breaks from the outer loop, and thus exiting the program. If the user does not select one or two, the continue command in the inner loop causes the entire loop to be run through again until the user either inputs a one or a two. Scope Section 3.12 An important thing to know about variables is how to know the scope of a variable. The scope of a variable defines in which sections of code the variable can be referenced. A variable can either be a global variable, or a local variable. A global variable is declared outside of any functions, including the main function, and a local variable is declared in a certain function. A global variable can be referenced from anywhere in the program. It is generally a good idea to avoid using global variables whenever possible, but they are required at certain times. A local variable belongs only to a function. It can be accessed or referenced by any statement in that function, it can be manipulated in that function, used for calculations in that function, and whatever other uses you can think of for a variable, but it can only be used in the particular function that it was declared in. If you try to access it outside of that particular function, you will get an error while compiling. Also, since local variables or only accessible within their own particular function, it is perfectly alright to have two variables with the same name, as long as they are in separate functions. Also, if a variable is declared inside a block of loop (within a set of curly braces), it is only accessible by that block. If you try to access it from outside its block, you will get an error. Consider this example (not actual code): PHP Code:
C conventions Section 3.13 here are a few C conventions that programmers like to follow. Of course, this is only convention, and there is no requirement that says you must follow it, but it is usually a good habit. The first convention is that programmers never start a variable name or a function name with a capital letter. Secondly, keep your variable names and function names something that relates to what the variable's or function's purpose is. This is so if you want to come back and read your code six months later, it is easy for you to understand. You are not going to remember every single variable in a piece of code that you have written after a while. Unfortunately, I have not demonstrated this convention too well. Also, when naming characters, if you want a function name or variable name to consist of more than one word, a programmer usually does this by capitalizing the first letter of every word, except for the first word. Third, it is a good habit to tab your code over when beginning a block, as I have been doing thus far. It makes your code cleaner, and easier to read. Basically, just keep your code as clean and easy to read as possible. Conclusion Section 3.14 You have learned quite a bit in this chapter. You will be surprised at how much you can already make your computer do. Conditionals and loops are one of the biggest parts in any programming language. To test your knowledge, write a program that allows the user to input an integer. Calculate every single prime number up to the number that the user has entered. Use functions wherever you deem necessary. This is challenging, but will help you practice just about everything you have learned so far. As always, leave me some feedback. I like to know what you think. If you need help with the challenge, post here. If I made a mistake, let me know. |
Chapter 4: Arrays & Strings
Disclaimer: This is not meant to be a comprehensive guide to programming C. I guess I should've put that in the first chapter. I'm by no means a great C programmer. A lot of people in IRC have not liked this tutorial that I'm writing too much. If you are serious about getting into C programming, I suggest picking up a book written by a professional. Now, on a side-note, I don't think my tutorial is that bad, so feel free to follow me, but don't take every single thing that I say here to heart. There's a good possibility that what I'm doing isn't the best way to do things. Anyway, without further ado, lets get into the chapter. Introduction Section 4.1 So far we've been doing a lot of work with numbers and single characters. That's all good, since you have to have the basics down before you get too deep into the language. Now, we all know that modern programs usually aren't strictly single-number or single-character based. They usually allow you to input words. Also, many times you'll have a list of numbers that you're going to need to perform calculations on. Using individual variables for every single one would get to be extremely tedious. In this chapter, I hope to show you how to deal with strings, and also how to deal with arrays of numbers more efficiently than using individual variables to store the list of numbers. I will do so by introducing the concept of arrays to you. Arrays are, simply, a list of variables of the same type (int, char, double etc.) that are addressed by using a common name. An individual variable held in an array is called an element. The list of variables are usually stored in contiguous memory locations. For instance, lets say you have an array that holds three elements. If the first element is located at 'memory address 1', then the next element would be located at 'memory address 2', and the last element would be stored at 'memory address 3'. If you don't understand how an array works yet, no need to fear. As always, once you get acquainted with them, it should all fall into place for you, and you will have a much better understanding of how they work once we get into pointers. That will come in the next chapter, though. One-dimensional arrays Section 4.2 When you declare an array, it's quite similar to declaring a variable. You have the type of the array first, followed by the name we will be using to address the array, followed by an open-bracket, then a number denoting the size of the array, followed by a closed bracket, and then, of course, a semicolon. All that the size of an array means is how many elements that the array can hold. So, lets say you declared an array with the size of 20. It would be capable of holding 20 different elements, or variables. Here's the general format of how you'd declare an array: PHP Code:
PHP Code:
Now, we want to be able to actually put numbers in there. What good would that do us if we couldn't use numbers? There are many ways of assigning a number to each individual element in an array. The easiest way to pick out a certain element and assign a number to it would be doing this: PHP Code:
You can use this simple indexing scheme with normal functions. You can use the individual elements just as you would any other variable, so it would be perfectly fine using them with scanf() or printf(). Now if you want to initialize an array you would do so like this: PHP Code:
Now, I'm going to write a simple program that prompts a user for 10 grades, inputs them to a variable, and finally asks the user to input an assignment number to find out what grade they made on that assignment. PHP Code:
Strings Section 4.3 Strings Basics Section 4.3.1 Strings, in C, are just an array of characters, which are terminated by a null byte. A null byte in C is simply a byte which contains 0 (zero, not the letter O). That means when you declare a string, it must be able to hold one character extra than the largest string it needs to hold, as it must be able to hold the null value at the end of the array, which denotes that the string has ended. Lets say, for example, we have a null-terminated string, c, which holds the value that. We would need an array which could hold 5 char variables. Heres what each individual element in the array would hold: c[0] would hold the character t, c[1] would hold the character h, c[2] would hold the character a, c[3] would hold the character t, and c[4] would hold the value \0. The \0 is how you typically assign the null variable. Initializing Strings Section 4.3.2 Now, initializing a string can be done very much the same way as initializing a regular array, but thats not the easiest way to do it, and I will show you why later. For learning purposes, here is an example of how to initialize a string in the not-so-efficient way: PHP Code:
There is a much easier way to initialize a string, though. Instead of putting every value in single quotes, separated by a comma, you can simply use double-quotes. When you do this, you dont need to separate every value by a comma, and you dont need to add the null character at the end of the string. C takes care of that for you. Heres an example: PHP Code:
There are many ways to get string input, but the function that I use is gets(). gets() is located under the stdio.h header file. The gets() function is unbelievably simple. It takes one argument, the name of the array you want to store the value that the function gets. It reads characters from the keyboard until you press enter. The value for enter is not stored, and is instead replaced with a null-terminator. There is one potential problem with gets(). It provides no bounds-checking whatsoever, so if you were to enter more characters than the array is capable of holding, then the array would overflow, and the extra characters could be saved over other memory that is important to the program, possibly causing the program to crash. Later, in this tutorial, I will show you alternatives to gets(), but for now, it should do. Now, you can output a string in many ways as well, but for now well continue to use printf(). I will show you other functions for outputting a string later. printf() works just as weve been using it all along, except for the fact that instead of using the %d format specifier like we have been thus far, we will use %s. Heres a short and simple program demonstrating how to use gets() and printf(). All this program will do is ask a user to input any string they want up to 20 characters, and print it back out to them. PHP Code:
Now, aside from basic input/output, there are four string functions that you should commit to memory, and that you will probably use fairly often. These are strcmp(), strlen(), strcpy(), and strcat(), all of which lie in the string.h header file. I will cover what each of these functions do in the following paragraphs. strcmp() simply compares to see if two strings are the same. This function is case-sensitive. strcmp() takes two arguments, both arrays of chars. It returns 0 (zero) if the strings are the same, less than zero if the first argument would appear before the second argument in the dictionary, and greater than zero if the first argument would appear after the second argument in the dictionary. Simple. Heres the general format: PHP Code:
PHP Code:
PHP Code:
PHP Code:
PHP Code:
str2. Heres a simple program to demonstrate its usage: PHP Code:
And last, but not least, is our strcat() function. It performs concatenation on a string. All concatenation is, is the process of taking the contents of one string, and tagging it along to the end of another. strcat() takes two arguments. It takes the contents of the second argument, and adds it along to the end of the first argument. Here it is in action: PHP Code:
Multi-dimensional arrays Section 4.4 A two-dimensional array is basically just an array of arrays. That probably sounds pretty confusing, but dont worry; youll see what I mean soon enough. Using a two-dimensional array is not much different than using a one-dimensional array. You simply add another set of brackets. Heres a two-dimensional int array: PHP Code:
Everything stored in a two-dimensional array is still done in contiguous memory. The number on the right changes quicker than the number on the left. Heres how the above example would look in memory: x[0][0] = location 1 x[0][1] = location 2 x[0][2] = location 3 x[1][0] = location 4 x[1][1] = location 5 x[1][2] = location 6 x[2][0] = location 7 x[2][1] = location 8 x[2][2] = location 9 Of course, in reality the memory address would be something more like 0x10000, not location 1, but you get the picture. In memory, the array x[3][3]; would be the exact same thing as x[9]; but two-dimensional arrays provide a nice way to address things. You are free to add as many dimensions to an array as you want, for all practical purposes. All you have to do to add additional dimensions is add the size of the new dimension along with the declaration of the array. The rightmost dimension changes quickest in memory. You may have been wondering how to create an array of strings. Two-dimensional arrays are the answer. Heres an example of an array of strings: PHP Code:
PHP Code:
PHP Code:
To demonstrate this in a real life example, Ive made a program that asks for five words as input, sorts them alphabetically, and prints them back out for the user. PHP Code:
The first part should be pretty easy for you to understand by now. The first thing this code does is declare a two-dimensional array, called words, which is capable of holding five words, each twenty characters long. After that, it prompts the user to input five different words. It goes into a loop, which will repeat five times. Each time the loop runs through, the gets() function is called. When it says gets(words[i]); all its doing is taking the input the user gives, and putting it in [i]words. i of course is however many times the loop has iterated. Now comes sorting, the tricky part. The type of sort that Ive used is called a bubble sort. It uses a nested loop for the sorting. What it does is it runs through the list, comparing each string with the one stored next to it. If the one stored next to it comes before lexicographically, then it swaps the position of the two strings. It goes through the entire list of strings. It repeats itself 4 times, thus making sure that the list is, in fact, sorted. Take a look inside the loop, and lets go through the code to find out how it works. If strcmp() returns greater than one (which means words[j+1] comes before words[j] lexicographically) then the two strings swap positions. The way they are swapped deserves some attention. First a new string, called temp, is created. It is used to store the word at words[j+1]. After that we copy words[j] into words[j+1]. We now have one of the strings exactly where we want, and the other stored in a temporary array. All thats left from there is copying temp into words[j] and the swap is done. If you dont quite understand how the bubble sort works right now, dont fret. I hadnt originally planned on covering the bubble sort in this tutorial. If you want more information on how the bubble sort works, google it. Always remember, Google is a programmers best friend. Conclusion Section 4.5 Hopefully you have an understanding of arrays now. Keep up your programming skills by making everything you can write. If you have any questions, suggestions, or just want to talk, feel free to PM me. Id like to hear what you think. |
All times are GMT -6. The time now is 12:21 PM. |
Powered by vBulletin® Version 3.8.2
Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
This site is best seen with your eyes open.