HISTORY

        C programming language was created by Dennis Ritchie of Bell Laboratories in 1971-1972 with Ken Thompson as they were developing the UNIX Operating System. Ritchie was head on the System Software Research department of Computing Sciences Research Center of Bell Laboratories. Ken Thompson on the other hand was working on the Multics project. He wrote the B language precursor to Ritchie's C language.


INTRODUCTION

        C programming language is a very powerful language in which most programs are developed. It's nature inspired me to write this page. To start C, you need to get the IDE(Integrated Development Environment) from here. Upon finishing this tutorial, you'll be able to learn:

1. Basics of C

       * data types
       * structure of a C program
       * constants and variables
       * input and output
       * conditionals
       * looping

2. Functions

       * Using function parameters
       * Returning data from a function

3. Arrays

       * Initializing array elements
       * Accessing array by looping
       * Multi-dimensional array

4. Pointers
5. Strings
6. Structures

       * Defining a structure
       * Accessing the members in the structure

7. File I/O and Command line arguments

       * Accessing the members in the structure
       * Accessing the members in the structure

Learn by Example

Note: Some of the lessons are not yet finished, it'll be up soon. So stay toon.. :) Keep posted.


Basics of C

:: Data types

C Datatypes:
    *int
    *float
    *double
    *char
    *void
    *enum

int is used to define integer numbers.

{
   int x;
   x = 5;
}

float is used to define floating point numbers or decimals.

{
   double x;;
   x = 5.121;
}

double is used to define BIG floating point numbers. It reserves twice the storage for the number. On PCs this is likely to be 8 bytes.

{
    int x;
   x = 2500000;
}

char defines characters.

{
    char x;
   x = 'A';
}


@ Modifiers @

    *short
    *long
    *signed
    *unsigned

Modifiers defines the amount of space allocated for a certain variable. There are rules to follow in using modifiers.

Type Bytes Bits Range

short int
unsigned short int
unsigned int
int
long int
signed char
unsigned char
float
double
long double

 

2
2
2
4
4
1
1
4
8
12
16
16
32
32
32
8
8
32
64
96
            -32,768 -> 32,767
                      0 -> 65535
                      0 -> 4294567295
-2,147,483,648 -> 2,147,483,647
-2,147,483,648 -> 2,147,483,647
                 -128 -> 127
                      0 -> 255



:: Structure of a C Program

Preprocessor Directive
Global Declarations

int main(void)
{
local declarations;
statements;
return 0;
}


The C preprocessor is a program that is executed before the source code is compiled.
Global Declarations is where you declare a variable or define a constant that can be used through out your program.


Example:

#include <stdio.h>
#define X 100
int z;

int main(void)
{
int y;
y=1;
z=2;
printf("Hello World");
printf("%d %d %d", X, y, z);
return 0;
}


:: Constants and Variables

Variables are like containers in you memory. You can store, remove, modify values in them. It is a space in the memory set aside for a certain data and is given a name for easy reference. To initialize a variable means that you intend to assign a value in the variable for the first time using arithmetic operators, like this. (x=2).

There are three types of constants. The memory constants, literal constants and the defined constants. It is considered literal constants(an unamed constant. number 20 cannot be change nor can you assign another variable in number 20), defined constants(#define PI 3.1415) while memory constants(const int PI 3.1415).

@Rules in naming constants and variables@

    Should not start with a number
    Should not contain arithmetic symbols
    Should not contain any special characters
    Should not contain space
    Can not contain numeric characters
    Can begin or contain underscores
    Can contain mixed letter cases.
2m
a+bm-c
$%^#$
test character
test7vari9
_test_
TeSt

Declaring Data - give the data a name
Defining Data - data is allocated


@4 Data Types@

There are 4 data types in C(int, char, float, void) and each have different properties. Properties like sizes. Data sizes are the number of container in the memory slots required to store it.

@Defining Constants@

There are 3 ways in define constants, #define, enum and const. But in this section, we'll use const.


For example you are to compute the circumference of a circle, we'll define a variable PI it's value which is 3.1415 because PI is needed in the circumference formula of a circle.


Using const keyword
    const int PI = 3.1415;

Since you declared PI using the const keyword, statements like PI = 23432; will be illegal.

Using define
    #define PI 3.1416

#define must be placed before the main function and the # symbol must the be the first character in the line.


:: Input and Output

Formatted Output
printf(print formatted)

printf("format string", argument list);

Format strings can contain(format specifiers, escape sequences).
Argument lists can contain(constants, variables).

Escape Sequences
\r - carraige return
\n - new line
\t - tab
\a - beep
\b - basckpace
\' - single quote
\'' - double quote
\\ - backslash

ex.

main
{
printf("Hello World");
return 0;
}



Formatted Input

scanf(scan formatted)

scanf("format string", address list);


main()
{
clrscr();
printf("Enter a #:");
scanf("%d", &x);
printf("The number is: %d", x);
getch();
}

Scanf Rules:

1. The conversion operation processes until:
    a.) A max number of characters is read.
    b.) Whitespace character is found after a digit in the numberic specification.
    c.) an error is detected.
