Chapter P1. So you want to program?

Goals for this chapter:
  • sh (bash)
  • make (make)
  • cc (cc)
  • strip (binutils)
  • touch (fileutils)
Dkystra will hate me.
Linus Torvalds.

  Programming means create, build, generate from nothing. This course will teach you, both, how to think to program and also the C language syntax from a beginner point of view and then extended to Curses, Networking and other C languages flavors. X-Window programming is covered in FTLinuxCourse: X Window: Use & Programming. HTML and Perl and covered on WebMaster course.  and Python are covered here. The Shell programming is covered in SysAdm  course.

FTLinuxCourse Programming will teach you to think to program and the C language from a mathematical basic point of view. Thus, we will review basic mathematical background and touches simple topics like elementary number theory, find root of polynomial, financial mathematics, linear algebra, analytical geometry and other simple formulas, very common and simple.

After the basics, we will cover, Curses programming and Networking programming. Then we will extend the concepts to Tcl and Python.
 

What is a program?

Programs are everywhere. For example in your town, you find everyday a semaphore. Well, the sequence, Red, Green, Yellow is tailored by a program. The shell scripts that allow to boot the Linux systems are programs tailored by the shell (generally the bash), the autoexect.bat in the DOS environment is a batch program, tailored by the COMMAND.COM, and so on.

Interpreted vs Compiled

Programs can be interpreted (a.e. shell scripts, Tcl, Expect scripts, GWBASIC programs) or compiled (C, Assembler, Pascal, ADA, etc.). Thus, a program is a list of instructions, that respect a language syntax.

A compiled program, includes in its own the binary components that allow them to run, without any other external program; thus they have a own life. Interpreted code, needs a interpreter, for example like the rc that depends from the system shell (the bash - Bourne Again Shell).

A compiled program, or a binary is the for example the "bc" (Basic Calculator).

We can use the Linux program: file, to understand this.

[root@ftosx1 /root]# file `which bash`
/bin/bash: ELF 32-bit LSB executable, Intel 80386, version 1, dynamically linked (uses shared libs), stripped
[root@ftosx1 /root]#

[root@ftosx1 /root]# file /etc/rc.d/rc
/etc/rc.d/rc: Bourne-Again shell script text
[root@ftosx1 /root]#

Therefore for an interpreted program, the source is available in the system, and is interpreted at run-time, by the shell. For example,

# /bin/sh
#
echo "The time of your first login in this session was:" `w | grep root | awk '{print $4}' | sort -r | tail -1`

To run this program, that we will call, myfirstlogin, we need to write the code, and run the interpreted, with the program:

bash# sh myfirstlogin
The time of your first login in this session was: 6:33pm

or

bash# chmod +x myfirstlogin
bash# ./myfirstlogin
The time of your first login in this session was: 6:33pm

In the second mode, we assign a "own life" to the script program.

A compiled program instead needs a compiler. (for example a C compiler).

bash# more hello.c

main ()
{
        puts ("Hello World!");
}

To compile this program you can simply run the make file "without the extension". This will compile the program.

bash# make hello
cc hello.c -o hello

To run this binary you can run the program:

bash# ./hello
Hello World!

The "program" hello is a binary!

[root@ftosx1 /root]# file hello
hello: ELF 32-bit LSB executable, Intel 80386, version 1, dynamically linked (uses shared libs), not stripped
 

Generally, Linux binaries programs and common utilities are installed in: "/bin" (Basic binaries: cp, rm, vi, chmod, ... 94 files), in, "/sbin" (System binaries: fdisk, fsck, init ... 160) and "/usr/bin" (User binaries and common utilities: awk, grep, bc) ... about 2,151 files. There are also the X Window System binaries installed in "/usr/X11R6/bin/". The word "bin" stand for binaries!

You can also strip the compiled binaries. Strip a program means removes the symbolic information. The symbolic information is "only" necessary to debug the program. Who will debug a program with a single line?

Therefore we proceed to strip it. Before to strip it we list the size.

[root@ftosx1 /root]# ls -al hello
-rwxr-xr-x    1 root     root        11733 Apr 25 17:40 hello

To strip, this program we run:

