Wednesday, January 9, 2013

Shell Programming:DECISION-MAKING & LOOP CONSTRUCTS


DECISION-MAKING & LOOP CONSTRUCTS:

* Shell programs can perform conditional tests on their arguments and variables and execute different commands based on the results. For example:

   if [ "$1" = "hyena" ]
   then
     echo "Sorry, hyenas not allowed."
     exit
   elif [ "$1" = "jackal" ]
   then
     echo "Jackals not welcome."
     exit
   else
     echo "Welcome to Bongo Congo."
   fi 
   echo "Do you have anything to declare?"

-- checks the command line to see if the first argument is "hyena" or "jackal" and bails out, using the "exit" command, if they are. Other arguments allow the rest of the file to be executed. Note how "$1" is enclosed in double quotes, so the test will not generate an error message if it yields a null result.
There are a wide variety of such test conditions:

   [ "$shvar" = "fox" ]    String comparison, true if match.
   [ "$shvar" != "fox" ]   String comparison, true if no match.
   [ "$shvar" = "" ]       True if null variable.
   [ "$shvar" != "" ]      True if not null variable.

   [ "$nval" -eq 0 ]       Integer test; true if equal to 0.
   [ "$nval" -ge 0 ]       Integer test; true if greater than or equal to 0.
   [ "$nval" -gt 0 ]       Integer test; true if greater than 0.
   [ "$nval" -le 0 ]       Integer test; true if less than or equal to 0.
   [ "$nval" -lt 0 ]       Integer test; true if less than to 0.
   [ "$nval" -ne 0 ]       Integer test; true if not equal to 0.

   [ -d tmp ]              True if "tmp" is a directory.
   [ -f tmp ]              True if "tmp" is an ordinary file.
   [ -r tmp ]              True if "tmp" can be read.
   [ -s tmp ]              True if "tmp" is nonzero length.
   [ -w tmp ]              True if "tmp" can be written.
   [ -x tmp ]              True if "tmp" is executable.

Incidentally, in the example above:

   if [ "$1" = "hyena" ]

-- there is a potential pitfall in that a user might enter, say, "-d" as a command-line parameter, which would cause an error when the program was run. Now there is only so much that can be done to save users from their own clumsiness, and "bullet-proofing" simple example programs tends to make them not so simple any more, but there is a simple if a bit cluttered fix for such a potential pitfall. It is left as an exercise for the reader.
There is also a "case" control construct that checks for equality with a list of items. It can be used with the example at the beginning of this section:

   case "$1" 
   in
     "gorilla")  echo "Sorry, gorillas not allowed."
                 exit;;
     "hyena")    echo "Hyenas not welcome."
                 exit;;
     *)          echo "Welcome to Bongo Congo.";;
   esac

The string ";;" is used to terminate each "case" clause.
* The fundamental loop construct in the shell is based on the "for" command. For example:

   for nvar in 1 2 3 4 5
   do
     echo $nvar
   done

-- echoes the numbers 1 through 5. The names of all the files in the current directory could be displayed with:

   for file in *
   do
     echo $file
   done

One nice little feature of the shell is that if the "in" parameters are not specified for the "for" command, it just cycles through the command-line arguments.
* There is a "break" command to exit a loop if necessary:

   for file
   do
     if [ "$file" = punchout ]
     then 
       break
     else
       echo $file
     fi
   done

There is also a "continue" command that starts the next iteration of the loop immediately. There must be a command in the "then" or "else" clauses, or the result is an error message. If it's not convenient to actually do anything in the "then" clause, a ":" can be used as a "no-op" command:

   then
     :
   else

* There are two other looping constructs available as well, "while" and "until". For an example of "while":

   n=10
   while [ "$n" -ne 0 ]
   do
     echo $n
     n=`expr $n - 1`
   done

-- counts down from 10 to 1. The "until" loop has similar syntax but tests for a false condition:

   n=10
   until [ "$n" -eq 0 ]
   do
   ...

Shell Programming:COMMAND-LINE ARGUMENTS

COMMAND-LINE ARGUMENTS:

* In general, shell programs operate in a "batch" mode, that is, without interaction from the user, and so most of their parameters are obtained on the command line. Each argument on the command line can be seen inside the shell program as a shell variable of the form "$1", "$2", "$3", and so on, with "$1" corresponding to the first argument, "$2" the second, "$3" the third, and so on.
There is also a "special" argument variable, "$0", that gives the name of the shell program itself. Other special variables include "$#", which gives the number of arguments supplied, and "$*", which gives a string with all the arguments supplied.
Since the argument variables are in the range "$1" to "$9", so what happens there's more than 9 arguments? No problem, the "shift" command can be used to move the arguments down through the argument list. That is, when "shift" is executed, then the second argument becomes "$1", the third argument becomes "$2", and so on; and if a "shift" is performed again, the third argument becomes "$1"; and so on. A count can be specified to cause a multiple shift:

   shift 3

-- shifts the arguments three times, so that the fourth argument ends up in "$1".

Shell Programming:COMMAND SUBSTITUTION


COMMAND SUBSTITUTION:

* The next step is to consider shell command substitution. Like any programming language, the shell does exactly what it is told to do, and so it is important to be very specific when telling it to do something. As an example, consider the "fgrep" command, which searches a file for a string. For example, to search a file named "source.txt" for the string "Coyote", enter:
   fgrep Coyote source.txt