2. There must be a field specification for each variable.
3. There must be a variable address of proper type for each field specification.
    a.) It is a fatal error to end the format string with a whitespace character.


:: Conditionals

There are 2 types of conditionals. The (if, if else, else) and the swith().

Using if()

if(statement)
{

}

else if(statment)

{

}

else

{

}


Notice that there are no semicolons used.

Using switch()

switch(expression)
{

         case const_expression 1:      /*this is an expression on equality*/
         {
         block of statements;              /*contains blocks of statements*/
         break;                                    /*with out this, it will continue executing the next conditions even the                                                         condition is statisfied*/
         }

         case const_expression 2:
         {
         block of statements;
         break;
         }

         default::
         {
         block of statements;
         }

}


:: Looping

There are 3 ways to loop. The for(),while(), do()while.

Using for()

for(x=initial; x<x_maximum; x=x+x_increment)
{

         block of statements;

}

Using while()

x = 0;

while(x<x_maximum)
{

         block of statements;
         x = x + x_increment;

}

Using do()while

x = 0;

do
{

         block of statements;
         x = x+ x_increment;

} while(x<x_maximum);


Functions

2 ways to pass data
- pass by reference
- pass by value

main()
{
Display(); /*trying to call the function Display().
*/
}

Display() /*A function*/
{
printf(“Hello World”); /*Displays “Hello World”*/
}

Functions are used to make your codes manageable, understandable, clear and simple. This process is called segmentation or modularization. Dividing your program into smaller pieces.



:: Using function parameters

main()
{
int x;
x = 5;
Display(x); /*Calling Display function with
parameter x.*/
}

Display(int x)
{
printf(“The value of x is: %d”, x);
}

Display(int x)
You can use parameters when calling a function. Parameters can be any data type(float, char, int, void). Parameters enables you to pass data from the main function or another function to another function. In our example, in the main function, we used the variable x as a parameter with the value 5 to pass to the Display function.

The Display function accepts the parameter x then displays the value of the parameter x which is 5 since we passed the variable x from the main function which contains the value 5.

Note:
The parameter variable can be any variable and is not bound to what variable the main function or other
function is trying to pass.

ex.
main()
{
int x=5;
Display(x);
}

Any of the following would do:

Display(int y)
{
}
Display(int z)
{
}
Display(int num)
{
}


:: Returning data from a function

You can return data from any function to the function
calling that function whether the data may be(int,
char, void, float).

main()
{
int y; /*Initializing the variable y.*/
int x = 5;
y = Display(x);
printf(“%d”, y);
}

int Display(int x)
{
x = x + 1;
return x; /*Returns the value of x*/
}

int Display(int x)
This means that your Display function will return an integer since you used “int” for the Display() function. You can use any data type depending on the type of data passed to such function.

return x;
This means that you are trying to return the value of the variable x to the function calling the Display() function.
x= x+1 or x=6.

y = Display(x);
In the main function, since the Display() function returns the the value of x = x+1 which is x = 6. This time, y=6.

Output: 6


Arrays

Arrays are set of variables represented by a single name. Each individual are called elements and identified with indexes. For eample, there are 10 arrayed integers, this is how we initialize the array.

int x[10];

Accessing a specific data in the array is to use the index. For example, the stored values in the array are;

0 1 2 3 4 5 6 7 8 9
5 3 4 79 34 82 23 5 74 7

To access an element in the array, the variable is followed by the index inside the bracket. For example,