[root@ftosx1 /root]# strip hello
[root@ftosx1 /root]# ls -al hello
-rwxr-xr-x    1 root     root         3012 Apr 25 17:40 hello

to know the difference we run the "bc" (Basic Calculator)

[root@ftosx1 /root]# bc
bc 1.05
Copyright 1991, 1992, 1993, 1994, 1997, 1998 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
11733-3012
8721
quit
[root@ftosx1 /root]# file hello
hello: ELF 32-bit LSB executable, Intel 80386, version 1, dynamically linked (uses shared libs), stripped
[root@ftosx1 /root]#

This is the difference between interpreted and compiled programs. In interpreted, the source is available. OpenSource philosophy offers also the source code, for the binaries!.

To write programs is necessary to build the program, with the final result in the mind, respecting the language syntax.

Without any previous programming knowledge, now we will try to write a program that do the semaphore steps.

Are you ready?

It is very easy!

This program will be something like the following:

1. Red light.
2. Wait 10 seconds.
3. Green light.
4. Wait 25 seconds.
5. Yellow light
6. Wait 5 seconds.
7. GOTO 1

Graphically,
 
 

Is this sample program clear to you? Is very easy!.

In its simplicity, it is a formal (infinite program, infinite means that never ends).

Its presents the "classical" program instruction, like:

Thus, you have your first program.

The last program, present a numbered sequence, line 1, line 2, ... . The BASIC (Beginners All purpoSe Instruction Set) language, probably the most easy programming language, introduces the line numbers.

Today, C/C++, Java and other languages don't offers this simplicity.

A first example in C language

From a hardware point of view programming languages may be classified in:

Low-level programs are programs that interact directly with the machine processor, called generally, assembler language. This programs may be for INTEL 8088-80386 ... Pentium III-4, or Motorola 68000, or PowerPC G4! Low-level programs run very fast, is just processor code!

Programs more near to the end user, are called high-level. This means that they are easy to use. BASIC, FORTRAN are high-level languages. High-level language run not very fast as assembler. Clearly, run more slow than low-level programs.

The C language was written to be easy, and therefore near to the user, but fast in running procedure. Some test, show that C compiled code (for example Eratosthenes Sieve1) are about 60 times more fast than a program written in BASIC language.

C language is the "standard" language in UNIX system from the beginning. The most important binary programs in Linux are written in C. The kernel is written in C, with some assembler programs that depends of the platform; all the graphical, X-Window/KDE/GNOME ... programs are written in C or C++, compiled with the relative library.

In FTLinuxCourse BASE, we present some simple example that now we recover here: the multiplicity table by 2: multi2.c
 

main ()
{
    int i;

        for (i=1; i<=10; i++)
        printf ("%2d   %3d\n", i, i*2);
}
 

This simple C code, run a finite loop, from 1 to 10 and print for each iteration the "iteration number" (i), and the "iteration number by 2" (i*2).

Now, we will go further on this code and start to explain some rudiments in the syntax.

The "main" procedure.

Each C program have a "main" procedure that interact with the system. It's called "main" to understand that there are no other principal procedure, and that probably the program will includes other (secondary) procedures.

If you knows, UNIX or Linux, we probably remember some system operations like "cp" (copy), that require arguments. For example, for the copy program, "cp", is necessary a source and a target.

For example:

bash# cp from.c to.c

This means the program, "from.c", was duplicated and called "to.c". Both files, are arguments for the "cp" program.

How is possible to program this?.

C offers, the "argv and argc" operators to be included in the main procedure.

We will modify the last program, "multi2.c" to print any table depending of the parameter. Therefore, when we will run,

table 2

will appears the Multiplicity table of 3 and when we run

table 17

will print the Multiplicity table for 17.

The code is as follows:
 

main (int argc, char ** argv)
{
    int i, myarg;
    char str[20];

        /* Assign the parameter to a allocated char, 20 bytes long.*/
        strcpy (str, (char *) argv [1]);

        /* Transform the string to an integer */
        myarg = atoi (str);

        for (i=1; i<=10; i++)
        printf ("%2d   %3d\n", i, i*myarg);
}
 
 

[root@ftosx1 /root]# make table
cc     table.c   -o table