-- and it would print out the matching lines. However, suppose we wanted to search for "Wile E. Coyote". If we did this as:
   fgrep Wile E. Coyote source.txt
-- we'd get an error message that "fgrep" couldn't open "E.". The string has to be enclosed in double-quotes (""):
   fgrep "Wile E. Coyote" source.txt
If a string has a special character in it, such as "*" or "?", that must be interpreted as a "literal" and not a wildcard, the shell can get a little confused. To ensure that the wildcards are not interpreted, the wildcard can either be "escaped" with a backslash ("\*" or "\?") or the string can be enclosed in single quotes, which prevents the shell from interpreting any of the characters within the string. For example, if:
   echo "$shvar"
-- is executed from a shell program, it would output the value of the shell variable "$shvar". In contrast, executing:
   echo '$shvar'
-- the output is the string "$shvar".
* Having considered "double-quoting" and "single-quoting", let's now consider "back-quoting". This is a little tricky to explain. As a useful tool, consider the "expr" command, which can be used to perform simple math from the command line:
   expr 2 + 4
This displays the value "6". There must be spaces between the parameters; in addition, to perform a multiplication the "*" has to be "escaped" so the shell doesn't interpret it:
   expr 3 \* 7 
Now suppose the string "expr 12 / 3" has been stored in a shell variable named "shcmd"; then executing:
   echo $shcmd
-- or:
   echo "$shcmd"
-- would simply produce the text "expr 12 / 3". If single-quotes were used:
   echo '$shcmd'
-- the result would be the string "$shcmd". However, if back-quotes, the reverse form of a single quote, were used:
   echo `$shcmd`
-- the result would be the value "4", since the string inside "shcmd" is executed. This is an extremely powerful technique that can be very confusing to use in practice.

Shell Programming:SHELL VARIABLES

SHELL VARIABLES:

* The first useful command to know about in building shell programs is "echo", which can be used to produce output from a shell program:

   echo "This is a test!"

This sends the string "This is a test!" to standard output. It is recommended to write shell programs that generate some output to inform the user of what they are doing.
The shell allows variables to be defined to store values. It's simple, just declare a variable is assign a value to it:

   shvar="This is a test!"

The string is enclosed in double-quotes to ensure that the variable swallows the entire string (more on this later), and there are no spaces around the "=". The value of the shell variable can be obtained by preceding it with a "$":

   echo $shvar

This displays "This is a test!". If no value had been stored in that shell variable, the result would have simply been a blank line. Values stored in shell variables can be used as parameters to other programs as well:

   ls $lastdir

The value stored in a shell variable can be erased by assigning the "null string" to the variable:

   shvar=""

There are some subtleties in using shell variables. For example, suppose a shell program performed the assignment:

   allfiles=*

-- and then performed:

   echo $allfiles

This would echo a list of all the files in the directory. However, only the string "*" would be stored in "allfiles". The expansion of "*" only occurs when the "echo" command is executed.
Another subtlety is in modifying the values of shell variables. Suppose we have a file name in a shell variable named "myfile" and want to copy that file to another with the same name, but with "2" tacked on to the end. We might think to try:

   mv $myfile $myfile2

-- but the problem is that the shell will think that "myfile2" is a different shell variable, and this won't work. Fortunately, there is a way around this; the change can be made as follows:

   mv $myfile ${myfile}2

A UNIX installation will have some variables installed by default, most importantly $HOME, which gives the location of a particular user's home directory.
As a final comment on shell variables, if one shell program calls another and the two shell programs have the same variable names, the two sets of variables will be treated as entirely different variables. To call other shell programs from a shell program and have them use the same shell variables as the calling program requires use of the "export" command:

   shvar="This is a test!"
   export shvar
   echo "Calling program two."
   shpgm2
   echo "Done!"

If "shpgm2" simply contains:

   echo $shvar

-- then it will echo "This is a test!".

Shell Programming:GETTING STARTED

GETTING STARTED:

* The first thing to do in understanding shell programs is to understand the elementary system commands that can be used in them. A list of fundamental UNIX system commands follows:
  ls         # Give a simple listing of files.
  cp         # Copy files.
  mv         # Move or rename files.
  rm         # Remove files.  
  rm -r      # Remove entire directory subtree.
  cd         # Change directories.
  pwd        # Print working directory.
  cat        # Lists a file or files sequentially.
  more       # Displays a file a screenfull at a time.
  pg         # Variant on "more".
  mkdir      # Make a directory.
  rmdir      # Remove a directory.
The shell executes such commands when they are typed in from the command prompt with their appropriate parameters, which are normally options and file names.
* The shell also allows files to be defined in terms of "wildcard characters" that define a range of files. The "*" wildcard character substitutes for any string of characters, so:
   rm *.txt
-- deletes all files that end with ".txt". The "?" wildcard character substitutes for any single character, so:
   rm book?.txt
-- deletes "book1.txt", "book2.txt", and so on. More than one wildcard character can be used at a time, for example:
   rm *book?.txt
-- deletes "book1.txt", "mybook1.txt", "bigbook2.txt", and so on.
* Another shell capability is "input and output redirection". The shell, like other UNIX utilities, accepts input by default from what is called "standard input", and generates output by default to what is called "standard output". These are normally defined as the keyboard and display, respectively, or what is referred to as the "console" in UNIX terms. However, standard input or output can be "redirected" to a file or another program if needed. Consider the "sort" command. This command sorts a list of words into alphabetic order; typing in:
   sort
   PORKY
   ELMER
   FOGHORN
   DAFFY
   WILE
   BUGS
   <CTL-D>