printf("%d", x[0]);

Using the index to identify any element in the array, it can be treated as any variable just like any variables you use in your C program. For example,

x[5] = 10;
x[3] = 12;

You can also assign any value in any element in the array using the scanf function. For example,

scanf("%d", &x[5]);


:: Initializing array elements

int x[10] = {1,2,3,4,0,4,5,3,12,43};

Either way, you can use this;

int x[10];
x[0] = 1;
x[1] = 2;
x[2] = 3;
x[3] = 4;
x[4] = 0;
x[5] = 4;
x[6] = 5;
x[7] = 3;
x[8] = 12;
x[9] = 43;



:: Accessing array by looping

#include<stdio.h>

main()
{
int x[10];
int counter;

/* Assigning value in the array. */
for(counter =0; counter < 10; counter++)
         {
          x[counter] = rand();
         }
/* Displaying the values in the array. */
for(counter =0; counter < 10; counter++)
         {
          printf("element %d has a valaue of %d.", counter, x[counter]);
         }
}


:: Multi-dimensional array

Using multi-dimensional array is very useful. Applications like spreadsheets, inventories, and other database like applications needs to store the data in multi-dimensional array.

Let's start with two dimensional array. In multi-dimensional arrays, rows and columns appears in the picture. For example,

2 4 6
1 5 6

#include<stdio.h>

main()
{
int x[2][3];
int row, column;

/* Displays the rows */
for(row =0; row< 2; row++)
         {
          /* Displays the columns */
         for(column=0; column< 3; column++)
                   printf("%d\t.", x[row][column]);
         printf("\n");
         }
}


Pointers

@ Pointers are addresses in the memory

Data Variable
Pointer Variable

main()
{
int x;
x = 5;
printf(“%d”, x);
printf(“%p”, &x);
}
main()
{
int x;
int *p;
x=5;
p = &x;
printf(“%d”, *p);
printf(“%p”, p);
}


p = address pointing to a data variable.
*p = data inside the address pointed by p.

Data Variable
The 1st printf function in the main, tends to display the value of x which is 5 as an integer. Then it displays the address where the variable x i stored. Using the “&” symbol beside the variable x means that he is referring to the address of the variable x. It then display the address using the %p format specifier.

Pointer Variable
The same result using the Data Variable, using pointer is kind a bit complicated but is very helpful in C
programming.

int *p;
In using pointers, you need to initialize a variable as a pointer(int *p). Using the (*) symbol before the variable signifies that the variable is a pointer variable.

p = &x;
Means that since p is a pointer, the address where the variable x is stored is equalized to the pointer
variable p. From this point, pointer p is pointing to the address where variable x is stored.

printf(“%d”, *p);
It then displays the value where pointer p is pointing. Since p is pointing to the address of the
variable x, it will display the value of x. Remember, (*p = data inside the address pointed by p.)

printf(“%p”, p);
The same with when we were using the data variable, it's just that this time, we use p instead of &x.
Since p is pointing to the address of x(&x), it will display the address where p is pointing, which is the
address of where variable x is stored.

Points to remember:
- You need to identify the type of data that the pointer points to.
- You can use as many pointers pointing on the the same variable or not.
- Never use pointers which is not initialized.


Strings

Strings are stored as a null-terminated array. This means that the last charater in the array is 00 in hex or '\0' in C. Strings also has indexes and starts with index 0. In initializing strings, char data type is used.

0 1 2 3 4 5 6 7 8 9 10 11
H E L L O   W O R L D \0

There's a pointer that points or reads the string character by character. If the pointer sees a null character(\0), it terminates.

To work with strings, you need to include the string.h library.

#include<stdio.h>
#include<string.h>

main()
{
char ch[5];
clrscr();
scanf("%s",ch);                  /*The address of the string is the address of the first charater in the array(&ch[0]).*/
printf("%s", ch);
getch();
}

ch = &ch[0];

You can ommit the "&" sign and the [0] since you are using the first character in the array.

String Functions:

