This is originally from my site: http://www.cprogrammingdock.serverspeople.net/
which i wrote few months ago..^^
and thought this maybe useful to those who haven't yet visited the site..
So here we are :D
+++++++++++++++++++++++++++++++++
C Programming
+++++++++++++++++++++++++++++++++
What is C programming? The C Programming Language is a structured, modular, compiled, general purpose language Traditionally used for system programming. It is portable, so you can easily transfer application programs written in C from one system from one another. You can use C for almost any programming task, anywhere.
C allows the most precise control of input and output. This can result in short efficient programs, where the programmer has made wise use of C's range of powerful operators. It also allows the programmer to produce programs which are impossible to understand.
Learning in C can result for better understanding of other languages such as C++, which is the superset of C, and many others, they almost share the same format. If you were familiar with C, you can have knowledge support to learn other Programming Languages.
++++++++++++++++++++++++++++++++++++
Your First Program in C
++++++++++++++++++++++++++++++++++++
This section of this tutorial will teach you how to write a program in C.
Here is the most popular program, "Hello World!"
Hello World!
Write this on your editor,
CODE :
#include <stdio.h>
main()
{
printf("Hello world!\n");
}
Save this as Hello.c, .c extension means that the file is a C source code. Now, compile this code using your compiler, then execute/run the code. If you are using Turbo C, you saw the screen flash, and nothing happened, press alt + f5 to view your work.
Lets talk about our program, in our program, we output the string "Hello World!", for we to do that , we made use of a function, the function printf, we will talk more of this later.
We started typing "#include", this is a preprocessor, along that we typed <stdio.h> this means that we included the header file stdio.h, this file contains the functions that we will use, one of the function we used is printf.
Next, we typed main(), this is the main part or the body of our program, under main are statements enclosed with brackets ( "{ }"). In our main program we typed,
CODE :
printf("Hello World!\n");
And we used printf. printf outputs data into the screen, as we have done, we made printf output Hello World! on the screen. In the code, Hello World! is followed by "n", this is an escape sequence, this tells the compiler to move the cursor to the next line.
There are many kinds of escape sequences, here are the mostly used:
\n - newline
\t - tab
\b - backspace
\xhhh - insert the character represented by ASCII code hhh, where hhh is equal to 1 to 3 hexadecimal digits
You may have noticed, the statement ends in semicolon ";", this tells the compiler that it is the end of a sentence. If you forgot to put a semicolon after each statements, you will receive an error that tell that a semicolon is missing in the particular statement.
+++++++++++++++++++++++++++++++
Math in C
+++++++++++++++++++++++++++++++
Now that we know how to output. We can now go on and lets talk about Math in C and Inputs.
Modify Hello.c, edit it like this.
CODE :
#include <stdio.h>
main()
{
int a,b,sum;
printf("Enter two numbers: ");
scanf("%d %d", &a,&b);
sum = a + b;
printf("\nThe sum is %d", sum);
}
Save this as sum.c
Let us now analyze. Under the main program, there are several changes,
CODE :
int a,b,sum;
The statement above means that we declared 3 variables under 1 data type "int", the variables were, a, b and sum.
Data Types
There are many data types in C, here are the four basic types:
Integers - numbers you learned to count.
Floating Point Numbers - have fractional portions and exponents, also known as real numbers.
Text - made up of single characters and strings.
Pointers - holds the address of variables. Does not hold data.
Format Specifications
Another statements that are new are,
CODE :
scanf("%d %d", &a,&b);
sum = a + b;
printf("nThe sum is %d", sum);
Now we used the scanf function. scanf lets the user to input data during runtime. We made use of "%d".%d is one kind of format command called a format specification. scanf says that we must input 2 integers seperated by a space. All format specifications starts with a percent sign "%" and usually followed by a single letter, indicating the data type to be inserted. %d is the format specification which means integer. So, you can only input numbers from -32768 to 32767.
Here are other examples of format specifications and the data type they specifies,
%u - unsigned integer - 0 to 65535
%ld - long integer - - 2147483648 to 2147483647
%p - pointer value
%f - floating point - 3.4-38 to 3.4+38
%e - float in exponential form
%c - character
%s - string
%x - integer in hexadecimal format
In our program, after the format specification, we typrd &a,&b, this means that when the user inputs the first integer, it will be addressed to a, "&"is an address operator.Same as the second integer, when the user inputs the second integer, it will be addressed to b.
The next statement is more like the operation of our program, it says that add a and b together and assign the answer to sum. "=" is an assignment operation, the operations usually take process on the rvalue(right value), and to be addressed to the lvalue(left value) by =.
in the last statement, we used printf again, and we again used format specification. When we are using format specifications in output, we are referring to a variable which holds value and to be printed on the screen, for that, we must call the name of the variable after the string, like our example,
CODE :
printf("nThe sum is %d", sum);
This outputs the value of the variable sum. sum has a value of a + b.
Now you know how are these statements connected, pretty cool ha?!
Arithmetic Operators
Here are the commonly used operations in C,
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus(Remainder)
++ Increment
-- Decrement
You might be confused, in a++ and ++a, this is mostly confusing in operations.
Suppose there are two expressions,
CODE :
sum = a + b++;
sum = a + ++b ;
The first expression says, "Add a and b together, assign the result to sum, and increment b by one. The second says "Increment b by one, a and b together, and assign the result to sum.Get it?
There are two other types of operations that we haven't discussed yet, these are logical and relational operators.
Relational Operations
Relational operations allow you to compare two values, yielding the result based on whether the comparison is true or false. If the comparison is false then the resulting value is 0,if true, the value is 1.
Here are the relational operations in C,
> greater than
>= greater than or equal to
< less that
<= less than or equal to
== equal to
!= not equal to
Now, the question is, how to use these in C.
If and Else
Modify sum.c,edit as follows,
CODE :
#include <stdio.h>
main()
{
float a,b,ratio;
printf("Enter two numbers: ");
scanf("%d %d", &a,&b);
ratio = a / b;
if (b == 0)
printf("nInvalid Inputs!");
else
printf("nThe ratio is %d", ratio);
}
Save this as ratio.c
We all know that in division, we cannot divide a number by 0, so in our program, we made use of conditional statements to avoid this mistake.
CODE :
if (b == 0)
printf("nInvalid Inputs!");
else
printf("nThe ratio is %d", ratio);
This is a conditional statement. It says that if b (which is the divisor) is equal to 0, then the statement/s under these will be executed, in the other hand, if it is false, the statement/s under else will be executed.
NOTE: In conditional statements, else can be optional.
So, if the user entered 0 as a divisor(b), an error message will be displayed.
The conditional statement's syntax is,
CODE :
if(expression)
sets of statements;
else
sets of statements;
If the statements under each condition are more than 1, brackets should be placed.
NOTE: If and else doesnt need to have semicolons.
Logical Operators
There are also three logical operators,
&& AND
|| OR
! NOT
These operators allows you to combine relational expresiions.
AND
true && true = true
true && false = false
false && true = false
false && false = false
OR
true && true = true
true && false = true
false && true = true
false && false = false
NOT
!true = false
!false = true
The examples above should be up to you to understand because its logical..=)
We had tackled about programs that executes conditionally (conditional statements), but now, how would you like to know programs that executes repeatedly. These are Loops.
There are three basic kinds of loops.
while loop,
for loop,
do..while loop
While Loop
Lets talk about the while loop. The while loop is the most general loop, and it can be used to replace the other two, in other words, the other two are only for special cases, but this loop can do the functions of the other two.
Here is an example,
CODE :
#include <stdio.h>
main()
{
int length;
length = 0;
puts("Enter a string and press ENTER :");
while (getchar() != 'n')
length++;
printf("nYour Sentence was %d characters long" length);
}
This program lets you type a string and counts how many characters does your string have until you press ENTER. pretty great huh..
Just like conditional statements, loops also consider expressions, when the expression is false, it escapes the loop, and until the expression is true, it will repeatedly execute the statements under the loop.
For Loop
Lets move on to the for loop. Consider this example.
CODE :
#include <stdio.h>
main()
{
int length;
puts("Enter a string and press ENTER :");
for(length = 0;getchar() != 'n';length++)
{
}
printf("nYour Sentence was %d characters long", length);
}
This example functions the same as the previous program, but here, we used for loop instead of while loop. As you can see, for loop merges 3 statements into one parenthesis. The for loop uses these statements as a condition to control the loop in the inner statements. At our example, we don't need statements so we've just inserted the brackets.
NOTE: For that, if you will not put brackets, the compiler will consider the next statement as a statement of the for loop.
The question, Why use for loop instead of just while loop? As i have said earlier, the two other loops are used in special cases, some uses of for loop are multidimensional arrays(advanced topic :: you will learn this soon).
Do..While Loop
Now, what if you want to have a special function to halt your program?. Use the do while loop..
Here is an example,
CODE :
#include <stdio.h>
main()
{
int a;
do
{
a = 1;
printf("%dn", a);
printf("nPress 'x' to quit, any other key to continue");
}
while (getch() != 'x');
}
If you will run this program, it will output 1 and ask you to press a key, if you choose 'x', the program will halt, on the other hand, if you press keys other than 'x', the code between do and while will repeat.
NOTE: the while in the do while loop, requires a semicolon.
In some reasons, you may have been tired and lazy in typing operations over and over again. For that you can use functions.
Functions are like shortcuts, whenever you will use an operation, you will just have to call it, by its function name.
Here is an example,
CODE :
#include <stdio.h>
void math_all(int a, int b);
main()
{
int c,d;
printf("Enter two numbers: ");
scanf("%d %d", &c,&d);
math_all(c,d);
}
void math_all(int a,int b)
{
int sum,dif,pro,quo;
sum = a + b;
dif = a - b;
pro = a * b;
quo = a / b;
printf("nThe Sum is %d",sum);
printf("nThe Difference is %d",dif);
printf("nThe Product is %d",pro);
printf("nThe Quotient is %d",quo);
}
Here, in our program, we made use of functions to call on different basic operations such as addition, subtraction, multiplication and division. As i mentioned earlier, functions are like shortcuts, analyze the code and see what i mean.
First, we declare the function, functions are declared globally, it means that it can be used in different parts of the program in and out the main().You may notice that we put the word "void" before the name,void means, it doesn't return any values at all. If the function returns a value, then we should put "int" before the name instead of void. After we have declared it, we can use it in main.
In main, we made use of scanf to get the value of the two numbers (c and d), then we passed the value to a and b, which are variables of the function math_all().
Next, we defined the function, its more like telling the compiler what does the function do. It usually composed of Operations and different library functions.
TIP: You can declare and define a function anywhere in the
program.
So far, we have discussed about variables that holds data, well, in this chapter, we will discuss variables that holds address of data,Pointers.
Before we define pointers, lets have a quick glance about the memory.
Memory Lookup
Computers hold programs and data in its memory, also called RAM - Random Access Memory. The computers memory, at its lowest level, are composed of bits,microscopic electronic circuits, bits are from Binary digITs.
Bits can remeber one of two values (1 and 0), you may have seen numbers written horizontally of vertically composed of 1's and 0's. Example,
11011010
These are bits, and every 8 bits of them are called bytes, if you want to know more of this, do search for binary numbers and find tutorials. Each byte in a computer's memory has a unique address -- Usually Hexadecimal Format, hexadecimal characters like 166EE can be converted to bits and vice versa. You can have a binary conversion table in the net, if you want, go search for it.
Define Pointers
A pointer is a variable that holds the address of some data, rather than the data itself. But you would ask yourself, Why is it important and how to use it?
You can use pointer to point to different data and different data structures. By changing the address the pointer contains, you can manipulate information in various locations.
Lets see an example of pointers,
CODE :
#include <stdio.h>
main()
{
int a, *pa;
a = 9;
pa = &a;
printf("%p", pa);
}
In this example, we had an output of a memory address, address of 9. Since we have to output an address, we have to use the format specification %p for pointers. When we declare pointers, we should put an asterisk * before it.
TIP: In declaring pointers, practice using names starting with p, example, *pa.
If you want to output the data of the address held by the pointer you should write,
CODE :
printf("%d", &*pa);
Since you will output a data which is an integer, you should use %d specification.
When you assign a varaiable to a pointer, make sure you have this format,
pointer = address of variable(&)
or
Value of pointer(*) = variable
Statements above represents this,
CODE :
pa = &a;
or
CODE :
*pa = a;
Get it?
After you have finished this tutorials, i recommend to read more advanced tutorials on pointers(since this tutorial is for beginners - basic - only).
An array is an example of a homogeneous random access data structure. An array is merely a collection of similar data elements such as integers, floats, characters, etc. which is stored together with a common name, and addressed by means of index that tells the location of the particular data entity in the array.
When we use homogeneous to an array, it means that each cells have the same data type, and the random-access aspect tells that we can access any of the cells of an array directly by just using its indices.
Example,
CODE :
#include <stdio.h>
main()
{
int a[50];
a[0] = 19;
}
Now, what have we done?, well, we assigned a data to an array.
NOTE: an array starts from 0. Example, in array a[50], the first block starts from a[0] and ends in a[49]. Why 49? as we declared a[50], we declared 50 blocks, and in an array, the end must be a NULL character . So, we started from 0 and end in 49 to make 50 a null character.
If you would visualize the arrays as horizontal blocks, and you addressed 19 to it, it would be like this
[0] [1] [2][3] [4] [5] [6] [7] [8]...... -- a[0] is the starting array.
|
19 -- the variable 19.
If it is not yet clear to you, 19 is stored at the block a[0], you can put another integer in any of the blocks, say you will put 54 in block 6, you will write
CODE :
a[6] = 54;
So, if you call a[0], you are referring to the value 19, and if you call a[6], you are referring to the value 54.
In short, you can define arrays as a bundle of blocks with the same data type.
In more advanced topics, you will learn multi-dimensional arrays, in our example, we only used a linear array (one dimensional).
In our last discussion, arrays, we used arrays to build lists of items of the same data type, but in this chapter, we will construct something out of different data types.Structures.
A structure is a conglomerate data structure, a lumping together of different data types. For example, you want to have information about a student.
CODE :
#include <stdio.h>
typedef struct {
char name[64];
int age;
int year;
} student;
Now, lets analyze, just like functions, we can declare and define structures outside main. We started with "typedef struct", this is a common syntax in c that tells the compiler that the following statements will be a part of a structure whose name is outside the statements. Then, we declared name, age, and year with different data types, yes, that's how structures are for. The variables declared inside the structure are called members of the structure. As mentioned, the name of the structure is outside the statements, and the name is "student".
Although, there are many formats of the structure's syntax, its better and I recommend using this format.
Next is the main, in main, we declared the variable you as a type student, which is a struct, with this, we can assign values for each member. To do that, we wrote the variable you followed by a member of the structure seperated by a period.
Then there you go, just treat the member of the structure as a regular variable.
Pointers and Structures
You can declare pointers to structures, just as you can declare pointers to other data types. This ability is essential for creating linked lists and other dynamic structures.
Now, rewrite our example.
CODE :
#include <stdio.h>
typedef struct {
char name[64];
int age;
int year;
} student;
There, now, what have been changed?, the period become an arrow, that syntax symbolizes that we declare the variable you as a pointer. Just like other pointers, a pointer to a member of a structure holds the address of data.
If you are able to analyze clearly the definitions above, you will find it easy to understand structures.
+++++++++++++++++++++++++++++
The C Preprocessor
+++++++++++++++++++++++++++++
We have written many source codes through our discussion. You may have ask, what is #include <stdio.h>??
First, is the #include, It is a C Preprocessor. There are many kinds of C Preprocessors such as,
CODE :
#include
#define
#if .. #else .. # endif
#ifdef .. #else .. #endif
#ifndef .. #else .. #endif
For now, we will discuss about #include, if you want to cover up all of the C Preprocessor, search for more advanced tutorials, but first, you should understand the #include preprocessor.
In our first example, Hello World, (and all the other examples), we have used #include, this is the most commonly used preprocessor.
CODE :
#include <stdio.h>
main()
{
printf("Hello world!n");
}
You may notice, #include is followed by <stdio.h>, stdio.h is a C/C++ header file that contains different functions. We call the or include the header file via #include, the syntax "<>" tells the compiler that the header file is at the C's directory. Header files at the directory are provided by the creator of the compiler. You may encounter a #include preprocessor followed by "file" -- #include "example.h". The quotes tells the compiler that the header file is located on the same folder/directory where the source code is located. These header files are commonly user defined.
You can create or modify a header file, but to do that, you should have sufficient knowledge of header files.
This only means that we use #include if our program needs a function which is at a header file. For example, we want to output hello world, but to do that, we need printf, but where is printf? at the header file stdio.h, how to include stdio.h? we use #include. =)
CODE :
#include <stdio.h>
If you are curious, you may ask, How many header files are there? What are the other header files? What are the functions inside each header file?.
For that, you have to search again for the complete list of the C Library.
Good Luck!
+++++++++++++++++++++++++++++
Next Steps..
+++++++++++++++++++++++++++++
This seems to be the end of this tutorial, but this is not yet the end of your learning. Find more advanced tutorials about C. Master C if you like, it takes time, but its worth it!
Thank you for visiting this site and reading the tutorials! Hope you have understood the basic concepts in C!
Thank You Very Much!
dEmOn
Cast your vote on this article *Note: the order of the votes has been reversed.
Comments: Published: 20 comments.
By: jourdie - 06:50 am Saturday September 08th, 2007
nice article, simple and easy to read. Nice job!
YAY im the 1st poster!
By: Bliepo32 - 01:16 pm Saturday September 08th, 2007
There are some errors in the article. For example, a newline is not "n" nut "\n". For the rest, it is ok. Because of that one error, I'll give you a 7 (would have been an 8).
By: c24lightning - 01:40 pm Saturday September 08th, 2007
pretty good, pretty good. but im still not sure if it's C or C++ cauz it looks like C++ langauge, but youre saying it's C....
By: murderbydeath - 02:37 pm Saturday September 08th, 2007
Well, I do believe the SQL escape stuff probably screwed up his \ns, Bliepo.
But...his code does have a lot of errors. For instance, in his structs example, you can't just declare you.name = "Student S. Surname". You have to use strcpy.
6/10
By: BananaKid - 01:16 pm Sunday September 09th, 2007
nice article 8/10 =]
btw c24lightning wtf are you talking about?? this is pure c.
It was really nice to read it.
but i know the basics and look for somethis more functional .
if(someone == know || know_where_to_look_for)
{
printf("i do %S" ,address);
}
By: deino4eva - 12:43 am Monday September 10th, 2007
Good article. Some sentences are a bit awkward, but its pretty easy to follow otherwise. In the pointer to a structure example you created a pointer that points to nothing. You have to malloc or create an instance of the structure to point to. And as murderbydeath pointed out, you can't assign a string with an equals sign like that. You need to use strcpy(destination, string_value)
By: eljonto - 01:04 am Wednesday September 12th, 2007
great tutorial for beginnners, really show basic oncepts important for later programming, 10/10
By: hackit2hell - 07:37 pm Tuesday September 18th, 2007
I must be slow. What do you do it with because I did it with notepad and it uh... sucks. I know I did it wrong someone please tell me what to use.
By: m0nk3ysh1n3 - 07:44 pm Wednesday September 19th, 2007
Makes me wish I could find a proper C compiler for Linux. This is all very new to me...any tips?
By: dEmOn - 07:47 am Thursday September 20th, 2007
for Linux.. use gcc..
for windows, dev C++
By: vicarious - 12:44 am Sunday September 30th, 2007
That is one intense article, so much work, so well set out, easy 10/10.
You forgot strings! You should add at the arrays section a sentence like there are many types of arrays! and do brief description! Other than that, this is awesome! It is the first C article I see that does not confuse a complete noob! Awesome! GOOD JOB! u get a 10/10
By: Kaito_Kidz - 12:32 am Saturday October 27th, 2007
By: Phyroxis - 11:14 pm Wednesday August 13th, 2008
I sort of feel... like you may not have written this article. Your introduction (before the actual tut) is way poorly written when compared to the rest of the article.. But I won't cry wolf or anything. Good job if this is all yours.
So, uh.... where the hell is the 'return'?
all functions [thats main too] NEED to have a type.
This site is the collective work of the
HackThisSite staff. Please don't reproduce in part or whole without permission.
Page Generated: Wed, 08 Oct 2008 03:58:25 -0500 Exec:
9