-- spits back:
   BUGS
   DAFFY
   ELMER
   FOGHORN
   PORKY
   WILE
Note that the CTL-D key input terminates direct keyboard input. It is also possible to store the same words in a file and then "redirect" the contents of that file to standard input with the "<" operator:
   sort < names.txt
This would list the sorted names to the display as before. They can be redirected to a file with the ">" operator:
   sort < names.txt > output.txt
They can also be appended to an existing file using the ">>" operator:
   sort < names.txt >> output.txt
In these cases, there's no visible output, since the command just executes and ends. However, if that's a problem, it can be fixed by connecting the "tee" command to the output through a "pipe", designated by "|". This allows the standard output of one command to be chained into the standard input of another command. In the case of "tee", it accepts text into its standard input and then dumps it both to a file and to standard output:
   sort < names.txt | tee output.txt
So this both displays the names and puts them in the output file. Many commands can be chained together to "filter" information through several processing steps. This ability to combine the effects of commands is one of the beauties of shell programming. By the way, "sort" has some handy additional options:
   sort -u    # Eliminate redundant lines in output.
   sort -r    # Sort in reverse order.
   sort -n    # Sort numbers. 
   sort -k 2  # Skip first field in sorting.
* If a command generates an error, it is displayed to what is called "standard error", instead of standard output, which defaults to the console. It will not be redirected by ">". However, the operator "2>" can be used to redirect the error message. For example:
   ls xyzzy 2> /dev/null
-- will give an error message if the file "xyzzy" doesn't exist, but the error will be redirected to the file "/dev/null". This is actually a "special file" that exists under UNIX where everything sent to it is simply discarded.
* The shell permits the execution of multiple commands sequentially on one line by chaining them with a ";":
   rm *.txt ; ls
A time-consuming program can also be run in a "parallel" fashion by following it with a "&":
   sort < bigfile.txt > output.txt &
* These commands and operations are essential elements for creating shell programs. They can be stored in a file and then executed by the shell. To tell the shell that the file contains commands, just mark it as "executable" with the "chmod" command. Each file under UNIX has a set of "permission" bits, listed by an "ls -l" -- the option providing file details -- as:
   rwxrwxrwx
The "r" gives "read" permission, the "w" gives "write" permission, and the "x" gives "execute" permission. There are three sets of these permission bits, one for the user, one for other members of a local group of users on a system, and one for everyone who can access the system -- remember that UNIX was designed as a multiuser environment.
The "chmod" command can be used to set these permissions, with the permissions specified as an octal code. For example:
   chmod 644 myfile.txt
This sets both read and write permission on the file for the user, but everybody else on the system only gets read permission. The same octal scheme can be used to set execute permission, though it's simpler just to use chmod "+x" option:
   chmod +x mypgm
This done, if the name "mypgm" is entered at the prompt, the shell reads the commands out of "mypgm" and executes them. The execute permission can be removed with the "-x" option.
For example, suppose we want to be able to inspect the contents of a set of archive files stored in the directory "/users/group/archives". We could create a file named "ckarc" and store the following command string in it:
  ls /users/group/archives | pg
This is a very simple shell program. As noted, the shell has control constructs, supports storage variables, and has several options that can be set to allow much more sophisticated programs. The following sections describe these features in a quick outline fashion.

Shell Programming:Introduction

* The UNIX operating system provides a flexible set of simple tools to perform a wide variety of system-management, text-processing, and general-purpose tasks. These simple tools can be used in very powerful ways by tying them together programmatically, using "shell scripts" or "shell programs".
The UNIX "shell" itself is a user-interface program that accepts commands from the user and executes them. It can also accept the same commands written as a list in a file, along with various other statements that the shell can interpret to provide input, output, decision-making, looping, variable storage, option specification, and so on. This file is a shell program.
Shell programs are, like any other programming language, useful for some things but not for others. They are excellent for system-management tasks but not for general-purpose programming of any sophistication. Shell programs, though generally simple to write, are also tricky to debug and slow in operation.
There are three versions of the UNIX shell: the original "Bourne shell (sh)", the "C shell (csh)" that was derived from it, and the "Korn shell (ksh)" that is in predominant use. The Bourne shell is in popular use as the freeware "Bourne-again shell" AKA "bash".

Visuel Basic:Loop

Do...Loop:

Used to execute a block of statements an unspecified number of times.

Do While condition
     statements
Loop

First, the condition is tested; if condition is True, then the statements are executed. When it gets to the Loop it goes back to the Do and tests condition again. If condition is False on the first pass, the statements are never executed.




For...Next:

When the number of iterations of the loop is known, it is better to use the For...Next rather than the Do...Loop.

For counter = start To end
     statements
Next

1) The counter is set to the value of start.
2) Counter is checked to see if it is greater than end; if yes, control passes to the statement after the Next; if not the statements are executed.
3)At Next, counter is incremented and goes back to step 2).

Visuel Basic:Control Structures


Control Structures:

If...Then...Else:

If condition1 Then
     statements1
Else
     statements2
End If