[root@ftosx1 /root]# ./table 2
 1     2
 2     4
 3     6
 4     8
 5    10
 6    12
 7    14
 8    16
 9    18
10    20
 

[root@ftosx1 /root]# ./table 17
 1    17
 2    34
 3    51
 4    68
 5    85
 6   102
 7   119
 8   136
 9   153
10   170
[root@ftosx1 /root]#

Now, before anything else, we will explain each line of code.

At first we present the Data Declaration:
 
 

int  integer: 1, 2, 3, 56, 90, 3216.
char character: 'a', 's', '1' ...

Now, we explain line by line
 
 

char str[20] means that the str variable is a variable char type that will includes at most 20 characters. The content is not initialized, and the variable is not allocated.
/*  */ is used to comment, like C at the beginning of the line in FORTRAN or REM in BASIC Languages
strcpy (str, (char *) argv [1]); Now, we transfer the content of the "argv[1]", the first argument that the user add after the program name to the variable str.
In this moment, the variable str is allocated.

An assignation like: str = argv[1]; have no sense, in this context.

The program name is argv[0].

myarg = atoi (str); Now, with the variable allocated we can transform the content to a number to be used in the program.

As explained in the atoi manual page (Run man atoi), the atoi function is equivalent to 

strtol(nptr, (char **)NULL, 10); 

with the difference that 
for (i=1; i<=10; i++)
        printf ("%2d   %3d\n", i, i*myarg);
This is the mode C perform loops.

Is also possible to create infinite loops, in the form:
 

for (;;)

Is possible to comment the previous source covering details like trap errors, add an exit at the end of the program to be orthodox, and other similar comments.

In the past years, was used the program, lint a C checker that find C errors in the syntax and the form.

We run here, the "lclint" an updated version for Linux, and found the following errors:
 

[root@ftosx1 bin]# ./lclint ../../table.c
LCLint 2.2a --- 02 Sep 96

Cannot find standard library: ansi.lcd
     Check LARCH_PATH environment variable.
../../table.c: (in function main)
../../table.c:8,9: Unrecognized identifier: strcpy
  Identifier used in code has not been declared. (-unrecog will suppress
  message)
../../table.c:11,17: Unrecognized identifier: atoi
../../table.c:14,9: Unrecognized identifier: printf
../../table.c:15,2: Path with no return in function declared to return int
  There is a path through a function declared to return a value on which there
  is no return statement. This means the execution may fall through without
  returning a meaningful result to the caller. (-noret will suppress message)
../../table.c:2,11: Parameter argc not used
  A function parameter is not used in the body of the function. If the argument
  is needed for type compatibility or future plans, use /*@unused@*/ in the
  argument declaration. (-paramuse will suppress message)

Finished LCLint checking --- 5 code errors found

For example the atoi function was not recognized. To solve this we need to declare what the function is before to use. Running the man page, we got that the atoi function is included in the include file  <stdlib.h>.

NAME
       atoi - convert a string to an integer.

SYNOPSIS
       #include <stdlib.h>

       int atoi(const char *nptr);

DESCRIPTION
       The  atoi()  function  converts  the  initial  portion  of  the string pointed to by nptr to int.  The
       behaviour is the same as

              strtol(nptr, (char **)NULL, 10);

       except that atoi() does not detect errors.

RETURN VALUE
       The converted value.

CONFORMING TO
       SVID 3, POSIX, BSD 4.3, ISO 9899

SEE ALSO
       atof(3), atol(3), strtod(3), strtol(3), strtoul(3)

GNU                       March 29, 1993                        1

(END)
 

To have an almost perfect (perfect is impossible) code we need to add all the "#includes" and solves all the warning. This "perfection" style is a real problem. To solve this was create the POSIX standard by the IEEE

Linus Tovalds ask for POSIX complaint information after his first kernel release.

Also in these days is possible that a specific compiler present bugs (for example the 2.96 gcc is not perfect).

Reading specs from /usr/lib/gcc-lib/i386-redhat-linux/egcs-2.91.66/specs
gcc version egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)
[root@ftosx1 /root]#
 

Is also possible that sometimes you download a source and your compiler generate errors; is very strange but probably. For example if you try to download the "official" LILO 21-.6.1 on SuSE 6.4, you will find the following "errors".

