A First C Programme

This is a variant on the traditional "Hello World" programme:

/* The standard IO libs are required : */
#include <stdio.h>

/* Begin main prog --- get command-line args : */
main (int argc, char *argv[]) {

    printf("Hello ");

    /* If there are some command-line args, print each out in turn : */
    if (argc > 1) { 
        int i;
        for(i=1; i < argc; i++) printf("%s ",argv[i]);
      }

    printf(" - welcome \n");
  }


Compile source to binary named c1, then run:
    $ c1
    Hello - welcome
    $
or
    $ c1 Iain Stinson
    Hello Iain Stinson - welcome
    $



The Above Programme Step-by-Step

  1. #include is a directive which includes some definitions from the system which are required to compile and execute the program.

    Most C programs need to include such definitions, e.g., to use IO.

  2. Programme consists of one function: main --- executed when the system loads and runs the program.

  3. (int argc, char *argv[]) are the parameters passed to the program by the operating system on start, e.g., from the command line.

  4. printf("Hello ") displays the word Hello on the output device (e.g., screen).

  5. argc, formal parameter to the programme (to main), holds the number of parameters: at least one --- the name of the programme itself.

  6. if (argc > 1) checks for additional parameters --- if so, code within the inner {...} is executed.

  7. Between the inner {...}:
    1. declaration of a local integer variable i;
    2. a loop: i starts at 1, increments through 2, 3,... last value of argc;
    3. each time around the loop: corresponding parameter printed using printf("%s ", argv[i]) --- each command-line parameter is printed;
    4. as a while-loop:
                i = 1;
                while (i < argc) {
                    printf("%s ",argv[i]);
                    i++;
                  }
            

  8. Welcome is printed by last printf: the \n causes a new line character to be printed.

  9. The outer {...} contain the definition of the function main. (The function named main is always called first.)

  10. Under UNIX, argv[0] is the name by which the program was invoked; other O/S may differ...


...previousup (conts)next...



About this document:

Produced from the SGML: /home/isd/public_html/_course_crash_in_c/_reml_grp/introduction.reml
On: 3/3/2003 at 16:16:4
Options: reml2 -i noindex -l long -o html -p multiple