If condition1 is True, then statements1 block is executed; Else, condition1 is not True, therefore statements2 block gets executed. The structure must be terminated with the End If statement.

The Else clause is optional. In a simple comparison, statements1 get executed or not.

If condition1 Then
     statements1
End If


Select Case:

Can be used as an alternative to the If...Then...Else structure, especially when many comparisons are involved.

Select Case ShirtSize
     Case 1
          SizeName.Caption = "Small"
     Case 2
          SizeName.Caption = "Medium"
     Case 3
          SizeName.Caption = "Large"
     Case 4
          SizeName.Caption = "Extra Large"
     Case Else
          SizeName.Caption = "Unknown size"
End Select

Visuel Basic :Operators

Operators:

Mathematical and Text operators

OperatorDefinition Example Result 
Exponent (power of) 4 ^ 2 16 
Multiply 5 * 4 20 
Divide 20 / 4 
Add 3 + 4 
Subtract 7 - 3 
Mod Remainder of division 20 Mod 6 
Integer division 20 \ 6 
String concatenation "Joan" & " " & "Smith" "Joan Smith" 


Note that the order of operators is determined by the usual rules in programming. When a statement includes multiple operations the order of operations is:
Parentheses ( ), ^, *, /, \, Mod, +, -

Logical operators

Operator Definition Example Result 
Equal to 9 = 11 False 
Greater than 11 > 9 True 
Less than 11 < 9 False 
>= Greater or equal 15 >= 15 True 
<= Less or equal 9 <= 15 True 
<> Not equal 9 <> 9 False 
AND Logical AND (9 = 9) AND (7 = 6) False 
OR Logical OR (9 = 9) OR (7 = 6) True

LESSON 2 - Writing code

Writing code:

Naming conventions:

