Appendix L. Learning a Programming Language syntax in one day.

I learn BASIC programming language alone at sixteen, using the original book written by the BASIC Language developers Kemeny and Kurtz. Some months later in enter in the University (UCV) and my professor explain me that the method applied in the faculty, is just present examples about the programming language. The alumns needs to learn the language syntax in about three or four days, himself alone.

Fast Training Linux Course covers, C, C++, Tcl, Python, PERL, PHP, MySQL, BASH, as well as Tk, Expect, and the graphical libraries Qt, Gtk, [Open]Motif, and Java and JavaScript as well. TeX are also covered.

A Programming Language haves its syntax.

C Language for example expect a semilcon: ";" at the end of any statement. Cycles are opened and closed with "{" and "}".

In JAVA similar rules are valid. In Tcl or BASH these semicolon are not necessary.

This appendix wants to presents a systematic approach to learn the syntax for any language in hours. We present a specific approach to learn each language covered in the Fast Training Linux Course.

Expressions

In this section we cover:


Expressions are the mode to access data. Data Types may be natural numbers, integers: like: 1, 345, 1041, 90, or  rational numbers, float in C, like: 2.71, 1.7777, 3.1, and others. The precision in operations, like sum, substraction, may lose decimals for this reason are available for example in C, the double, as a data type.

In C we have constants:

#define MYBUFSIZE 512

#define A    90.45

In C++ is more explicti the definition of C. Simply,

cost a = 3.4556;

Other modes is using variables, a, a1, l90, mystring and others. This changes from language to language. For example in Tcl we have:

set a 90

or

set a "The dog is black"

But, in C or C++ assignment changes for data type. You may have for example:

    a = 91.89;

and

    strcpy (mystring, "The dog is black");

In C++, we can define variables

if (int a = myvalue(default)) {
    b = a++;
}
 

In the normal shell programming, BASH

a=1
echo $a

In C-Shell, we have:

set esc="\033["
 

Arrays

In C, an array is a classical memory set of data, which declaration is the following:

int mydigits [10];

In Tcl, is used the concept of list.

list a b "Is fun"
a b {Is fun }

You can search elements inside the list or add new one using "concat"

lindex [list a b "Is fun"]

In Python, we have

>> a = ['spam', 'eggs', 100, 1234]
>> a[0]
'spam'

In PERL we have

#!/usr/bin/perl -w

@my_net = qw(world ftosx1 ftosx2 heaven www thunder wind earth);
print "@my_net"\n;
world ftosx1 ftosx2 heaven www thunder wind earth
 
 





Control Structures

In this section we cover:

Control structures are the mode to use a code and in accord to a condition, applies the first, or the second code.

Generally, the if-the-else control structure presents the same mode. we list here examples in C, Tcl and BASH

In C, we have,

if (a == b) {
    b =c;
} else {
    a = 1;
}

In C++ control structures are the same. The difference between C and C++, are in the uses of classes, Data Abstraction and Inheritance

In Tcl, we have

if [catch {open $myfile} input] {
    puts "$input"
    return;
}

In BASH Shell we have,

if [ ! -f /etc/sysconfig/network ];
then exit 0;
else echo "this is my way";
fi

In Python, we have

if x < 0:
       x = 0
            print 'Negative changed to zero'
      elif x == 0:
            print 'Zero'
      elif x == 1:
            print 'Single'
      else:
           print 'More'
 

and in PERL we have

if ($x > $ y) {
    print "$x is high than $y";
} elseif ($x < $y) {
    print "$x is high than $y";
} else {
    print "$x is equal than $y";
}
 

The For statement is used for a pre-fixed cycle of data with a fixed step.

In C, the natural mode for a for is as follows:
 

for (i=1; i< 90; i++) {
   printf ("%d %d ",i, i*8 );
}

In C, is also used the for for and infinite cycle.

for (;;){
}

In PERL we have:

for ($a=0; $a < 90; $a=$a+3) {
    print "a is now $a\n";
}

Like in Tcl, we can also use foreach

@my_net = qw(world ftosx1 ftosx2 heaven www thunder wind earth);
foreach $record (@my_net) {
    print "$record\n";
}

In BASH

