Created with The GIMP


2007 CHLUGger of the Year!
Mailing List
Help Open Source
Question of the Day

About Us

Directions to Meetings
Contact Us
Guest Speaker Info
Acceptable Use
Link To Us!

CHLUG Exclusives

Open Office 3.0- New and Enhanced Features New!
Linux Hacking and the Law New!
VOIP with Asterisk
Assessing OSS
Knoppix Ubiquitous Computing
Filesystem Hierarchy
Virtual Hosting
Emacs Talk Notes
Home Sweet ~
Top 100 CLIs
Device Drivers
Real Time Linux
Network Considerations Part II
Network Considerations Part I
Amanda Presentation
GNU/Linux Calculators Configuring Rio
Linux Sound
Samba notes
Network time protocol
C programming in Linux
Boot, startup and shutdown
hdparm HOWTO

Friends of CHLUG

Ubuntu NJ LoCo
Cherry Hill Library
LUG in Princeton
Useful Links

Loads of Linux Links
Art of UNIX Programming
More Links


Contact Congress
Why We Use Linux
Companies Using Linux
Linux in Business

Get Linux!

Get Firefox!


Created with The GIMP

Website Designer-

C Programming Under Linux:
Basic Concepts 1
By Carl Hein 2000.

I. The C Language -

* Simplest program:
    #include  <stdio.h>                 /* Standard-I/O library include-statement. */

    main()                                     /* Main Routine */
        printf("Hello world.\n");

* Parts of the language:

  - Variables:

       ­ Basic Variable Types:
            int    - integers
            float  - floating-point, real, decimals
            char  - characters
       ­ Variable Declarations:
            int     i, j, k;
            float  x;

        ­ Arrays[ ]:
            int     strikes[100];
            float  salaries[10];
           char  word[80];            /* Is a character-string. */

        ­ Structures:
           Data-structures enable you to make your own variable types as combinations
            of other variables.

                struct  player_stats
                        int bats, hits, runs, strikes, walks;
                        float batting_average;
                        char team[120];
                    } player[800];

            Example usage:
                    player[233].hits = 7;
                    player[233].runs = 0;

  - Statements:

    All statements must end in a semi-colon ";".
    Semi-colons separate statements from each other.
     (Multiple statements can be placed on each line.)
    Statements can be grouped into a block by squiggly brackets "{" "}".

    ­ Types of statements:

        - Variable Assignment
                    x = y + 9;        /* Variable assignment. */
        - "If" statement
                    if (condition) statement; else other_statement;      /* else-other optional */
            The statements can be blocks of statements in brackets {}.
                if (i < 3)  x = y + 9;     /* If i is less-than 3, then x gets y+9. */
                if (i < 3)
                {                                 /* Example of a block of statements. */
                    j = i;                         /* Will be executed if condition is true. */
                    printf("It happened.\n");
                if (i <= 3)  printf("i was less-than-or-equal 3.\n");
                else          printf("i was greater than 3.\n);

        - "For" loop
                for (initial_value;  end_condition;  increment)   statement;
                for (i=0;  i<10;  i=i+1)
                { printf("i = %d\n", i); }

        - "While" loop
                while (condition)  statement;
                while (i < j)  { x = x * 2.2; }
                do { x = x * 2.2; } while (x < 78.9);    /* Always does at least once. */

 - Subroutines:
        Subroutines are blocks of statements which can be called from other routines.
        Subroutines must be defined outside other subroutines.
                void  display_day( int day )
                    printf("Today's date is %d\n", day );

                /* Somewhere else, call as: */
                display_day( 30 );

        Subroutines can return values, in which case we refer to it as a function.
                int  sum( int a, int b )
                    int result;
                    result = a + b;
                     return result;
                    /* Somewhere else, use as: */
                    total = sum( price, tax );

- Input / Output:
             keyboard/screen  - scanf / printf
             character strings - sscanf / sprintf
             files              -         fscanf / fprintf
            ­ Keyboard input:
                    scanf("%d", &i);              /* Gets an integer. (int i;) */
                    scanf("%f", &x);              /* Gets a floating-point value. (float x;) */
                    scanf("%s", name);         /* Gets a character string.   (char name[9]) */

            ­ Screen ouput:
                    printf("The answer on question %d is %f for item %s.\n",   i, x, name );
            - File I/O
                    FILE *fptr;

                    fptr = fopen("myfile.dat", "r");
                    fscanf( fptr, "%d", &i );
                    fscanf( fptr, "%f", &x );

                Similarly for output,    fprintf( fptr, "whatever");

II. Compiling + Running Programs -

1. Write or edit program:    emacs, vi, joe, pico, etc..
2. Compile:                           gcc  or cc
3. Run:                                 <program_name>

            Edit:                > emacs  test.c
            Compile:         > cc  test.c -o test.exe
            Run:                > test.exe

III. Debugging -

    If you have a problem with your program, a debugger is often helpful.
    For example, if you have an endless-loop, you can stop your program
    while it runs, to see where it is and what the variables are.
    If your program crashes, you can find where it was and what values
    all the variables had.

    1. Compile with -g
                                  > cc  -g  test.c  -o test.exe
    2. Run program under gdb.   Type run at the gdb prompt.
                                   > gdb  test.exe
                                   gdb> run

      Pressing control-C will pause your program.
      Continue with:                     cont
     To see where you are:         where
     To examine a variable:         print  <variable_name>
     To quit:                                  quit

IV. Example Program

    /* Bubble Sort Example Program. */
    #include <stdio.h>

    /* Global Variable(s). */
    int number_of_values;

    /* Subroutines. */
    void initialize_dummy_data( float *list )
        int i;            /* Local variable. */
        for (i=0; i<number_of_values; i=i+1)
            list[i] = number_of_values - i;

    void bubble_sort( float *list, int N )               /* The bubble sorter subroutine. */
        int i, j;
        float tmp;
        for (i=0; i<number_of_values; i=i+1)
            for (j=0; j<number_of_values-1; j=j+1)
                if (list[j] > list[j+1])                    /* If pair of items are out of order, then ... */
                        tmp = list[j];                            /* Swap their values. */
                        list[j] = list[j+1];
                        list[j+1] = tmp;

    main()                               /* Main routine. */
        float list[1000];
        int i;

        printf("How many values would you like to sort in the list ? ");
        scanf("%d", &number_of_values );
        initialize_dummy_data( list );
        bubble_sort( list, number_of_values );
        for (i=0; i<number_of_values; i=i+1)  printf("%d  %f\n", i, list[i] );

V.  More Hints -
* C is case-sensitive.
      (int x;    is different than   int X;)

* For help at any time, use the on-line manual: man

    Example: man scanf

* Math functions, such as sin, cos, tan, sqrt, log, exp, random, etc., require that you
    include the math-library.
     1. Place

               #include <math.h>
         in the top of your program.
     2. Compile with -lm
                gcc  your_program.c  -lm  -o  my_program.exe

* If you forget the  -o executable_name  on the compile line, then C compilers
    name the executable a.out by default.
    You can always rename it:  mv  a.out  myprog

* All arrays start at zero (0).
   For example, the ten-element array:
            int Abc[10};
   Contains elements ranging from 0 to 9.

* Other good resources:

     C-Programming, K&R  (Brian Kernighan, Dennis Ritchie)