These are the rules to follow when naming elements in VB - variables, constants, controls, procedures, and so on:
  • A name must begin with a letter.
  • May be as much as 255 characters long (but don't forget that somedy has to type the stuff!).
  • Must not contain a space or an embedded period or type-declaration characters used to specify a data type ; these are ! # % $ & @
  • Must not be a reserved word (that is part of the code, like Option, for example).
  • The dash, although legal, should be avoided because it may be confused with the minus sign. Instead of Family-name use Family_name or FamilyName.

Data types:

Data typeStorage sizeRange
Byte1 byte0 to 255
Boolean2 bytesTrue or False
Integer2 bytes-32,768 to 32,767
Long (long integer)4 bytes-2,147,483,648 to 2,147,483,647
Single (single-precision floating-point)4 bytes-3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values
Double (double-precision floating-point)8 bytes-1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values
Currency (scaled integer)8 bytes-922,337,203,685,477.5808 to 922,337,203,685,477.5807
Decimal14 bytes+/-79,228,162,514,264,337,593,543,950,335 with no decimal point; +/-7.9228162514264337593543950335 with 28 places to the right of the decimal; smallest non-zero number is +/-0.0000000000000000000000000001
Date8 bytesJanuary 1, 100 to December 31, 9999
Object4 bytesAny Object reference
String (variable-length)10 bytes + string length0 to approximately 2 billion
String (fixed-length)Length of string1 to approximately 65,400
Variant (with numbers)16 bytesAny numeric value up to the range of a Double
Variant (with characters)22 bytes + string lengthSame range as for variable-length String
User-defined (using Type)Number required by elementsThe range of each element is the same as the range of its data type.


In all probability, in 90% of your applications you will use at most six types: String, Integer, Long, Single, Boolean and Date. The Variant type is often used automatically when type is not important. A Variant-type field can contain text or numbers, depending on the data that is actually entered. It is flexible but it is not very efficient in terms of storage.


Declaring variables:

Declaring a variable means giving it a name, a data type and sometimes an initial value. The declaration can be explicit or implicit.

An explicit declaration: variable is declared in the Declarations Section or at the beginning of a Procedure. An explicit declaration looks like:
Dim MyNumber As Integer

Now the variable MyNumber exists and a 2-byte space has been reserved for it.

An implicit declaration: the variable is declared "on the fly", its data type is deduced from other variables. For example:
Dim Total1 As Integer      'Explicit declaration
Dim Total2 As Integer      'Explicit declaration
Total3 = Total1 + Total2      'Implicit declaration
Total3 is not formally declared but is implied, it is "arrived at" from the other declarations. 

It is never a good idea to have implicit declarations. It goes against the rules for clarity, readability and ease of use of the code.
To make sure that this rule is followed, start the Declarations with the Option Explicit clause. This tells the compiler to consider implicit declarations as errors and forces the programmer to declare everything explicitly.

Other examples of declarations:
Dim MyName As String
Dim StudentDOB As Date
Dim Amount5, Amount6, Amount7

In the last example the type assigned to each variable will be: Variant. It is the default type when none is specified.

There can be multiple explicit declarations in a statement:
Dim EmpName As String, SalaryMonth As Currency, SalaryYear As Currency

In this final example, what are the types assigned to the three variables:
Dim Amount1, Amount2, Amount3 As Single

All Single-precision floating point, you say. Wrong! Only Amount3 is Single. Amount1 and Amount2 are considered Variant because VB specifies that each variable in a statement must be explicitly declared. Thus Amount1 and Amount2 take the default data type. This is different from what most other languages do.

Constants:

A constant is a value that doe:s not change during the execution of a procedure. The constant is defined with:
Const ValuePi = 3.1416


The Scope of variables

The term Scope refers to whether the variable is available outside the procedure in which it appears. The scope is procedure-level ormodule-level.

A variable declared with Dim at the beginning of a procedure is only available in that procedure. When the procedure ends, the variable disappears. Consider the following example:
          Option Explicit
                    Dim Total2 As Integer

          Private Sub Command1_Click ()
                    Dim Total1 As Integer
                    Static Total3 As Integer
                    Total1 = Total1 + 1
                    Total2 = Total2 + 1
                    Total3 = Total3 + 1
          End Sub

          Private Sub Command2_Click ()
                    Dim Total1 As Integer
                    Total1 = Total1 + 1
                    Total2 = Total2 + 1
                    Total3 = Total3 + 1
          End Sub

Every time Button1 is clicked, Total1 is declared as a new variable during the execution of that clicked event. It is a procedure-level variable. It will always stay at 1. The same for the Button2 event: Total1 is a new variable in that procedure. When the procedure ends, Total1 disappears.
Total2 is declared in the Declarations section. It is a module-level variable, meaning it is available to every control in this Form. When Button1 is clicked, it increments by 1 and it retains that value. When Button2 is clicked, Total2 is incremented from its previous value, even if it came from the Button1 event. 
Total3 shows another way of retaining the value of a local variable. By declaring it with Static instead of Dim, the variable acts like a module-level variable, although it is declared in a procedure.

Another scope indicator that you will see when you study examples of code is Private and Public. This determines whether a procedure is available only in this Form (module) or if it is available to any module in the application. For now, we will work only with Private procedures.


The Visual Basic Programming Language


History:

Microsoft released Visual Basic in 1987. It was the first visual development tool from Microsoft, and it was to compete with C, C++, Pascal and other well-known programming languages. From the start, Visual Basic wasn't a hit. It wasn't until release 2.0 in 1991 that people really discovered the potential of the language, and with release 3.0 it had become the fastest-growing programming language on the market.

What Is Visual Basic?

Programmers have undergone a major change in many years of programming various machines. For example what could be created in minutes with Visual Basic could take days in other languages such: as "C" or "Pascal". Visual Basic provides many interesting sets of tools to aid you in building exciting applications. Visual Basic provides these tools to make your life far more easier because all the real hard code is already written for you.
With controls like these you can create many applications which use certain parts of windows. For example, one of the controls could be a button, which we have demonstrated in the "Hello World" program below. First create the control on the screen, then write the code which would be executed once the control button is pressed. With this sort of operation in mind, simple programs would take very little code. Why do it like the poor old "C" programmer who would have to write code to even display a window on the screen, when Visual Basic already has this part written for you.
Even though people tend to say Visual Basic's compiler is far behind the compilers of Pascal and C, it has earned itself the status of a professional programming language, and has almost freed BASIC of the reputation of a children's language. Overall you would class Visual Basic as a Graphics User Interface(GUI). Because as you draw, you write for the program. This must always be remembered in any kind of creation of a Visual Basic program. All in all, VB is the preferred language of many future program mers. If you want to start programming Windows, and don't know how to start, give Visual Basic a shot.

Significant Language Features

Visual Basic is not only a programming language, but also a complete graphical development environment. This environment allows users with little programming experience to quickly develop useful Microsoft Windows applications which have the ability to use OLE ( Object Linking and Embedding ) objects, such as an Excel spreadsheet. Visual Basic also has the ability to develop programs that can be used as a front end application to a database system, serving as the user interface which collects user input and displays formatted output in a more appealing and useful form than many SQL versions are capable of.
Visual Basic's main selling point is the ease with which it allows the user to create nice looking, graphical programs with little coding by the programmer, unlike many other languages that may take hundreds of lines of programmer keyed code. As the programmer works in the graphical environment, much of the program code is automatically generated by the Visual Basic program. In order to understand how this happens it is necessary to understand the major concepts, objects and tools used by Visual Basic. The main object in Visual Basic is called a form. When you open a new project, you will start with a clear form that looks similar to this :


This form will eventually be incorporated into your program as a window. To this form you add controls. Controls are things like text boxes, check boxes and command buttons. Controls are added to your form by choosing them from the Visual Basic "tool box" with the mouse and inserting them in the form. Yours may look different, but the basic Visual Basic Tool Box looks like this :


Once forms/controls are created, you can change the properties ( appearance, structure etc. ) related to those objects in that particular objects properties window. From this window, you choose the property you want to change from the list and change its corresponding setting. Here is an example of a properties window :

Finally, you can add events to your controls. Events are responses to actions performed on controls. For example, in the "Hello world" program sample on this page, when you click on the command button on our form the event that is triggered is the output of the message "Hello world" to the screen. Code must be written to create an event. You can do this in Visual Basic's code window. Yours will look similar to this ( except of course, the body of the sub-procedure where the actions are specified) :

Areas of Application:

The term "Personal Programming" refers to the idea that, wherever you work, whatever you do, you can expand your computer's usefulness by writing applications to use in your own job. Personal Programming is what Visual Basic is all about.
Using Visual Basic's tools, you quickly translate an abstract idea into a program design you can actually see on the screen. VB encourages you to experiment, revise, correct, and network your design until the new project meets your requirements. However , most of all, it inspires your imagination and creativity.
Visual Basic is ideal for developing applications that run in the new Windows 95 operating system. VB presents a 3-step approach for creating programs:
  1. Design the appearance of your application.
  2. Assign property settings to the objects of your program.
  3. Write the code to direct specific tasks at runtime.

Visual Basic can and is used in a number of different areas, for example:
  • Eucation
  • Research
  • Medecine
  • Business
  • Commerce
  • Marketing and Sales
  • Accounting
  • Consulting
  • Law
  • Science

Sample Programs:

Hello World! Example Program:

Description

This program demonstrates the text output and button control functions of the Visual Basic programming language. By clicking on the button "Hello World", the message "Hello world" is displayed in the upper left hand corner.

Source Code

Visual Basic


VERSION 4.00
Begin VB.Form Form1 
   Caption         =   "Hello"
   ClientHeight    =   6030
   ClientLeft      =   1095
   ClientTop       =   1515
   ClientWidth     =   6720
   Height          =   6435
   Left            =   1035
   LinkTopic       =   "Form1"
   ScaleHeight     =   6030
   ScaleWidth      =   6720
   Top             =   1170
   Width           =   6840
   Begin VB.CommandButton Command1 
      Caption         =   "Hello World"
      Height          =   975
      Left            =   2040
      TabIndex        =   0
      Top             =   2280
      Width           =   2535
   End
End
Attribute VB_Name = "Form1"
Attribute VB_Creatable = False
Attribute VB_Exposed = False
Private Sub Command1_Click()
Cls
Print "Hello World"
End Sub

  • Sample Run




Loops

Loops

C gives you a choice of three types of loop, while, do while and for.
  • The while loop keeps repeating an action until an associated test returns false. This is useful where the programmer does not know in advance how many times the loop will be traversed.
  • The do while loops is similar, but the test occurs after the loop body is executed. This ensures that the loop body is run at least once.
  • The for loop is frequently used, usually where the loop will be traversed a fixed number of times. It is very flexible, and novice programmers should take care not to abuse the power it offers.
  • The while Loop

    The while loop repeats a statement until the test at the top proves false.
    As an example, here is a function to return the length of a string.  Remember that the string is represented as an array of characters terminated by a null character '\0'.

    
    int string_length(char string[])
    {       int i = 0;
    
            while (string[i] != '\0')
                    i++;
    
            return(i);
    }
    The string is passed to the function as an argument. The size of the array is not specified, the function will work for a string of any size.The while loop is used to look at the characters in the string one at a time until the null character is found. Then the loop is exited and the index of the null is returned. While the character isn't null, the index is incremented and the test is repeated.

    The do while Loop:

    This is very similar to the while loop except that the test occurs at the end of the loop body. This guarantees that the loop is executed at least once before continuing. Such a setup is frequently used where data is to be read. The test then verifies the data, and loops back to read again if it was unacceptable.
    
    do
    {       printf("Enter 1 for yes, 0 for no :");
            scanf("%d", &input_value);
    } while (input_value != 1 && input_value != 0)

    The for Loop:

    The for loop works well where the number of iterations of the loop is known before the loop is entered. The head of the loop consists of three parts separated by semicolons.
    • The first is run before the loop is entered. This is usually the initialisation of the loop variable.
    • The second is a test, the loop is exited when this returns false.
    • The third is a statement to be run every time the loop body is completed. This is usually an increment of the loop counter.
    The example is a function which calculates the average of the numbers stored in an array. The function takes the array and the number of elements as arguments.
    
    float average(float array[], int count)
    {       float total = 0.0;
            int i;
    
            for(i = 0; i < count; i++)
                    total += array[i];
    
            return(total / count);
    }
    The for loop ensures that the correct number of array elements are added up before calculating the average.
    The three statements at the head of a for loop usually do just one thing each, however any of them can be left blank. A blank first or last statement will mean no initialisation or running increment. A blank comparison statement will always be treated as true. This will cause the loop to run indefinitely unless interrupted by some other means. This might be a return or a break statement.
    It is also possible to squeeze several statements into the first or third position, separating them with commas. This allows a loop with more than one controlling variable. The example below illustrates the definition of such a loop, with variables hi and lo starting at 100 and 0 respectively and converging.
    
    for (hi = 100, lo = 0; hi >= lo; hi--, lo++)
    The for loop is extremely flexible and allows many types of program behaviour to be specified simply and quickly.


Control Statements

A program consists of a number of statements which are usually executed in sequence. Programs can be much more powerful if we can control the order in which statements are run.
Statements fall into three general types;
  • Assignment, where values, usually the results of calculations, are stored in variables.
  • Input / Output, data is read in or printed out.
  • Control, the program makes a decision about what to do next.
This section will discuss the use of control statements in C. We will show how they can be used to write powerful programs by;
  • Repeating important sections of the program.
  • Selecting between optional sections of a program.
  • The if else Statement:

    This is used to decide whether to do something at a special point, or to decide between two courses of action.
    The following test decides whether a student has passed an exam with a pass mark of 45
    
    if (result >= 45)
            printf("Pass\n");
    else
            printf("Fail\n");
    It is possible to use the if part without the else.
    
    if (temperature < 0)
            print("Frozen\n");
    Each version consists of a test, (this is the bracketed statement following the if). If the test is true then the next statement is obeyed. If is is false then the statement following the else is obeyed if present. After this, the rest of the program continues as normal.If we wish to have more than one statement following the if or the else, they should be grouped together between curly brackets. Such a grouping is called a compound statement or a block.
    
    if (result >= 45)
    {       printf("Passed\n");
            printf("Congratulations\n")
    }
    else
    {       printf("Failed\n");
            printf("Good luck in the resits\n");
    }
    Sometimes we wish to make a multi-way decision based on several conditions. The most general way of doing this is by using the else if variant on the if statement. This works by cascading several comparisons. As soon as one of these gives a true result, the following statement or block is executed, and no further comparisons are performed. In the following example we are awarding grades depending on the exam result.
    
    if (result >= 75)
            printf("Passed: Grade A\n");
    else if (result >= 60)
            printf("Passed: Grade B\n");
    else if (result >= 45)
            printf("Passed: Grade C\n");
    else
            printf("Failed\n");
    In this example, all comparisons test a single variable called 
    result. In other cases, each test may involve a different variable or some combination of tests. The same pattern can be used with more or fewer else if's, and the final lone else may be left out. It is up to the programmer to devise the correct structure for each programming problem.
  • The switch Statement

    This is another form of the multi way decision. It is well structured, but can only be used in certain cases where;
    • Only one variable is tested, all branches must depend on the value of that variable. The variable must be an integral type. (int, long, short or char).
    • Each possible value of the variable can control a single branch. A final, catch all, default branch may optionally be used to trap all unspecified cases.
    Hopefully an example will clarify things. This is a function which converts an integer into a vague description. It is useful where we are only concerned in measuring a quantity when it is quite small.
    
    estimate(number)
    int number;
    /* Estimate a number as none, one, two, several, many */
    {       switch(number) {
            case 0 :
                    printf("None\n");
                    break;
            case 1 :
                    printf("One\n");
                    break;
            case 2 :
                    printf("Two\n");
                    break;
            case 3 :
            case 4 :
            case 5 :
                    printf("Several\n");
                    break;
            default :
                    printf("Many\n");
                    break;
            }
    }
    Each interesting case is listed with a corresponding action. The break statement prevents any further statements from being executed by leaving the switch. Since case 3 and case 4 have no following break, they continue on allowing the same action for several values of number.Both if and switch constructs allow the programmer to make a selection from a number of possible actions.
    The other main type of control statement is the loop. Loops allow a statement, or block of statements, to be repeated. Computers are very good at repeating simple tasks many times, the loop is C's way of achieving this.

Expressions and Operators

Arithmetic operators

Here are the most common arithmetic operators


*, / and % will be performed before + or - in any expression. Brackets can be used to force a different order of evaluation to this. Where division is performed between two integers, the result will be an integer, with remainder discarded. Modulo reduction is only meaningful between integers. If a program is ever required to divide a number by zero, this will cause an error, usually causing the program to crash.
Here are some arithmetic expressions used within assignment statements.

velocity = distance / time;

force = mass * acceleration;

count = count + 1;
C has some operators which allow abbreviation of certain types of arithmetic assignment statements.

These operations are usually very efficient. They can be combined with another expression.


Versions where the operator occurs before the variable name change the value of the variable before evaluating the expression, so


These can cause confusion if you try to do too many things on one command line. You are recommended to restrict your use of ++ and -- to ensure that your programs stay readable.
Another shorthand notation is listed below


These are simple to read and use.

Comparison

C has no special type to represent logical or boolean values. It improvises by using any of the integral types char, int, short, long, unsigned, with a value of 0 representing false and any other value representing true. It is rare for logical values to be stored in variables. They are usually generated as required by comparing two numeric values. This is where the comparison operators are used, they compare two numeric values and produce a logical result.



Note that == is used in comparisons and = is used in assignments. Comparison operators are used in expressions like the ones below.

x == y

i > 10

a + b != c
In the last example, all arithmetic is done before any comparison is made.These comparisons are most frequently used to control an if statement or a for or a while loop. These will be introduced in a later chapter.

Constant and Variable Types

In C, a variable must be declared before it can be used. Variables can be declared at the start of any block of code, but most are found at the start of each function. Most local variables are created when the function is called, and are destroyed on return from that function.
A declaration begins with the type, followed by the name of one or more variables. For example,

int high, low, results[20];
Declarations can be spread out, allowing space for





 an explanatory comment. Variables can also be initialised when they are declared, this is done by adding an equals sign and the required value after the declaration.

int high = 250;     /* Maximum Temperature */
int low = -40;      /* Minimum Temperature */
int results[20];    /* Series of temperature readings */
C provides a wide range of types. The most common are

There are also several variants on these types.


All of the integer types plus the char are called the integral types. float and double are called the real types.

Constants

A C constant is usually just the written version of a number. For example 1, 0, 5.73, 12.5e9. We can specify our constants in octal or hexadecimal, or force them to be treated as long integers.
  • Octal constants are written with a leading zero - 015.
  • Hexadecimal constants are written with a leading 0x - 0x1ae.
  • Long constants are written with a trailing L - 890L.
Character constants are usually just the character enclosed in single quotes; 'a', 'b', 'c'. Some characters can't be represented in this way, so we use a 2 character sequence.

In addition, a required bit pattern can be specified using its octal equivalent.
'\044' produces bit pattern 00100100.
Character constants are rarely used, since string constants are more convenient. A string constant is surrounded by double quotes eg "Brian and Dennis". The string is actually stored as an array of characters. The null character '\0' is automatically placed at the end of such a string to act as a string terminator.
A character is a different type to a single character string. This is important

A Quick Overview of C

It is usual to start programming courses with a simple example program. This course is no exception.:

A Very Simple Program

This program which will print out the message This is a C program


#include <stdio.h>

main()
{
        printf("This is a C program\n");
}
Though the program is very simple, a few points are worthy of note.
Every C program contains a function called main. This is the start point of the program.
#include <stdio.h> allows the program to interact with the screen, keyboard and filesystem of your computer. You will find it at the beginning of almost every C program.
main() declares the start of the function, while the two curly brackets show the start and finish of the function. Curly brackets in C are used to group statements together as in a function, or in the body of a loop. Such a grouping is known as a compound statement or a block.
printf("This is a C program\n");
prints the words on the screen. The text to be printed is enclosed in double quotes. The \n at the end of the text tells the program to print a newline as part of the output.
Most C programs are in lower case letters. You will usually find upper case letters used in preprocessor definitions (which will be discussed later) or inside quotes as parts of character strings. C is case sensitive, that is, it recognises a lower case letter and it's upper case equivalent as being different.
While useful for teaching, such a simple program has few practical uses. Let us consider something rather more practical. The following program will print a conversion table for weight in pounds (U.S.A. Measurement) to pounds and stones (Imperial Measurement) or Kilograms (International).

About C

About C

As a programming language, C is rather like Pascal or Fortran. Values are stored in variables. Programs are structured by defining and calling functions. Program flow is controlled using loops, if statements and function calls. Input and output can be directed to the terminal or to files. Related data can be stored together in arrays or structures.
Of the three languages, C allows the most precise control of input and output. C is also rather more terse than Fortran or Pascal. This can result in short efficient programs, where the programmer has made wise use of C's range of powerful operators. It also allows the programmer to produce programs which are impossible to understand.
Programmers who are familiar with the use of pointers (or indirect addressing, to use the correct term) will welcome the ease of use compared with some other languages. Undisciplined use of pointers can lead to errors which are very hard to trace. This course only deals with the simplest applications of pointers.
It is hoped that newcomers will find C a useful and friendly language. Care must be taken in using C. Many of the extra facilities which it offers can lead to extra types of programming error. You will have to learn to deal with these to successfully make the transition to being a C programmer.

Tuesday, January 8, 2013

The C Programming Language

This animation shows the execution of a simple C program.
The C programming language is a popular and widely used programming language for creating computer programs. Programmers around the world embrace C because it gives maximum control and efficiency to the programmer.



History:

C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were taken from the earlier language B and B's earlier ancestors BCPL and CPL. CPL ( Combined Programming Language ) was developed with the purpose of creating a language that was capable of both high level, machine independent programming and would still allow the programmer to control the behavior of individual bits of information. The one major drawback of CPL was that it was too large for use in many applications. In 1967, BCPL ( Basic CPL ) was created a
s a scaled down version of CPL while still retaining its basic features. In 1970, Ken Thompson, while working at Bell Labs, took this process further by developing the B language. B was a scaled down version of BCPL written specifically for use in systems programming. Finally in 1972, a co-worker of Ken Thompson, Dennis Ritchie, returned some of the generality found in BCPL to the B language in the process of developing the language we now know as C.C's power and flexibility soon became apparent. Because of this, the Unix operating system which was originally written in assembly language, was almost immediately re-written in C ( only the assembly language code needed to "bootstrap" the C code was kept ). During the rest of the 1970's, C spread throughout many colleges and universities because of it's close ties to Unix and the availability of C compilers. Soon, many different organizations began using their own versions of C causing compatibility problems. In response to this in 1983, the American National Standards Institute ( ANSI ) formed a committee to establish a standard definition of C which became known as ANSI Standard C. Today C is in widespread use with a rich standard library of functions.



Significant Language Features

C is a powerful, flexible language that provides fast program execution and imposes few constraints on the programmer. It allows low level access to information and commands while still retaining the portability and syntax of a high level language. These qualities make it a useful language for both systems programming and general purpose programs.C's power and fast program execution come from it's ability to access low level commands, similar to assembly language, but with high level syntax. It's flexibility comes from the many ways the programmer has to accomplish the same tasks. C includes bitwise operators along with powerful pointer manipulation capabilities. C imposes few constraints on the programmer. The main area this shows up is in C's lack of type checking. This can be a powerful advantage to an experienced programmer but a dangerous disadvantage to a novice.
Another strong point of C is it's use of modularity. Sections of code can be stored in libraries for re-use in future programs. This concept of modularity also helps with C's portability and execution speed. The core C language leaves out many features included in the core of other languages. These functions are instead stored in the C Standard Library where they can be called on when needed.. An example of this concept would be C's lack of built in I/O capabilities. I/O functions tend to slow down program execution and also be machine independent when running optimally. For these reasons, they are stored in a library separately from the C language and only included when necessary.


Areas of Application

The C programming language is used in many different areas of application, but the most prolific area is UNIX operating system applications. The C language is also used in computer games:
  • UNIX operating system
  • computer games
  • Sample Programs:

    Hello world! Example Program

    /* Hello World program */
    
    #include<stdio.h>
    
    main()
    {
        printf("Hello World");
    
    
    }
    
    
    


Powered by Blogger.