heaven:~/lilo-21.6.1 # cc -v
Reading specs from /usr/lib/gcc-lib/i486-linux/egcs-2.91.66/specs
gcc version egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)
heaven:~/lilo-21.6.1 # make
cc -E check-config.cpp `( if [ -r $ROOT/etc/lilo.defines ]; then cat $ROOT/etc/lilo.defines; else echo -DM386 -DIGNORECASE -DVARSETUP -DREWRITE_TABLE -DONE_SHOT -DVERSION -DREISERFS; fi ) | sed 's/-D/-DLCF_/g'` `[ -r /usr/include/asm/boot.h ] && echo -DHAS_BOOT_H` >/dev/null
as86 -0 -a -w -l temp2.lis -o temp2.o temp2.s
00821 0321           74           00>           toNull: je      near null       ! cursor control
*****                                                                ^junk after operands
01510 07D3           72           00>                   jb      near doload
*****                                                                ^junk after operands
00821 0321           74           00            toNull: je      near null       ! cursor control
*****                                                           ^unbound label
*****                                                                ^junk after operands
01510 07D3           72           00                    jb      near doload
*****                                                                ^junk after operands
*****                                                                ^unbound label

00004 errors
00000 warnings
make: *** [temp2.o] Error 1
rm temp2.o
heaven:~/lilo-21.6.1 #

If you compile this source using other compiler you will built the lilo program without problems.

In 1991, when Linus Torvalds was a student, built the gcc compiler on a 386 machine with 4 MB was a very nice experience. From single source (like now), you start a compilation using another compiler. For example, to run or compile TeX or xdvi, the authors advice your to compile the "gcc".

The "gcc", the GNU C Compiler offers a betters performance and support some simple and fundamental memory arrays than neither official and expensive compilers like SCO "cc" solves.

The "gcc" compilation on a UNIX Interactive takes differents steps, ten years ago. The first step was the compilation itself. When the compilation starts the internal procedures tests if the C compiler, you are using was a good compiler. Then, the procedure runs its tests to know if the compiler create good binaries.

On a 386 with 4 MB, the gcc compilation from the UNIX Interactive C compiler, takes about four hours, in 1991. This time includes all the test and the compilation.
 

Float and Double

Now, we will introduce a new example to introduce the float and double data types and some elementary math C operators.

Kernighan and Ritchie in the classical the "The C language" introduce float numbers using a for that present a table between Fahrenheit and Celius grades. Bjarne Stroustrup instead presents an inch-to-centimeters transformation.

We instead present here a program that allows to found the square root using simple operations like multimplication, addition and division.

I discover this program 2, long time ago.

We write here in plain english ... then we will translate in C Language.

This program offers a method to found the square root using simple arithmetic operations like addition, multiplication and division

In plain English (or BASIC Language):

1.  READ THE NUMBER, X  ... (also INPUT X ... is the valid sequence)
2.  Y = X;
3.  Y1 = Y
4.  Y = 1/2 * (Y + X/Y)
5.  IF ABS(Y-Y1) < 0.000001 PRINT "THE SQUARE ROOT OF X IS Y:" X, Y. EXIT
6.  GOTO 3
 

#include <math.h>
main ()
{

    float x, y, y1;

    x = y = 3;

    for (;;) {
      y1 = y;
      y = 0.5 * (y + x/ y );
      if (fabs(y - y1) < 0.000001)  {
            printf ("The squared root of %4.6f is %4.6f\n", x, y);
            exit (0);
      }
    };

    printf ("%6.2f\n", y);

}

You can get this program from FTContribs/Files/C_C++/ProgrammingCourse/1/sqrt.c

To compile this program we need to run:

[root@ftosx1 ProgrammingCourse]# make sqrt
cc     sqrt.c   -o sqrt
[root@ftosx1 ProgrammingCourse]#

... and run it

[root@ftosx1 ProgrammingCourse]# ./sqrt
The squared root of 3.000000 is 1.732051
[root@ftosx1 ProgrammingCourse]#

Done!

You can run this simple program also using a simple calculator ... without the square root. You can repeat and repeat the procedure. When the number you found does not change. This number will be the square root.

Of course there are a simple and clear mathematical explanation how this algorthm converge to the square root.