char *stpcpy (const char *dest,const char *src) -- Copy one string into another.
int strcmp(const char *string1,const char *string2) - Compare string1 and string2 to determine alphabetic order.
char *strcpy(const char *string1,const char *string2) -- Copy string2 to stringl.
char *strerror(int errnum) -- Get error message corresponding to specified error number.
int strlen(const char *string) -- Determine the length of a string.
char *strncat(const char *string1, char *string2, size_t n) -- Append n characters from string2 to stringl.
int strncmp(const char *string1, char *string2, size_t n) -- Compare first n characters of two strings.
char *strncpy(const char *string1,const char *string2, size_t n) -- Copy first n characters of string2 to stringl .
int strcasecmp(const char *s1, const char *s2) -- case insensitive version of strcmp() .
int strncasecmp(const char *s1, const char *s2, int n) -- case insensitive version of strncmp() .

There are still lots of string functions, these are just the basics. There are more or less 33 functions you can use in working with strings.


Structures

Structures is a collection of variables under a single name. Each variable can be of any data type and is a assigned with a name to identify it from the structure. Using structures is like defining a new type of data.


:: Defining a structure

Structures are placed almost at the top of the source code. It is usually placed after the preprocessor directives and the Global variables. To define a new type, typedef is used. For example,

typedef struct {
      char name[20];
      int age;
} info;

We can now define a new type variables of info type, this can be declared this way;

info student;

It's like you are defining a new integer variable. Structures are customed data-type like system.


:: Accessing the members in the structure

To access the members in the structure, it is just like using a normal variable but it's a bit complicated. For examle, since we defined student as a new info data type;

student.name

We need to use a dot as an operator to select the members in the structure.

Example:

#include<stdio.h>

typedef struct {
char name[20];
int age;
} info;

main()
{
info student;
clrscr();
printf("Enter name of the student.");
scanf("%s", student.name);
printf("Enter Age. ");
scanf("%d", &student.age); /*We used the "&" sign since we are referring to the address of the variable. */
printf("%s %d", student.name, student.age);
getch();
}


File I/O and Command line arguments

Save your data, retrieve your data. These are the things that are essesntial in data computing. One purpose of computers is to serve as a storage of data. Thus, the solution to this need is to use files.
In using files, we need to open the files. Opening the files also means to create files if the file does not exist.When a command a given to open a file, the operating system does the dirty work. The operating system returns a file handle to your program, it implies that you also need to have a file handle to accept it. File handles are similar to variables. To declare a handle, it goes like this,

FILE *fp;

Notice that FILE are in caps. FILE is the variable type. Notice also that we used * for the variable fp. The variable can be of any name you intend to use. From this point, we already have a so called file pointer fp.


:: Opening a file

Now that we already have a file pointer, we can now open the file using the fopen function in C. Your program tells the operating system to open the file and returns a file pointer. For example,

fp = fopen("temp.txt", "r");

The first parameter of the function fopen is the name of the file that you intend to access. The next paramater is the mode of accessing the file. Here are the different modes.

Mode Used for? File Created? Existing File?
"a" Appending yes Appended to
"a+" Reading and appending yes Appended to
"r" Reading only no Returns NULL
"r+" Reading and writing no Returns NULL
"w" Write only yes Destroyed
"w+" Reading and writing yes Destroyed


:: Writing to files

A this point, there should already be a file pointer initialized and a file opened . There are lots of ways to manipulate files. But the mostly used is the same as the concept of printf.

To write to a file, we need to use the file pointer. Using fprintf is just like using the printf, the only difference is the use of file pointer.For example,

fprintf(fp, "Let's write to this file");

Example:

#include<stdio.h>
#include<stdlib.h>

main()
{
int i, num[10];
FILE *fp;

for(i=0 ;i<10; i++)
      num[i] = i+1;

fp = fopen("num.txt", "w+");

for(i=0; i<10; i++)
      fprintf(fp, "Index %d: %d\n", i, num[i]);

fclose(fp);
}


Check out the file num.txt in you C directory.

:: Reading files

Reading files is similar to scanf. Same process, we need file pointer as a paramter for the fscanf function. For example.

#include<stdio.h>
#include<stdlib.h>

main()
{
int i;
FILE *fp;

fp = fopen("text.txt", "r");

if(fopen==NULL)
      {
      printf("File not found.");
      exit (0);
      }

while( fscanf(fp, "%d", i) ! = EOF)
      printf("%d\n",i);

fclose(fp);
}


If you open a file, be sure to close it when your done using it. To close a file, this is how it's done,

fclose(fp);

Note: fp with no *.