Zelaron Gaming Forum  
Stats Arcade Portal Forum FAQ Members List Social Groups Calendar Search Today's Posts Mark Forums Read
Go Back   Zelaron Gaming Forum > The Zelaron Nexus > Science and Art > Tech Help

 
 
Thread Tools Display Modes

 
C tutorial
 
Posted 2004-06-26, 11:35 PM
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 don’t 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:
#include <stdio.h>
#include <conio.h>

int main(void)
{
   
printf("hello world");
   
getche();
   return 
0;

Once you have done that the next step is to compile. Each compiler differs a little on how to do this but if you can't figure it out look at the help file along with your compiler. For dev-c++ there is a drop-down menu in between projects and options callled execute. Click on that and you will see a command called compile. If you get errors compiling pm (private message) me and I will see if I can help you out. After you compile go back to the execute drop-down menu and run. It should say:

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.

Last edited by Demosthenes; 2004-07-21 at 12:33 PM.
Old
Profile PM WWW Search
Demosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to be
 
Demosthenes
 



 
 
Posted 2004-06-26, 11:36 PM in reply to Demosthenes's post "C tutorial"
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:
Retutn-type nameOfFunction(arguments)
{
    
statement 1;
    
statement 2;
    
statement 3;
    ...

Remember that this is not actual code, this is just a short example of what a function would look like.

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:
data-type variable-name
or

PHP Code:
data-type variable-name someValue
C has 5 basic data types listed below:


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:
int someInteger
The keyword int tells the computer to set aside memory for an integer variable, someInteger is the name you give it and all statements must end with a semicolon so there you have it.

You can also initialize a variable. Intilization of a variable means give it a certain value when you declare it:

PHP Code:
int someInteger 8;
    
char someChar 'a'
Initialization is the basic variable decleration followed by an equal sign and then a value. When intializing a char you must encase the value within single-quotes.

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:
z=2+3
then z would have the value of 5. Also consider this short program:

PHP Code:
#include <stdio.h>

int main(void)
{
    
int z 5;
    
int x 12;
    
x;
    return 
0;

At the end of this short program z would have the value of 17 because it says that z becomes the value of whatever z was before and x. Since those were 12 and 5 it becomes 17.

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:

#include <stdio.h> // this is a preprocessor directive

int main(void)
{
    
printf("hello"); //i can add as much to this line as I want now and it will do nothing
    // printf("world"); nothing on this line will print because the comment is before printf
    /*
    printf("This");
    printf("does");
    printf("not");
    printf("print");
    I am in the middle of a block comment so write now I can say whatever I want
    I end the block comment on the next line
    */ 
    
    
return 0;

Obviously that is not how comments are used but that should give you an example of how to use each type of comment. All that the program above will do is display hello on your dos screen.

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:
x=sum(2,4); 
Since this is returning an integer value (the sum of 2 and 4) you will want the return type to be int. If you wanted a double return type or a char return type you could also do so using the same method.

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:
int sum(int xint y); 
Ofcourse the computer doesn't know what to do with sum yet. You must define the process a function needs to take below the main method. The first line of a function definition is it's prototype again. After that you have a curly-bracket and you define your function. If your function needs to return a value you put that as the last line of a definition. Then you close your function with a curly bracket. I will write a program that uses our sum function and prints it out on the screen.

PHP Code:
#include <stdio.h>
    
int sum(int xint y);  // function prototype

int main(void)
{
    
int x;  // the variable you will assign the value of sum to
    
x=sum(2,4); // assigns the value of 6 to x
    
printf("%d"x); //prints 6 onto your screen
    
return 0;  // return statement for function main
}

    
int sum(int xint y)  // notice you don't put a semicolon here
{
    
int z;
    
z=x+y;  // z is assigned the value of whatever x + y is
    
return z;  // you return the value of z
}  // end of program 
Conclusion Section 1.9

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.

Last edited by Demosthenes; 2004-07-21 at 12:35 PM.
Old
Profile PM WWW Search
Demosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to be
 
Demosthenes
 



 
 
Posted 2004-07-21, 12:32 PM in reply to Demosthenes's post starting "Chapter 1 Introduction Section 1.1..."
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:
char ch getchar(); 
That statement takes whatever is typed onto the keyboard and assigns it to ch. Unfortunately there is a drawback to this function. Once a user has input a character it waits for the user to hit enter before it executes the function. If you tried to type many characters before you hit enter in our previous example, getchar() would take the first character you typed and assign that to ch. A user of a program that uses the getchar() function could easily be confused by this unless he is properly instructed on how to use the program.

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:
int num;
scanf("%d", &num); 
The first argument is a string which tells the function which type of variable the second argument will be. "%d" lets the function know that it should expect an integer input. The first argument must be in double-quotes. The second argument is the name of the variable. It must be followed by &. I will explain why in a different chapter. If you typed that segment of code above into your compiler, compiled, and ran it, it would wait for the user to enter a number, take the value and assign it to the variable num. It is always a good idea to prompt your users to let them know exactly what type of input you are looking for using printf().

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:
printf("Whatever you want to output"); 
Now it's time to expand on the capabilities of printf(). What if you wanted to tell printf() to go to the next line, or put double quotes as part of the output. The way to tell the function to do those things is by using escape sequences. Escape sequence starts with a backslash which is followed by a character or characters which tell the function how to act. Escape sequences act as characters for the most part, meaning that they can be assigned to a character variable. Here are some of the escape sequences:


\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:
#include <stdio.h>
    
int main(void)
{
    
printf(" line one line two line three");
    return 
0;

Prints:


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:
#include <stdio.h>
    
int main(void)
{
    
printf(" line one \n line two \n line three");
    return 
0;

This would print:


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:
char c '\t' 
That assigns the tab escape sequence to the variable c.

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:
#include <stdio.h>

int main(void)
{
    
int i 6;
    
char c 'f';
    
float x 6.00;
    
printf("Here is the output: %d %c %f",  icx); 

    return 
0;

The output to that program would be:

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:
unsigned int x
A little info about char Section 2.6

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:
char ch 'K';
printf("%d"ch); 
Look at the output. Now try this:

PHP Code:
int i 75;
printf("%c"i); 
For the first set of statements, the output should have been 75. For the second set of statements the output should be K.

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:
(typevalue 
Here is a short little program which assigns a value to a double variable, and then type casts it into an integer:

PHP Code:
#include <stdio.h>
    
int main(void)
{
    
double d 6.2;
    
int x = (int) d// the double variable d is casted into an integer
    
printf("%d"x);
    return 
0;

This could also be rewritten as:

PHP Code:
#include <stdio.h>

int main(void)
{
    
double d 6.2;
    
printf("%d", (int) d// the type cast is in the function itself this time
    
return 0;

Conclusion Section 2.8

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.
Old
Profile PM WWW Search
Demosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to be
 
Demosthenes
 



 
 
Posted 2004-07-21, 12:44 PM in reply to Demosthenes's post starting "Chapter 2: Input/Output and type castes..."
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:
nameOfLoop(condition)
{
    
statement 1;
    
statement 2;
    
statement 3;
    
statement 4;
    .......
    
increment;

It's a simple concept.

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:
x=x+1
All that means is that the value of one is being added to the previous value of x. So, if x was 10 before, after that statement executes, it would be 11. You could decrement the same way, all you would need to do would be to substitute the minus sign in place of the plus sign. If you really wanted, a multiplication symbol, or division symbol could also be placed there, although I can't really thing of any real uses for those. You could also increment or decrement by any number, not just one.

There is a shorthand for increments and decrements.

PHP Code:
x+=1// same thing as x=x+1
x-=1// same thing as x=x-1 
Again, you could use any number for increments. x+=3 would be perfectly alright.

There is another shorthand, but this only works if you want to increment or decrement by one.

PHP Code:
x++; // increments x by 1
x--; // decrements x by 1
++x// increments x by 1
--x// decrements x by 1 
Remember, that this only works if you want to increment or decrement by one. x+++ will not increment by 2, and your compiler would most likely give you a syntax error if you tried that. There is a slight difference between x++ and ++x, but I will cover that when I am covering for loops.

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:
while(condition)
{
    
statement 1;
    
statement 2;
    .....
    
increment;

The first part of the loop is the keyword while. This is the start of the while loop. The condition, enclosed in parenthesis, follows the while keyword. Remember, this uses one of the relational operators. Afterwords, there is an opening curly brace, followed by a set of statements that the programmer wants the program to execute. After that, the test variable is incremented. Here is a real program that prints the numbers 1-10, going to the next line after every number, using a while loop.

PHP Code:
#include <stdio.h>

int main(void)
{
    
int controlVariable 1// declares the test variable and sets it's value to 0
    
    
while(controlVariable <= 10// as long as control variable is less than or equal to 10
    
{
  
printf("%d\n"controlVariable);  // prints value of control variable
  
controlVariable++;  // increments control variable by one
    
}  // ends while loop
  
    
return 0;  

An easy program, right? It starts off by including any header files required for the program like we have been doing for every program, and then starts main.

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:
for(control variableconditionincrement)
{
    
statement 1;
    
statement 2;
    ..........

This loop starts with the keyword for, and is followed by parenthesis. Now, what goes inside the parenthesis is where this loop gets slightly tricky. There are three things that must go inside the parenthesis, instead of just one as was the case in the while loop. Every single element that is placed inside the parenthesis is separated by a semicolon. The first element in there is the control variable. The control variable isn't declared, or initialized here, but you must put its name there, and you can assign it a value if you want. Next is the condition, which is no different from the condition in the while loop. The last element with the parenthesis is the increment. Once that is done, you don't have to worry about incrementing after all the statements in the loop. Only thing to do after the increment is put the statements which you want looped, encapsulated in curly braces.

Here is the same program we wrote for the while loop, except using a for loop:

PHP Code:
#include <stdio.h>
    
int main(void)
{
    
int controlVariable=1// declares the control variable
    
for(controlVariable;controlVariable<=10;controlVariable++) // take note of the setup    
    
{
  
printf("%d\n"controlVariable); // prints number
    
}
    
    return 
0;

I'm going to rewrite this program so that the value of controlVariable is assigned within the parenthesis themselves, for demonstration purposes.

PHP Code:
#include <stdio.h>

int main(void)
{
    
int controlVariable;    
    for(
controlVariable=1;controlVariable<=10;controlVariable++) // notice the subtle change
    
{
  
printf("%d\n"controlVariable);
    }

    return 
0;

Similar to the first program, the control variable is declared outside the loop. You have to remember, the first thing that goes in the parenthesis is the name of the control variable. Optionally, you can add a value along with it, as I have demonstrated in the second program, but it is not essential to the loop. It is always a good idea to give your control variable a starting value no matter which loop you are using, because if you do not, then the control variable could start with just about any value possible, the reason being that if a variable is not assigned a value, then it just uses the value already in memory from a program that has been previously run.

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:
do
{
    
statement 1;
    
statement 2;
    .....
    
increment;
} while(
condition); 
The do keyword starts it off, followed by a curly brace. Inside the curly braces, you put all the statements you want to, and then increment. Again, remember to increment, or your program will be stuck in an infinite loop. After incrementing, you follow with your closing curly brace. Directly following that, you have the condition just as you would for a while loop, except that this time the expression is followed by a semicolon; something that none of the other loops are followed by. Remember, the condition is tested at the end of this loop.

We'll use the same program again as an example.

PHP Code:
#include <stdio.h>

int main(void)
{
    
int controlVariable=1;
    do
    {
  
printf("%d\n"controlVariable);
  
controlVariable++;
    } while(
controlVariable<=10);

Easy. The control variable is declared outside the loop and is given a value. Then you initiate the loop with the do keyword. Inside the curly braces we have our printf() statement, and our increment. After that, we have the condition, which is just like the writing a while loop, except with a semicolon to end it.

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:
if(condition)
{
    
statement 1;
    
statement 2;
    ...

I will write a simple program which demonstrates the use of an if statement. All it does is say, "you picked one," if the user inputs the number one, and nothing if the user doesn't enter number 1.

PHP Code:
#include <stdio.h>

int main(void)
{
    
int x;
    
    
printf("please enter a number\n");
    
scanf("%d", &x);

    if(
x==1)
    {
  
printf("you picked one");
    }

    return 
0;

The program above is another simple program. It declares a variable, x, and then prompts the user for a numerical value. Once the number is entered, it is tested. The condition to pass the test is that x must equal one. If x equals one, then the program outputs, "you picked one," and if it doesn't, it simply exits.

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:
#include <stdio.h>

int main(void)
{
    
int x;
  
    
printf(please enter a number\n");
    scanf("
%d", &x);
    
    if(x==1)
    {
  printf("
you picked one");
    }
  
    if(x==2)
    {
  printf("
you picked two");
    }

    return 0;

Exact same code as the first program, the only thing added was the test for if x equals two, and the statement that needs to be performed if that condition is met. The way the program would run is, it would ask for input, and then first test against one. If that condition is met it will print, "you picked one." Then, regardless of whether the above statement was met or not, it would perform the second test. If that condition is met, then it will print, "you picked two." This is not the most efficient way to do this, though, and as programmers, we want to do everything as efficiently as possible. I will show you another way to do this in the next section.

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:
#include <stdio.h>

int main(void)
{
    
int x;

    
printf("please enter a number\n");
    
scanf("%d", &x);
  
    if(
x==1)
    {
  
printf("you picked one");
    }

    if(
x==2)
    {
  
printf("you picked two");
    }

    if(
x!=&& x!=2// implementation of the and operator
    
{
  
printf("You picked a number other than one or two.");
    }

    return 
0;

The program runs just as expected. Tests for x equaling one, and then two. Then it reaches the last if statement. Here, it tests if x is not equal to one, and if x is not equal to two. If both of these statements are true, then the program proceeds to execute the printf() statement.

Now for the not operator. The last if statement in the previous program could be rewritten as:

PHP Code:
if(!(x==|| x==2)
{
    
printf("you picked a number other than one or two.");

This does the same thing. Just read it from the inside to the outside. This statement is true if x is not equal to one or two.

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:
if(condition 1)
{
    
statement 1;
    
statement 2;
    ...
}
    
else if(
condition 2)
{
    
statement 1;
    
statement 2;
    ...
}
    
else if(
condition 3)
{
    
statement 1;
    
statement 2;
    ...
}

else if(
condition 4)
{
    
statement 1;
    
statement 2;
    ...

Remember, you can have a lot more than four else-if statements in a set if you want. You can put as many else-if statements as you want in a set.

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:
#include <stdio.h>

int main(void)
{
    
int x;
  
    
printf("please enter a number");
    
scanf("%d", &x);

    if(
x==1)
    {
  
printf("you picked one");
    }

    else if(
x==2)
    {
  
printf("you picked two");
    }

    else if(!(
x==|| x==2))
    {
  
printf("you picked a number other than one or two");
    }

    return 
0;

The only change in this program was that an else was added in front of the second and third if statements. This subtle change in code with give the program the same output in a slightly more efficient manner. I reiterate the fact, as a programmer, you want your code to be efficient.

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:
if(condition 1)
{
    
statement 1;
    
statement 2;
}

else if(
condition 2)
{
    
statement 1;
    
statement 2;
}
    
else if(
condition 3)
{
    
statement 1;
    
statement 2;
}
  
else
{
    
statement 1;
    
statement 2;

So, once again, if were rewriting the program in the above example, it would look like this:

PHP Code:
#include <stdio.h>
  
int main(void)
{
    
int x;
    
    
printf("please enter a number");
    
scanf("%d", &x);

    if(
x==1)
    {
  
printf("you picked one");
    }

    else if(
x==2)
    {
  
printf("you picked two");
    }

    else
    {
  
printf("you picked a number other than one or two");
    }

    return 
0;

In this program, the final else-if statement was replaced with an else statement. Remember the way we had set up the last else-if statement? We had set it up so that if none of the other conditions were true, then the final else-if statement would be, and it would execute. Substituting that with the else statement does the exact same thing.

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:
switch(variable-to-be-tested)
{
    case 
value1:
  
statement 1;
  
statement 2;
  break;
    case 
value2:
  
statement 1;
  
statement 2;
  break;
    case 
value3:
  
statement 1;
  
statement 2;
  break;
    default:
  
statement 1;
  
statement 2;
  

ou start out with the switch keyword, and put the variable you want tested in parenthesis. That's it. You don't put a condition in the parenthesis, only a variable, which is slightly different than what we've been doing so far.

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:
#include <stdio.h>
    
int main(void)
{
    
int x;
  
    
printf("please enter a numbe");
    
scanf("%d", &x);

    switch(
x)
    
  case 
1:
      
printf("you picked one");
      break;
  case 
2:
      
printf("you picked two");
      break;
  default:
      
printf("you picked a number other than one or two.");
    }

    return 
0;

After asking you for a number, this program uses the switch statement. Since the variable we are testing is x, that goes inside the parenthesis. First we test if x is equal to one, so the number one is placed next to the case. If that is true, then the statements inside the first case are executed, and the break signals to exit the switch statement. If not, then you test against the second case. If that is true, then all the statements associated with the second case are executed, and then the break signals to exit the switch statement. If neither of those conditions match the value in x, then the statement inside default executes, and the program then continues as it is supposed to.

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:
#include <stdio.h>

int main(void)
{
    
int x;
    
scanf("%d", &x);
    
    if(
x<5// if this condition is met, then the loop will take place
    
{
  
int i;
  for(
i=0;i<10;i++)
  {
      
printf("%d\n"i);
  }
    }

    else
    {
  
printf("you entered a number greater than or equal to five.");
    }

    return 
0;

This is a simple program. It declares the variable, x, and then asks the user to enter a value and assigns it to x. Once this is done, it tests if x is less than five. If it is, then it performs whatever is encased within the curly braces associated with the if statement, which is the loop. If the condition is met, and the loop is executed, then the computer outputs the numbers 0-9 on the screen. If it is not met it simply prints that the user entered a number greater than or equal to five.

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:
if(condition//outer if statement
{
    if(
condition// inner if statement
    
{
  
statement1;
  
statement2;
  ...
    }

Remember, it is required that both conditions in the inner and outer if-statement to be met before the statements in the inner if-statement can execute. Also, if you would like, you can add statements inside the outer if-statement, and outside the inner if-statement, and they would execute, requiring only the first condition to be met.

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:
for(controlVariable;condition;increment//outer loop
{
    for(
controlVariable;condition;increment)
    {
  
statements;
    }

It's as simple as that. I will demonstrate a nested for loop for you by writing a program which prints the multiplication table up to 10.

PHP Code:
#include <stdio.h>

int main(void)
{
    
int i;
    
printf("\n"); //make sure we are not on a line with other text on it
  
    
for(i=1;i<=10;i++) // outer loop
    
{
            
int j;
            for(
j=1;j<=10;j++) // inner loop
            
{
                 
printf("%d\t"i*j// the operation i*j is performed in printf() before output
            
}
      
           
printf("\n"); //print new line every time the inner loop is complete    
       
}  
      return 
0;

The program declares i, the control variable for the outer loop. It then uses a printf() function to print a new line. This is to make sure that no other text is on the same line as the first row of your table. This is just to add a little elegance to the program, and is inessential for making the actual program run. After that, the outer loop is initiated. The first thing that is within the outer loop is the declaration for j, the control variable for the inner loop. After that, the program goes into the inner loop. It executes the printf() function. The format specifier sees the second argument is i*j. It runs that simple calculation first, and then outputs the answer along with a tab. It then increments the inner loop. Once the control variable for the inner loop, j, is 10, and the final cycle for the inner loop is complete, the program exits the inner loop, and goes back to the outer loop. It sees a statement that prints a new line so that your next row can be started. After the last statement in the outer loop is executed, it increments i, the outer loop's control variable. It redeclares j, and reassigns it the value of 1, ergo repeating to the whole process repeating itself over. After the outer loop's last cycle, it exits the loop, which in this case proceeds to exiting the program.

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:
#include <stdio.h>      
    
int main(void)
{
    for(;;)  
// an infinite loop (outer loop)
    
{
  
printf("\nPlease enter an integer");
  
int x;
  
int y;
  
scanf("%d", &x);
  
printf("\nPlease enter another integer");
  
scanf("%d", &y);
  
printf("\nthe sum of the integers is: %d"x+y);
  
int test;
  for(;;) 
//(inner loop)
  
{
      
printf("\nEnter \"1\" if you want to perform another operation");
      
printf("\nEnter \"2\" if you want to exit");
      
scanf("%d", &test);
      if(
test == 1)
      {
    break; 
// break from the inner loop
      
}

      else if(
test == 2)
      {
    break; 
//break from inner loop
      
}

      else
      {
    continue; 
              
/* continue in inner loop
                                this continue only takes place if the user didn't enter "1" or "2"
    it asks the user again what they want to do*/
      
}
  }

  if(
test == 1)
  {
      continue; 
//continue outer loop performing this whole process again
  
}

  else
  {
      break; 
// break from outer loop
  
}
    }

    return 
0;

This program is an excellent example, because it uses many of the concepts of C that we have already learned.

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:
for(;;) //arbitrary outer loop
// start of block 1
    
int i;
    if(
someCondition)
    {  
// start of block 2
  
int j;
  for(;;) 
//arbitrary inner loop
  
// start of block 3
          
int k;
      
statements;
  } 
// end of block 3
    
// end of block 2
// end of block 1 
Here, the variable i will be accessible throughout this segment of code, since everything is under its block, which is block 1. The variable j will not be accessible outside of block 2, but the inner loop could use it, since it is under block 2. The variable k will only be accessible by the inner loop.

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.
Old
Profile PM WWW Search
Demosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to be
 
Demosthenes
 



 
 
Posted 2004-12-24, 06:46 PM in reply to Demosthenes's post starting "Chapter 3: Loops and Conditionals ..."
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:
type array-name[size]; 
And an example of an actual declaration:

PHP Code:
int grades[20]; 
All that does so far is reserve some memory for us that we can address using the handle "grades".

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:
grades[1] = 6
That will assign grades[1] the value of 6. The 1 inside the brackets is known as the index number, because it is indexing the element known as grades[1]. Now, a little thing you must know about arrays in C is that the index number begins with 0. That means when you use grades[1] you are actually indexing the second element in the array. To index the first element you would use grades[0]. Also, keep in mind, since indexing begins with 0, the greatest index number you could use in this instance is 19, because we've only set aside 20 elements.

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:
int grades[5] = {961007590100}; 
The syntax is simple. It's just like you're declaring an array, except instead of an immediate semicolon, you use an equal sign, followed by a curly-brace, and then the values for each individual element separated by commas, followed by another curly brace and then a semicolon. In the example above, grades[0] would be 96, grades[1] would be 100, grades[2] would be 75, grades[3] would be 90, and grades[4] would be 100. Remember, it can only index up to 4. Initializing char variables is slightly different. I'll cover that in the next section.

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:
#include <stdio.h>

int main(void)
{
  
int grades[10];
  
int i;
  for(
i=0i<10i++)
  {
      
printf("Please input grade for assignment # %d\n"i+1); 
      
scanf("%d", &grades[i]);
  }

  
printf("Please eneter the assignment number you'd like to look up\n");
  
int assignmentNumber;
  
scanf("%d", &assignmentNumber);
  
printf("The grade you made on assignment number %d was %d\n"assignmentNumbergrades[assignmentNumber-1]);
  
  return 
0;
    } 
The first thing this simple program does is declare an array of integers with the handle grade, and gives it a size of 10. Then it declares another integer, i, which is used as our loop control variable. It then goes into a loop, which loops ten times. Inside the loop, it prompt the user to input a certain assignment. The reason we use i+1 in the printf() is because the index starts at 0, and usually people start counting from 1. Then it has a scanf() statement which inputs a number and stores it at location grades[i] (it uses the loop control variable to store a variable at the element's location). Once it's out of the loop it prompts the user to enter the number of the assignment that they'd like to look up. It declares another integer variable, called assignmentNumber which stores the number that the user enters. It then prints that number. The reason we use [assignmentNumber-1], again, is because the user will enter starting from #1, while the computer starts from 0.

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.

Let’s 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. Here’s 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 that’s 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:
char c[5] = {‘t’‘h’‘a’‘t’‘\}; 
Take note that when you are initializing an array of chars then you must use the single-quotes as I have done above.

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 don’t need to separate every value by a comma, and you don’t need to add the null character at the end of the string. C takes care of that for you. Here’s an example:

PHP Code:
char c[5] = “that”
String Functions Section 4.3.3

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 we’ll continue to use printf(). I will show you other functions for outputting a string later. printf() works just as we’ve 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.

Here’s 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:
#include <stdio.h>

int main(void)
{
    
printf(“Please enter a string up to 20 characters.\);
    
char str[21]; // one extra for null-terminator
    
gets(str);
    
printf(“You inputed %str);
    return 
0;

As you can see, using either of the two functions that I’ve covered above is quite easy.

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. Here’s the general format:

PHP Code:
strcmp(str1str2); 
And a simple program that asks you to enter the word “hello.”

PHP Code:
#include <stdio.h>
#include <string.h>

int main(void)
{
    
char str[10]; 
    while(
strcmp(str“hello”) != 0)
    {
  
printf(“please input the word \”hello\”\);
  
gets(str);
    }
    
    return 
0;

strlen() takes one string argument, and returns its length. It doesn’t count the null-terminator, so if you had a string that held the word “that”, strlen() would return 4. Here’s strlen()’s general format:

PHP Code:
strlen(str); 
And as always, a simple program to demonstrate its usage.

PHP Code:
#include <stdio.h>
#include <string.h>

int main(void)
{
    
char str[80];
    
printf(“Please enter a string“);
    
gets(str);
    
printf(“\n%s contains %d characters”strstrlen(str));

    return 
0;

strcpy() takes this general format:

PHP Code:
strcpy(str1str2); 
strcpy() copies the string in str2 to str1. It performs absolutely no size-checks, so you, the programmer must make sure that str1 is big enough to hold
str2.

Here’s a simple program to demonstrate its usage:

PHP Code:
#include <stdio.h>
#include <string.h>

int main(void)
{
    
char str[80];
    
strcpy(str“hello”);
    
printf(“%str);

    return 
0;

This program should print “hello”.

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:
#include <stdio.h>
#include <string.h>

int main(void)
{
    
char str[20] = “hello “;
    
strcat(str“there”);
    
printf(“%str);
    return 
0;

That program should output the phrase “hello there”.

Multi-dimensional arrays Section 4.4

A two-dimensional array is basically just an array of arrays. That probably sounds pretty confusing, but don’t worry; you’ll 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. Here’s a two-dimensional int array:

PHP Code:
int x[3][3]; 
That declares a two-dimensional integer array which is capable of holding nine different values. If a single-dimensional int array with the size of three is a list of three numbers, you can think of the example above as three separate lists, each capable of holding three numbers.

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. Here’s 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. Here’s an example of an array of strings:

PHP Code:
char c[5][20]; 
You can think about that as five different words, each capable of holding 20 different characters. Using two-dimensional arrays with string functions are just as easy. You specify which string you want to operate on by using the name of the array, followed by a single set of brackets with the number of the word you want to work on inside the brackets. Here’s a couple of examples:

PHP Code:
gets(c[2]); 
And another:

PHP Code:
printf(“%c[2]); 
Those two examples should be pretty self-explanatory. The first one gets input from the keyboard, and proceeds to take that input and put it as the third word. The second one simply prints the third word to the screen.

To demonstrate this in a real life example, I’ve made a program that asks for five words as input, sorts them alphabetically, and prints them back out for the user.

PHP Code:
#include <stdio.h>
#include <string.h>

int main(void)
{
    
char words[5][20];
    
    
printf("Please enter five words less than 20 characters long:\n");
    
    
int i;
    for(
i=0i<5i++)
    {
          
gets(words[i]);
    }

    
int j;
    for(
0i<4i++)
    {
  for(
j=0;j<4;j++)
  {
      if(
strcmp(words[j], words[j+1])>0)
      {
    
char temp[20];
    
strcpy(tempwords[j+1]);
    
strcpy(words[j+1], words[j]);
    
strcpy(words[j], temp);
      }
  }
    }
    
    
printf("\nAnd here are the words sorted:\n");
    for(
i=0i<5i++)
    {
  
printf("%s\n"words[i]);
    }

    return 
0;

This code is a little tough to understand. If you don’t understand how this works, don’t worry. The biggest thing you need to get out of reading this code is to understand how multidimensional arrays work, and how to invoke string functions while using multidimensional arrays. That said, I’ll still walk you through this 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 it’s 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 I’ve 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 that’s left from there is copying temp into words[j] and the swap is done.

If you don’t quite understand how the bubble sort works right now, don’t fret. I hadn’t 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 programmer’s 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. I’d like to hear what you think.
Old
Profile PM WWW Search
Demosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to be
 
Demosthenes
 
 

Bookmarks

« Previous Thread | Next Thread »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules [Forum Rules]
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump


All times are GMT -6. The time now is 07:13 AM.
'Synthesis 2' vBulletin 3.x styles and 'x79' derivative
by WetWired the Unbound and Chruser
Copyright ©2002-2008 zelaron.com
Powered by vBulletin® Version 3.8.2
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
This site is best seen with your eyes open.