The first value of X may be X[0], the second value of X, in the algorithm may be X[1], and so on. We will call the "limit' of the sequence of values of X[N], "Y".

Then, like at the line 4 of the algorithm, we have

Y = 1/2 * (Y + X/Y)

Then we have:
 
 
2Y = Y + X/Y 2Y^2 = Y^2 + X 2Y^2 - Y^2 = X Y^2 = X Y = SQRT(X)

From a mathematical point of view this is called "limit". From a computational point of view, these sequence are:

Y[N] = 1/2 * (Y[N-1] + X/Y[N-1])








Using similar formulae you can obtain the cubic and the N-th root of any number, only using  simple operation.

We suppose that is clear that:
 
 

+ Is the sum, the addition: a+b=c, 2 + 1 =3
Is the subtraction, 1- 1 = 0, 9 - 8 = 1
* multiplication, 2 * 3 = 6
/ division, 6/3 = 2, 1/8 = 0.125, 1/3 = .333333333 ...
% rest or remainder, 4%2=0, 5%2=1

Now, is important to understand that the C language offers (necessarily) a priority order to follow the operations.
 
 

Precedent is from Left to right 
*   /  %
+   -

You can add as many parethsis you need to fix your precedence. We will cover more in depth this topic and for a formal point of view in Chapter 2: P2

To compile the program we run: "make sqrt". Just the source name without the extension.

What happens if we try to run again?

