C Programming For Beginners
C Programming For Beginners
void main()
{
printf("\nHello World\n"); // print to
screen
}
Save this code into a file, and call the file hello.c, then compile it
by typing at a command prompt:
gcc hello.c
If you are using *Nix you should have an a.out file now, but if you
are using Windows you might be wondering what is gcc, and
where do I type the above line into. On Windows getting up and
started with C is little bit more difficult than with a *Nix variant.
You can get a variation of gcc to output Windows code called
DJGPP at www.delorie.com/djgpp/ Setting up the compiler is
probably the hardest part to getting started programming, and
unfortunately this site doesn't cover setting up DJGPP. Another
compiler option is to get Microsoft Visual C++, an excellent editor,
with lots of nice features. The draw back is that the standard
edition costs around $100. But if you can afford a copy, get it. If
you have Visual C++ and it is already installed then load it, click
File, then New, then select Win32 Console application from the
project list. Type in a project name, and then press ok. Next it will
ask you what it should automatically create. Select the hello
world application, and then you should get a program very
similar to the one above. F7 compiles, and Ctrl-F5 will run it.
From now on the tutorial will refer to the *Nix method and output
files. If you compiled the program in Windows instead of *Nix you
would have a hello.exe instead of a a.out
Note:If you are coming from the gameboy advance tutorial , please
note you will need a separate compiler for this tutorial. The
reason is the gcc with the devkit advance is for the gameboy, so
the code it generates will not run on a PC, also becuase the
gameboy has no standard font built in, you will not be able to see
the output of the printf statement, basically the above program
will do nothing.
This creates an executable file a.out, which is then executed
simply by typing its name. The result is that the characters Hello
World are printed out, preceded by an empty line.
A C Program contains functions and variables. The functions
specify the tasks to be performed by the program. The above
program has one function called main. This function tells your
program where to start running. main functions are normally
kept short and calls different functions to perform the necessary
sub-tasks. All C codes must have a main function.
Also notice that C is case-sensitive . The commands have to be
written like they are above. C also denotes the end of statement
with a semi-colon like Java & Pascal. Brackets signify either to "{"
begin a group of statements, or "}" end a group of statements. The
// or /* comment */ designates a comment. Anything after two
slashes the compiler ignores. The last part of the program you
should notice is the #include. This simply includes a group of
functions from the filename specified between then less than and
greater than signs (<...>). The file above stdio.h contains a list of
standard functions for C to use, the function the our above
program uses is printf. Printf takes a string of characters between
quotation marks, and outputs them to the screen.
Now that you understand the hello world program it's time to
learn more about data types, and the printf statement.
2. Data Types and Printf
Here is our next program to discuss. It declares several variables,
performs some computations, and then outputs the results of
those computations to the screen.
#include <stdio.h>
void main()
{
int numcandy; // declare a number variable
double cost; // declare a variable that
can store decimals
while (expression_2)
{
...block of statements...
expression_3;
}
For instance, the following structure is often encountered:
i = initial_i;
for ( ; ; )
{
...block of statements...
void main()
{
int numcandy;
double cost;
int numberlollipopps;
double totalcost;
numberlollipopps =
START_NUMBERLOLLIPOPS; // set start value to
our constant
totalcost = 0;
void main()
{
char Str[STR_LENGTH];
char* pStr;
int i;
Str[0] = 'H';
Str[1] = 'i';
Str[2] = '!';
Str[3] = '\0'; // special end string
character
printf("The string in Str is : %s\n",
Str);
pStr = &Str[0];
for (i = 0; i < STR_LENGTH; i++)
{
*pStr = '0'+i;
pStr++;
}
Str[STR_LENGTH-1] = '\0';
printf("The string in Str is : %s\n",
Str);
}
First off, let's talk about the array notation to declare an array in
C, you use [] square braces. The line of the program char
Str[STR_LENGTH]; declares an array of ten characters. Basically
this is just ten individual char s which are all put together in
memory into the same place. An apartment complex in memory to
use our pointer metaphor. They can all be access through our
variable name Str along with a [n] where n is the element number
(apartment number at same address). Also notice that when C
declares an array of ten. The elements you can access are
numbered 0 to 9. Accessing the first apartment corresponds to
accessing the zeroeth element in C. Arrays are always like this, so
learn to deal with it. Always count from 0 to size of array - 1.
Next notice that we put the letters "Hi!" into the array, but then
we put in a '\0' You are probably wondering what this is. If you
recall in lesson two on printf, there are special charcter
sequences that do special things like "\n" stands for new line.
Well time to learn a new one. "\0" stands for end string. All
character strings need to end with this special character '\0'. If
they do not, and then someone calls printf on the string. Then
printf would start at the memory location of your string, and
continue printing tell it encounters '\0' So you will end up with a
bunch of garbage at the end of your string. So make sure to
terminate your strings properly.
The next part of the code to discuss is our pointer access to the
string. Just like we learned, I declared a character pointer with an
asterick and gave it the name pStr. I then pointed pStr to the
starting address of our character string using the line pStr =
&Str[0]; . Now pStr points to the start of our char array Str. Then I
used a for loop, and started at 0, went through 10 elements of the
array (STR_LENGTH) and assigned the corresponding value of i.
The line pStr++; may seem a bit confusing. C has a bunch of short
cuts to manipulate variables the ++ just means add one to the
variable (in this case it moves the pointer to the next element in
the array). The ++ syntax here is equivalent to pStr = pStr + 1;.
After manipulating the string, I terminated it with '\0' and
printed it out. That about does it for pointers and arrays, here are
a few quick notes. You should note that you will see other
shortcuts in C like -- (subtracts one) or +=3; (adds three). I won't
bother covering them, since you should be able to figure them out
just by looking at them. Another note is that you can make arrays
of any of C's types, I just used char arrays since they seem to be
the most common. Here is a sample line to make an array of five
integers: int arrayofint[5]; .
5. Functions
This part should be quite simple compared to the last part.
Functions are easy to use; they allow complicated programs to be
parcelled up into small blocks, each of which is easier to write,
read, and maintain. We have already encountered the function
main and made use of printf from the standard library. Now
let's look at writing and using our own functions.
Calling a Function
The call to a function in C simply entails referencing its name
with the appropriate arguments. The C compiler checks for
compatibility between the arguments in the calling sequence and
the definition of the function. When someone writes a function
for someone to use that funciton will often be contained in a
different C source file. Sometimes, however we may not have
access to all the source code for all the functions. This is the case
for most standard library functions like printf. However, we still
know how to use printf, and the arguments it requires because
those arguments are listed in the header file called stdio.h, which
we have been including in our programs.
Library functions are generally not available to us in source form.
Argument type checking is accomplished through the use of
header files (like stdio.h) which contain all the necessary
information. The most commonly used header files are
<stdio.h> -> defining I/O routines
<string.h> -> defining string manipulation
routines
<math.h> -> defining mathematical routines
<stdlib.h> -> defining number conversion,
storage allocation
and similar tasks
<stdarg.h> -> defining libraries to handle
routines with variable
numbers of arguments
<time.h> -> defining time-manipulation
routines
To find out more about there header files and the functions they
contain you can either by a book about C or visit our Other
Resources . In addtion to those header files, we can of course
make our own functions and header files. A function has the
following layout:
return-type function-name ( argument-list-if-
necessary )
{
...local-declarations...
...statements...
return return-value;
}
If return-type is omitted, C defaults to int. The return-
value must be of the declared type.
A function may simply perform a task without returning any
value, in which case it has the following layout:
void function-name ( argument-list-if-necessary
)
{
...local-declarations...
...statements...
}
Arguments are always passed by value in C function calls. This
means that local ``copies'' of the values of the arguments are
passed to the routines. Any change made to the arguments
internally in the function are made only to the local copies of the
arguments. In order to change (or define) an argument in the
argument list, this argument must be passed as an address,
thereby forcing C to change the ``real'' argument in the calling
routine.
As an example, consider exchanging two numbers between
variables. First let's illustrate what happen if the variables are
passed by value:
#include <stdio.h>
void main()
{ /* WRONG CODE */
int a, b;
a = 5;
b = 7;
printf("From main: a = %d, b = %d\n", a,
b);
exchange(a, b);
printf("Back in main: ");
printf("a = %d, b = %d\n", a, b);
}
temp = a;
a = b;
b = temp;
printf(" From function exchange: ");
printf("a = %d, b = %d\n", a, b);
}
Run this code and observe that a and b are NOT exchanged! Only
the copies of the arguments are exchanged. The RIGHT way to do
this is of course to use pointers. Also note that in the above code
how the function exchange was prototyped. It was declared with a
semicolon, and ZERO statements before the main function. This is
called forward declaration. This allows the C Compiler to compile
main, without not yet knowing the code for exchange. All it needs
to know is what exchange arguments look like. This way we can
put the exchange function after our main function. We could have
easily put exchange before main and gotten rid of the declaration.
The next code segment will fix exchange to use pointers, and
move exchange above main to eliminate the need for the forward
declaration.
#include <stdio.h>
temp = *a;
*a = *b;
*b = temp;
printf(" From function exchange: ");
printf("a = %d, b = %d\n", *a, *b);
}
void main()
{ /* RIGHT CODE */
int a, b;
a = 5;
b = 7;
printf("From main: a = %d, b = %d\n", a,
b);
exchange(&a, &b);
printf("Back in main: ");
printf("a = %d, b = %d\n", a, b);
}
The rule of thumb here is that
You use regular variables if the function does not change the
values of those arguments
You MUST use pointers if the function changes the values of those
arguments
Lastly, I noticed that none of the examples with functions have
returned values. So this quick example will illustrate returning
values with functions. Functions may not seem that useful yet, but
as your program grows you will no longer want to have all your
code in main. So you will want to split it up into functions. Below
we have a function that adds the two arguments it receives and
returns their value. Not to complex, but does its job well. Take a
look:
#include <stdio.h>
void main()
{
int a;
int b;
int sum;
a = 6;
b = 7;
sum = addints(a, b);
printf("The sum of a and b is : %d\n",
sum);
}
6. Other Resources
That concludes our tutorial on C, you should have a fairly good
handle on all the basics of the C langauge now. There are still
quite a few things that such a short tutorial could not cover like
structs, file I/O, typedefs, c standard library functions, and more.
But we have gathered a few links to some further resources here.
Where you can learn more about. We also have two books listed
that come highly recommended. Good luck with you adventures
as a hero.... I mean programmer. If you have any comments or
questions feel free to contact us.
CProgramming.Com this is the resource for C programmers. It is
the source for tons of information. It has good tutorials, which are
easy to understand and message boards so you can get help for
any problems you may encounter. This is the place for C!
DJGPP Want a great *free* C++ compiler this is it. Easy to setup,
and with Allegro you'll be making games in no time!
DEV C++ another free compiler for C/C++
Dr. Dobb's Journal software tools for the professional
programmer. We used to link to the Programmer's Vault, but as
this has been integrated into Dr. Dobb's we will link there instead.
C Tutorial at Drexel.edu - contains a little bit more information
about file i/o and command line arguments. Parts of the above
tutorial were based on this one here.
BOOK : C Programming Language (2nd Edition) by Brian W.
Kernighan, Dennis M. Ritchie. This is slightly more complex than a
tutorial or a book to learn C. It is more of a reference. But is was
written by the guys who invented C, so what can I say. It is the
definite source for accurate information on the C language.
BOOK : C For Dummies®, Volume One & Two Bundle by Dan
Gookin. This is an excellent book to start learning C from. It's
simple, and takes you step by step through the world of making
programs, and becoming a programmer.