for file in ./*.html
do
        echo "Processing file ..." $file
        sed -f ./sed.str < $file > ./mytmp1
        mv ./mytmp1 ./$file
done
 

The While is the statement that

while {
    ;
} (1)

In PERL we have

while ($counter < 100) {
    print "... and we have $counter\n";
}
 
 

The switch is similar to an extended if-elseif statement but

In C++ we have:

switch (val) {
    case 1:
        f1 ();
    case 2:
        g ();
}
 

In the BASH we have in normal scripts:

case "$1" in
  start)
        echo -n "Starting INET services: "
        daemon inetd
        RETVAL=$?

        echo
        [ $RETVAL -eq 0 ] && touch /var/lock/subsys/inet
        ;;
  stop)
        echo -n "Stopping INET services: "
        killproc inetd
        RETVAL=$?

        echo
        [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/inet
        ;;
  status)
        status inetd
        RETVAL=$?
        ;;
  restart)
        $0 stop
        $0 start
        RETVAL=$?
        ;;
  reload)
        killall -HUP inetd
        RETVAL=$?
        ;;
  *)
        echo "Usage: inet {start|stop|status|restart|reload}"
        exit 1
esac

Passing By Reference

Passing by Reference is a classical and used mode to work. May be complex to understand but is necessary.

For example writing programs for a HP-41C, you can pass by reference and access the content of a remote variable.

You can have A[1]=2. Then, you can access, B[A[1]] = B[2]. In this mode are accessing

In C, the Classical mode to strcpy in C,

void strcpy (char *s, char *t)
{

    while (*s++ = * t++)
        ;
}
 

Data Structures

In C, is common to use structures and union. However after the inroduction in C++ of the concept of class, the use become more and more popular. Languages like Python works with classes.

We present some declarations in C/C++ and Python.

In C we have, for example:

struct student {
    char name[25];
    int id, age;
    char sex;
};

To use these structures we can

struct student s1, s2;

In the same way we can declare and use unions

typedef struct {
    float area, perimeter;
    int type;

    union {
        float radius;
        float a[2];
        int b[3];
        position p;
    } geom_fig;
} figure;
 

The variable may be defined like:

figure fig;

And we can have:

fig.type = 44;
 

In C++ we can have

struct stack {
    private:
        char s[max_len];
        int top;
    public:
        void reset () { top = 0};
        void push (char c) { top++; s[top] = c }
        char pop ()  {retrun (s[
};
 

In Python we generally uses lits

stack = [3, 4, 5]
stack.append(6)
stack.append(7)
 

however there are also other data structures like dictionaries.

File I/O

The necessary information about files must be how to open, to close, how to write and append data. Also check if the file information may be usefull.

For example in Tcl we haveRe: Please let me know if you can help me again ...

open "/tmp/mytmp" "w"

In C++, we have

if (!f_in.open (argv[1], input)) {
                cerr << "cannot open " << argv[1];
                exit (1);
}

In PERL we have,

if (! open (MYFILE, "output") {
    print "I am here\n";
}

Programs,  functions and includes

After that you knows how to declare variables, the first step is

In BASIC was very common the SUB (to call a specific code) in a specific moment. In structured languages like PASCAL, C, C++, or Tcl, are used functions.

For example in C, we have

main ()
{
        my_func(par1, par2);
        do_something();
}

my_func(par1, par2)
{

        do_the_repetitve_task(mypar1, mypar2)
}

Similar behaviour we have for other languages.

Examples

About examples there are a lot of "default minimal examples". Algoritms are like secret jewels for computer teachers.

Each examples presents a method and illustrates the concepts like

Here we list the most common examples:


Hello World

This is the classical example to print data. Is some mode to say: "I am present and try to understand this language".

We list here a couple of minimal examples for C

main (){
    puts ("Hello World\n")
}

or you can use "printf" (formatted print), instead puts (put string)

In C++ we have

#include <stream.h>

main ()
{
    cout << "Hello World !" "\n";
}
 

In PERL we have:
 

#!/usr/bin/perl -w

print "Hello\n";
 

The Python version equivalent. Both languages will join to a new name called Parrot.
 
 

Print a table of data with decimals

After the first example, is common to present examples with decimal numbers.

We present here a table with the number and its square and cubic root.

main ()
{
        for (i=1; i <= 23; i++)
            printf ("%d   %6.4   %6.4", i, sqrt(i), power(i, 1/3));

}

In PERL we can use for to print a list of primes.

However, we prefer to present a famous enthusiast PERL script, that prints an infinite list of number is:

perl -wle '$_ = 1; (1 x $_) !~ /^(11+)\1+$/ && print while $_++'
 

(I get the last algorithm at: Primes and the Perl regular expression parser )

This second example presents a control data structure and float data.

Numerical algoritms likes, the Euclid Algothim, find the square root of a number, Print a list of primes, the Eratosthenes sieve and other similar.

Here we list the algorithms in C or C++.

/*
* Euclid
*/
# includes <stdio.h>
int gdc (int u, int v)
{
    int t;
    while (u > 0) {
        if (u < v) {
            t =u;
            u = v;
            v = t;
        }
    u = u - v;
    }
    return v;
}

main () {
    int x, y;
    while (scanf (%d %d", &x, &y)
        if (x > 0 && y > 0)
            printf ("%d %d %d\n", x, y, gdc (x,y));
}

/* End of Euclid */
 

Working with strings

Other examples may be created using strings.

A complete project using structures and files, may complete a primary panorama.

A complete project with files, must use, for example structures, scanf and printf, on a small DataBase.

Conclusions

To learn a programming language after you know the syntax is necessary only to formulate good exercises and solves it.  Fast Training Linux Course covers with examples a high number of techniques.

Write the same algorithms in different languages helps to understand the differences between the languages, and how each language handle different structures.

In Linux with the OpenSource ... you have access to all the source ... strcpy source, vi source, Motif source ... and everything you can dream. One of the goals of Fast Training Linux Course is to teach you all the necessary, to moves in the Linux Source without problems.