[root@ftosx1 ProgrammingCourse]# make sqrt
make: `sqrt' is up to date.
 

You obtain a message from the make program that explain us that the program is up to date; in other words a compilation was not necessary.

This happens because the binary date is more updated than the source date!. We can check with "ls".

[root@ftosx1 ProgrammingCourse]# ls -al
total 17
drwxr-xr-x    2 root     root           77 Apr 26 21:56 .
drwxr-xr-x    3 root     root          258 Apr 26 15:33 ..
-rwxr-xr-x    1 root     root        12058 Apr 26 20:48 sqrt
-rw-r--r--    1 root     root          262 Apr 26 20:48 sqrt.c
[root@ftosx1 ProgrammingCourse]#
 

However, UNIX and Linux offers us a mode to touch or modify the source date forcing the compilation!

To do that we need simply to run, the "touch" program

[root@ftosx1 ProgrammingCourse]# touch sqrt.c
[root@ftosx1 ProgrammingCourse]# make sqrt
cc     sqrt.c   -o sqrt

Another important fact is that we are running the make, without the Makefile.

[root@ftosx1 ProgrammingCourse]# ls -al Makefile
ls: Makefile: No such file or directory
[root@ftosx1 ProgrammingCourse]#

Generally "any" compilation needs a "make". For example to built a kernel, you need simply to run a compilation ... the kernel compilation.

This compilation is tailored by the "/usr/src/linux/Makefile"

Real Complex Makefiles are present in the X Window System compilation. We will cover Makefile in Chapter 6: P6

The Environ

In the first example that we write in C language

#include <stdio.h>

main (int argc, char ** argv, char ** environ)
{
    int i=0;

    while (environ[i])
        printf ("%s\n", environ[i++]);
}

We compile ...

[root@ftosx1 ProgrammingCourse]# make myenv
cc     myenv.c   -o myenv

and run ...

[root@ftosx1 ProgrammingCourse]# ./myenv
LESSOPEN=|/usr/bin/lesspipe.sh %s
USERNAME=root
COLORTERM=
HISTSIZE=1000
KDE_MULTIHEAD=false
HOSTNAME=ftosx1.futuretg.com
LOGNAME=root
KDE_DISPLAY=:0.0
GTK_RC_FILES=/etc/gtk/gtkrc:/root/.gtkrc:/root/.gtkrc-kde
LD_LIBRARY_PATH=/root/adabas/lib:/root/adabas/lib:/root/adabas/lib:/root/adabas/lib:/root/FTOSX/FTKDE/latest/qt/lib:/usr/X11R6/lib::/usr/lib
MAIL=/var/spool/mail/root
DBROOT=/root/adabas
DBWORK=/root/adabas/sql
TERM=xterm
HOSTTYPE=i386
LTDL_LIBRARY_PATH=/usr/lib
KDEDIR=/usr
PATH=/root/adabas/bin:/root/adabas/pgm:/usr/kerberos/bin:/root/adabas/bin:/root/adabas/pgm:/root/adabas/bin:/root/adabas/pgm:/usr/local/sbin:/usr/sbin:/sbin:/root/adabas/bin:/root/adabas/pgm:/usr/kerberos/bin:/sbin:/usr/sbin:/bin:/usr/bin:/usr/X11R6/bin:/usr/local/bin:/usr/X11R6/bin:/usr/bin:/root/FTOSX/FTKDE/latest/qt:/usr/bin/Acrobat4/bin:/root/bin
HOME=/root
INPUTRC=/etc/inputrc
DBCONFIG=/root/adabas/sql
KDE_INITIAL_DESKTOP=1
SHELL=/bin/bash
QT_XFT=0
USER=root
BASH_ENV=/root/.bashrc
QTDIR=/root/FTOSX/FTKDE/latest/qt
DISPLAY=:0.0
SESSION_MANAGER=local/ftosx1.futuretg.com:/tmp/.ICE-unix/1198
LANG=en_US
OSTYPE=Linux
SHLVL=2
LS_COLORS=no=00:fi=00:di=01;34:ln=01;36:pi=40;33:so=01;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=01;32:*.cmd=01;32:*.exe=01;32:*.com=01;32:*.btm=01;32:*.bat=01;32:*.sh=01;32:*.csh=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.gz=01;31:*.bz2=01;31:*.bz=01;31:*.tz=01;31:*.rpm=01;31:*.cpio=01;31:*.jpg=01;35:*.gif=01;35:*.bmp=01;35:*.xbm=01;35:*.xpm=01;35:*.png=01;35:*.tif=01;35:
_=./myenv
[root@ftosx1 ProgrammingCourse]#
 

The global C variable "environ", does not appear in C books like the standard "argv" and "argc". But is particular important to get variables like the "path", and others. The "environment" is commonly used in "Networking programming"

We will cover Network Programming techniques in Chapter 11: P11

A first example in C++

In C, the "++" operator means the next.

For example, if we have in C,

    x = 30;

    y = x++;

    y will be 31.

A similar operator is available for subtraction "--".

Now, What may be C++, like a C extension?

C++ solves simple C problems like input data and basically offers a mode to abstract data using classes.

Dr. Stroustrup, develop its C++ and present to us in the following articles:

In this chapter 1, we will present only some simple modes to input and output data, in C++.

For example, we offers a C++ version of the "multi2.c"
 

In C: multi2.c In C++ multi2.cc
main ()
{
    int i;

        for (i=1; i<=10; i++)
        printf ("%2d   %3d\n", i, i*2);
}

#include <iostream.h>
#include <stream.h>

main ()
{
    int i;

    for (i=1; i<=10; i++)
         cout << i << " " << i*2 << "\n";
}

To compile the C++ program we need to add the C++ library:

[root@ftosx1 1]# gcc multi2.cc -o multi2++ -lstdc++
[root@ftosx1 1]# ./multi2++
1 2
2 4
3 6
4 8
5 10
6 12
7 14
8 16
9 18
10 20
[root@ftosx1 1]#
 

Now, we do the same for the program table that get data from the command line
 

In C: table.c In C++ table.cc
main (int argc, char ** argv)
{
    int i, myarg;
    char str[20];

        /* Assign the parameter to a allocated char, 20 bytes long.*/
        strcpy (str, (char *) argv [1]);

        /* Transform the string to an integer */
        myarg = atoi (str);

        for (i=1; i<=10; i++)
        printf ("%2d   %3d\n", i, i*myarg);
}

#include <g++/iostream.h>
#include <g++/stream.h>

main ()
{
    int i;

    for (i=1; i<=10; i++)
         cout << i << " " << i*2 << "\n";
}

[root@ftosx1 1]# gcc table.cc -o table++ -lstdc++
[root@ftosx1 1]# ./table++

Enter the number?35
1 35
2 70
3 105
4 140
5 175
6 210
7 245
8 280
9 315
10 350
[root@ftosx1 1]#
[root@ftosx1 1]#
 

We note how the "cin <<" operator for input is more easy that the "string" to "int" transformation that need a strcpy to allocate the memory.

C++ is a long better than C. C is the classical and continue to be used with success.

GNOME uses simple C. KDE based on Qt uses C++. This is another reason why Qt a commercial now free graphical libraries are "better" than the "excellent" Gtk libraries.

We will cover C++ Programming Language in
 

How to Design of a Program with a Flow Chart

Design a program may be an "art", like Dr. Knuth explain us about twenty years ago. Anyway is important to understand "how to" design a program.

When I start to study Computer Sciences, in 1980, in the UCV, my teacher explain me that "a good flow chart will be a good program, syntax language may be learned in a week".

We present here a flow chart template and describe each component:
 
 

You can use flow chart symbols to "start", to stop, to visualize the "input data", the "print", the cycles: for, while, the conditionals: if, while, etc.

A flow char is a draw ( a chart) that reproduce the program flow.

For example, we have:
 
 

The sum of the first 50 numbers
The maximum between three numbers
The factorial of N. N! = 1 * 2 * 3 * ... N

In this OpenSource days, understand source and write new code make the difference.

To make a chart you need a template ... or simply you can use StarDraw included in StarOffice 5.2, that is for free.

With StarOffice you can create charts likes the following:
 
 







We will conclude this first chapter developing two flow charts:

I discover this "natural" mode to obtain the cubic root, from the square root, using a simple calculator "naturally".

1. Find a simple calculator
2. Press a number.
3. Then press the square root button, twice (two times).
4. Now, multiply the new number by the original.
5. If the result does not changes then the cubic root was found.
6. Go to step 3 ... and repeat the procedure until the number generate by the process does not change.

Try this with a simple calculator!

Now, we provide the flow chart for this algorithm:






In different examples here we use the GOTO statement. However in Dijkstra, E.W.  in 1968: "Goto Statement Considered Harmful", CACM, v11 (March ) pp. 147-148, shows that the goto statement is considered to be harmful because it hampers program understandability. For these reason, no goto are used in C programming languages. Control and loops are substituted by "if" "for" while" and other similar statement.

The second algorithm prints the factors presents in a number. Linux offers this binary: factor

[root@ftosx1 /root]# factor
64
64: 2 2 2 2 2 2
1061
1061: 1061
6
6: 2 3

[root@ftosx1 /root]#

Some mamethical collegues spend years to knows if a specific number is prime or not.

The process is very simple. We test the rest of the division from 2 until N -1. If the rest is zero, then we print the number.


Once, you know to think to program, you can write programs in any language: HP Programmable calculators, in BASIC, in FORTRAN, in C, in C++, in Assembler 80386 ... in any assembler language.

To write graphical programs using Qt, you need to know the library function names.
 
 

Exercises

  1. Download a C source and try to understand the C Data Declaration and the logical operators
  2. Using StarDraw to create the flow charts for all the programs in this chapter.


Test

  1. What are the difference between interpreted and compiled programs?.
  2. Where are located system binaries?
  3. The "vi" is a system binary (/sbin), a basic binary (/bin) or a user binary (/usr/bin) ?
  4. Where is located the "chmod" binary program is a system binary (/sbin), a basic binary (/bin) or a user binary (/usr/bin) ?
  5. What is the word in C syntax to represent the principal procedure?
  6. What is the word in C syntax to represent the arguments (or parameters) that the user add in the command line when run the program ?. What variable contains the number of arguments?
  7. What is the word in C syntax to add and get the environment?
  8. What is the C function to transform strings to numbers?
  9. Why is necessary to use strcpy before to transform argv[1] to an integer?
  10. What is the content of argv[0] ?
  11. What is the C operator for the rest in an integer division?
  12. What is the C++ operator to print output? and to read ?
  13. What is the flow chart element for a cycle ?
  14. Write a program to print a table of sinus and cosines from 0 to 100.
Consult the answers

Check the Interactive Exam Cram Programming: Try the interactive cram ...

Internet Resources for this Chapter.



1 - Eratosthenes Sieve is a method that find all the primes between 2 and N, after remove the composite (not prime) numbers.
2- This was the first real program I wrote at sixteen, in BASIC.