Wednesday, 12 June 2013

Types of Programming Languages

As might be expected in a dynamic and evolving field, there is no single standard for classifying programming languages. In fact, dozens of categories exist. One of the most fundamental ways programming languages are characterized is by programming


paradigm. A programming paradigm provides the programmer’s view of code execution. The most influential paradigms are examined in the next three sections, in approximate chronological order. Each of these paradigms represents a mature worldview, with enormous amounts of research and effort expended in their development.

A given language is not limited to use of a single paradigm. Java, for example, supports elements of both procedural and object-oriented programming, and it can be used in a concurrent, event-driven way. Programming paradigms continue to grow and evolve, as new generations of hardware and software present new opportunities and challenges for software developers.

Procedural Programming Languages

Procedural programming specifies a list of operations that the program must complete to reach the desired state. This one of the simpler programming paradigms, where a program is represented much like a cookbook recipe. Each program has a starting state, a list of operations to complete, and an ending point. This approach is also known as imperative programming. Integral to the idea of procedural programming is the concept of a procedure call.

Procedures, also known as functions, subroutines, or methods, are small sections of code that perform a particular function. A procedure is effectively a list of computations to be carried out. Procedural programming can be compared to unstructured programming, where all of the code resides in a single large block. By splitting the programmatic tasks into small pieces, procedural programming allows a section of code to be re-used in the program without making multiple copies. It also makes it easier for programmers to understand and maintain program structure.

Two of the most popular procedural programming languages are FORTRAN and BASIC.

Structured Programming Languages

Structured programming is a special type of procedural programming. It provides additional tools to manage the problems that larger programs were creating. Structured programming requires that programmers break program structure into small pieces of code that are easily understood. It also frowns upon the use of global variables and instead uses variables local to each subroutine. One of the well known features of structural programming is that it does not allow the use of the GOTO statement. It is often associated with a “top-down” approach to design. The top-down approach begins with an initial overview of the system that contains minimal details about the different parts. Subsequent design iterations then add increasing detail to the components until the design is complete.

The most popular structured programming languages include C, Ada, and Pascal.

Object-Oriented Programming Languages

Object-oriented programming is one the newest and most powerful paradigms. In object-oriented programs, the designer specifies both the data structures and the types of operations that can be applied to those data structures. This pairing of a piece of data with the operations that can be performed on it is known as an object. A program thus


becomes a collection of cooperating objects, rather than a list of instructions. Objects can store state information and interact with other objects, but generally each object has a distinct, limited role.

There are several key concepts in object-oriented programming (OOP) . A class is a template or prototype from which objects are created, so it describes a collection of variables and methods (which is what functions are called in OOP). These methods can be accessible to all other classes (public methods) or can have restricted access (private methods). New classes can be derived from a parent class. These derived classes inherit the attributes and behavior of the parent (inheritance), but they can also be extended with new data structures and methods.

The list of available methods of an object represents all the possible interactions it can have with external objects, which means that it is a concise specification of what the object does. This makes OOP a flexible system, because an object can be modified or extended with no changes to its external interface. New classes can be added to a system that uses the interfaces of the existing classes.

Objects typically communicate with each other by message passing. A message can send data to an object or request that it invoke a method. The objects can both send and receive messages.

Another key characteristic of OOP is encapsulation, which refers to how the implementation details of a particular class are hidden from all objects outside of the class. Programmers specify what information in an object can be shared with other objects.

A final attribute of object oriented programming languages is polymorphism. Polymorphism means that objects of different types can receive the same message and respond in different ways. The different objects need to have only the same interface (that is, method definition). The calling object (the client) does not need to know exactly what type of object it is calling, only that is has a method of a specific name with defined arguments. Polymorphism is often applied to derived classes, which replace the methods of the parent class with different behaviors. Polymorphism and inheritance together make OOP flexible and easy to extend.

Object-oriented programming proponents claim several large advantages. They maintain that OOP emphasizes modular code that is simple to develop and maintain. OOP is popular in larger software projects, because objects or groups of objects can be divided among teams and developed in parallel. It encourages careful up-front design, which facilitates a disciplined development process. Object-oriented programming seems to provide a more manageable foundation for larger software projects.

The most popular object-oriented programming languages include Java, Visual Basic, C#, C++, and Python.

Other Paradigms



Concurrent programming provides for multiple computations running at once. This often means support for multiple threads of program execution. For example, one thread might


monitor the mouse and keyboard for user input, although another thread performs database accesses. Popular concurrent languages include Ada and Java.

Functional programming languages define subroutines and programs as mathematical functions. These languages are most frequently used in various types of mathematical problem solving. Popular functional languages include LISP and Mathematica.

Event-driven programming is a paradigm where the program flow is determined by user actions. This is in contrast to batch programming, where flow is determined when the program is written. Event-driven programming is used for interactive programs, such as word processors and spreadsheets. The program usually has an event loop, which repeatedly checks for interesting events, such as a keypress or mouse movement. Events cause the execution of trigger functions, which process the events.

Two final paradigms to discuss are compiled languages and interpreted languages. Compiled languages use a program called a compiler to translate source code into machine instructions, usually saved to a separate executable file. Interpreted languages, in contrast, are programs that can be executed from directly from source code by a special program called an interpreter. This distinction refers to the implementation, rather than the language design itself. Most software is compiled, and in theory, any language can be compiled. LISP a well known interpreted language. Some popular implementations, such as Java and C#, use just-in-time compilation. Source programs are compiled into bytecode, which is an executable for an abstract virtual machine. At run time, the bytecode is compiled into native machine code.

Summary

Programming languages are artificial languages designed to control computers and many man hours have been spent to develop new and improved languages. There are thousands of different programming languages, but most conform to a few basic paradigms.


Procedural programming languages divide a program’s source code into smaller modules. Structured programming languages impose more constraints on program organization and flow, including a ban on GOTO statements. Object-oriented programs organize data structures and code into objects, so that a program becomes a group of cooperating objects. Key features of the object- oriented paradigm are classes, inheritance, data encapsulation, and polymorphism.

Tuesday, 11 June 2013

Generations of Programming Languages

Programming languages have been classified into several programming language generations. Historically, this classification was used to indicate increasing power of programming styles. Later writers have somewhat redefined the meanings as distinctions previously seen as important became less significant to current practice.

First genaration

A first-generation programming language is a machine-level programming language.
Originally, no translator was used to compile or assemble the first-generation language. The first-generation programming instructions were entered through the front panel switches of the computer system.
A first generation (programming) language (1GL) is a grouping of programming languages that are machine level languages used to program first-generation computers. The instructions were given through the front panel switches of these computers, directly to the CPU. There was originally no compiler or assembler to process the instructions in 1GL.
The instructions in 1GL are made of binary numbers, represented by 1s and 0s. This makes the language suitable for the understanding of the machine but very much more difficult to interpret and learn by the human programmer.
Also known as a 1st generation language.
The main advantage of programming in 1GL is that the code can run very fast and very efficiently, precisely because the instructions are executed directly by the CPU. One of the main disadvantages of programming in a low level language is that when an error occurs, the code is not as easy to fix.
The program is written as binary instructions, consisting of zeros and ones. This language is very much adapted to a specific computer and CPU, and code portability is therefore significantly reduced in comparison to higher level languages.
Modern day programmers still occasionally use machine level code, especially when programming lower level functions of the system, such as drivers, interfaces with firmware and hardware devices. Modern tools, such as native-code compilers are used to produce machine level from a higher-level language.

Second generation

Second-generation programming languages, originally just called low level programming languages, were created to simplify the burden of programming by making its expression more like the normal mode of expression for thoughts used by the programmer. They were introduced in the late 1950s, with FORTAN reflecting the needs of scientific programmers, ALGOL reflecting an attempt to produce a European/American standard view.
The most important issue faced by the developers of second-level languages was convincing customers that the code produced by the compilers performed well-enough to justify abandonment of assembly programming. In view of the widespread skepticism about the possibility of producing efficient programs with an automatic programming system and the fact that inefficiencies could no longer be hidden, the developers were convinced that the kind of system they had in mind would be widely used only if they could demonstrate that it would produce programs almost as efficient as hand coded ones and do so on virtually every job. The FORTRAN compiler was seen as a tour-de-force in the production of high-quality code, even including "… a Monte Carlo simulation of its execution … so as to minimize the transfers of items between the store and the index registers."

Third generation

The introduction of a third generation of computer technology coincided with the creation of a new generation of programming languages. The essential feature of third-generation languages is their hardware-independence, i.e. expression of an algorithm in a way that was independent of the characteristics of the machine on which the algorithm would run.
Some or all of a number of other developments that occurred at the same time were included in 3GLs.
Interpretation was introduced. Some 3GLs were compiled, a process analogous to the creation of a complete machine code executable from assembly code, the difference being that in higher-level languages there is no longer a one-to-one, or even linear, relationship between source code instructions and machine code instructions. Compilers are able to target different hardware by producing different translations of the same source code commands.
Interpreters, on the other hand, essentially execute the source code instructions themselves — if one encounters an "add" instruction, it performs an addition itself, rather than outputting an addition instruction to be executed later. Machine-independence is achieved by having different interpreters in the machine codes of the targeted platforms, i.e. the interpreter itself generally has to be compiled. Interpretation was not a linear "advance", but an alternative model to compilation, which continues to exist alongside it, and other, more recently developed, hybrids. Lisp is an early interpreted language.
The earliest 3GLs, such as Fortran and COBOL, were spaghetti coded, i.e. they had the same style of flow of control as assembler and machine code, making heavy use of the goto statement.Structured programming introduced a model where a program was seen as a hierarchy of nested blocks rather than a linear list of instructions. For instance, structured programmers were to conceive of a loop as a block of code that is repeated, rather than so many commands followed by a backwards jump or goto. Structured programming is less about power — in the sense of one higher-level command expanding into many lower-level ones — than safety. Programmers following it were much less prone to make mistakes. The division of code into blocks, subroutines and other modules with clearly-defined interfaces also had productivity benefits in allowing many programmers to work on one project. Once introduced (in the ALGOL language), structured programming was incorporated into almost all languages, and retrofitted to languages that did not originally have it, such as Fortran, etc.
Block structure was also associated with deprecation of global variables, a similar source of error to goto. Instead, the structured languages introduced lexical scoping and automated management of storage with a stack.
Another high-level feature was the development of type systems that went beyond the data types of the underlying machine code, such as strings, arrays and records.
Where early 3GLs were special-purpose, (e.g. science or commerce) an attempt was made to create general-purpose languages, such as C and Pascal. While these enjoyed great success,domain specific languages did not disappear.

program structure and variable declaration

Program Structure

Virtually all structured programs share a similar overall structure:
  • Statements to establish the start of the program
  • Variable declaration
  • Program statements (blocks of code)
The following is a simple example of a program written in several different programming languages. We call this the “Hello World” example since all the program does is print “Hello World” on the computer screen.
LanguageExample program
“C”
#include <stdio.h>void main() {
    printf("Hello World");
}
C++
#include <iostream>int main() {
    cout << "Hello World";
    return 0;
}
Pascal
program helloworld (output);begin
    writeln('Hello World');
end. 
Oracle PL/SQL
CREATE OR REPLACE PROCEDURE helloworld AS
BEGIN
    DBMS_OUTPUT.PUT_LINE('Hello World');
END;
Java
class helloworld {
    public static void main (String args []) {
       System.out.println ("Hello World");
    }
}
Perl
#!/usr/local/bin/perl -w print "Hello World";
Basic
print "Hello World"
Note that the Perl and Basic languages are technically not compiled languages. These language statements are “interpreted” as the program is running.

Variable Declaration

Variables are place holders for data a program might use or manipulate. Variables are given names so that we can assign values to them and refer to them later to read the values. Variables typically store values of a given type. Types generally include:
  • Integer – to store integer or “whole” numbers
  • Real – to store real or fractional numbers (also called float to indicate a floating point number)
  • Character – A single character such as a letter of the alphabet or punctuation.
  • String – A collection of characters
In order to use a variable within a program, the compiler needs to know in advance the type of data that will be stored in it. For this reason, we declare the variables at the start of the program. Variable declaration consists of giving a new name and a data type for the variable. This is normally done at the very start of the program.
In the following example programs, variables of different types are declared and used in the programs.
LanguageExample program
“C”
#include <stdio.h>
void main() {
   int age;
   float salary;
   char middle_initial;
   age = 21;
   salary = 29521.12;
   middle_initial = "K";
   printf("I am %d years old ", age);
   printf("I make %8.2f per year " salary);
   printf("My middle initial is %c ", middle_initial);
}
Pascal
program myexample (output);
   var age: integer;
   salary: real;
   middle_initial: char;
begin 
   age := 21;
   salary := 29521.12;
   middle_initial := 'K';
   writeln('I am ', age, ' years old');
   writeln('I make ', salary, ' per year');
   writeln('My middle initial is ', middle_initial);
end.
Oracle PL/SQL
CREATE OR REPLACE PROCEDURE myexample AS
    age NUMBER;
    salary NUMBER;
    middle_initial CHAR(1);
BEGIN
   age := 21;
   salary := 29521.12;
   middle_initial := 'K';
   DBMS_OUTPUT.PUT_LINE('I am ' || age || ' years old');
   DBMS_OUTPUT.PUT_LINE('I make ' || TO_CHAR(salary, '99999.99') || ' per year');
   DBMS_OUTPUT.PUT_LINE('My middle initial is ' || middle_initial);
END;
Java
class myexample {
   public static void main (String args []) {
      int age; 
      double salary;
      String middle_initial;
      age = 21;
      salary = 29521.12;
      middle_initial = "K";
      System.out.println ("I am " + age + " years old ");
      System.out.println ("I make " + salary + " per year");
      System.out.println ("My middle initial is " + middle_initial);
   }
}
Perl
#!/usr/local/bin/perl $
     age = 21; 
     $salary = 29521.12; 
     $middle_initial = "K"; 
     print "I am " . $age . " years old "; 
     print "I make " . $salary . " per year "; 
     print "My middle initial is " . $middle_initial;
Basic
Dim age AS Integer 
Dim salary AS Decimal 
Dim middle_initial As String 
age = 21 
salary = 29521.12 
middle_initial = "K" 
print "I am " & age & " years old " 
print "I make " & $salary & " per year " 
print "My middle initial is " & $middle_initial
In the above examples it is clear that different programming languages have slightly different syntax and data types. However for the most part, variable declaration is straight forward.
Real differences begin to appear when more complex data structures such as arrays and pointers are declared. Such discussion is best left for programming courses.

what is programming?

What is Programming?

In the most basic sense, programming means creating a set of instructions for completing some specific task. In this sense, many of our daily activities can be described as programmatic—they involve specific steps that often follow a set order. For instance, if you get home from school and want to make yourself a peanut butter and jelly sandwich, you know that you will have to get two slices of bread, butter each piece, spread peanut butter on one slice and jelly on the other, and finally put the two together. If you leave out a step you might end up with something other than a PB&J sandwich. If you do things out of order—say, you put the slices of bread together before you spread the peanut butter—you'll end up with a mess.
Apple pie recipe
In this general sense, our lives are filled with programs and programming. When you make your bed you follow certain steps in a programmatic fashion. The steps must be the correct ones and they must be in the correct order. If you want to make your grandmother's favorite apple pie, you would ask her how to do it, and she most likely would send you a program—a recipe. A program is therefore also useful for replicating a product even if you are far removed from the original creator of the product.
But programs are not only useful for reproducing products. Humans—even young children—have a remarkable capacity for mastering programmatic processes and behaviors. Take the familiar children's game, One Potato, Two Potato. This chant is a common way for children to choose who is going to be "it" in a game. The children will all stand in a circle around the counter and hold their fists out in front of them. The counter recites the rhyme, striking each fist in the circle in turn for each word of the rhyme. When the counter strikes a fist on the last word of the rhyme—"...seven potato, more."—that fist is knocked out of the game. The counter then repeats the rhyme, each time knocking out another fist. The last person with a fist remaining raised is "it". This simple game has all of the elements of a program—a set sequence of events, actions performed based on the outcome of a process, and repetition.
In the context of computing, programming means creating a set of instructions not for a person but for a computer, in order to accomplish a specific task. To do so you use a set of directives—a programming language—known to both the programmer and the computer operating system. The kind of things we program computers to do is different from what we “program” ourselves to do. Usually a set of instructions, or program, for a computer is intended to complete a task that:
  • is repetitious, and therefore would exceed human patience or capacity for long term attention to detail;
  • controls machinery in conditions unsuitable for humans because of physical limitations, hazardous conditions, etc.;
  • requires a high degree of accuracy;
  • requires high speed.

Basic Programming Concepts

Even though each programming language you use is unique, there are certain concepts common to all languages, including LiveCode's scripting language. Let's look at three of the most common concepts and structures used in programming.
  1. Sequence of commands (The right commands in the right order.)
    It is important not only to give the right commands or steps—they must also be given in the correct sequence. We can easily see in some of our mundane examples—making a sandwich, tying one's shoes, following a recipe—that proper order is essential to our success. We might call such obvious sequences task order, because the proper sequence is dictated by the nature of the task.
    But there are also procedures in which the order of steps is unimportant. Often in such procedures, a conventional order emerges to avoid confusion. An excellent example in the U.S. context is addressing letters for mailing. Every school child knows that you do it in this order:
    First name Last name
    House number Street name
    City, State   Zip code
    Country
    Oddly enough, this conventional order is exactly the reverse of how the address is examined at the various postal distribution points in the mail system. The post office at the point of origin would look at the country and put the letter in a pile for international mail. The distribution center in the destination country would look at the zip code and perhaps state. The local post office would examine the street address and place it in the proper mail carrier's route, and the mail carrier, upon arriving on that street, would place it into the mailbox bearing that address. Finally, whoever checked the mail at the house would look at the name and give the letter to the person it was addressed to.
    Envelope showing Russian address order
    In some countries the conventional order follows the logical task order in addressing envelopes. In Russia, for example, letters are addressed in exactly the opposite order to the U.S. convention.
    Example: You want to clear your screen of all buttons and fields, show a field with text, wait for the user to click, then hide the field and show the former ones.
    To work correctly, not only do all the commands have to be there, they have to be in the right order.
  2. Conditional structures (Do certain things based on a true or false, yes or no decision.)
    These provide for one outcome or sequence of events to be executed if a statement is true, and another outcome or sequence of events to be triggered if the statement is false.
    In most programming languages these structures take the form if . . . then . . . else.
    The One Potato, Two Potato game uses lots of conditional decisions.
    If the counter lands on your fist on the word "more" then you must remove your fist from the circle.
    If both of your fists are knocked out of the circle then you are out of the game.
    Computing examples:
    Example 1:
    If a word exists in a list, then print it out,
    Else tell the user that the word does not exist.

    Example 2:
    If a sentence contains the word "silly" then put that sentence into the silly list.
    Else if it doesn't contain the word "silly" then put it into the serious list.
  3. Looping structures (A list of instructions to do more than once.)
    Used to make the computer repeat a certain command or sequence of commands. The loop may run for a predetermined number of times, until a certain condition becomes true, or as long as a certain condition remains true.
    Here are some ways that looping might be done:
    Do the following 20 times.
    Do the following once for each word in the list
    Repeat the following until the user presses the option key
    Repeat the following as long as the option key is depressed.
    Again, the One Potato game provides an obvious example of a looping structure. The rhyme is repeated and fists counted for as many times as needed until just one person is left.
    Another Example:
    Given a list of party guests, assign everyone to one of three groups for "ice-breaker" games.

Programming Strategies

Programming can range in complexity from solving small problems—like setting an alarm time on your watch or cell phone—to very sophisticated instructional or business applications. For more complex tasks, you can use these strategies to help you think through the logic of your program before starting to write code.
A flow chart diagram of the one potato-two potato game
(Click to enlarge.)
Top-down design
Top-down design is a way of approaching a complex programming task by first mapping out the entire program and identifying the major components that it will require. Then the programmer would use flowcharts and general statements to represent the logical flow of your program. Once the major components are identified, the programmer then focuses on each component in greater detail, finally culminating in writing the actual program code for creating each component.
In the example at right, we have represented the “program” for playing One Potato, Two Potato using a top-down approach. Each shape in the flowchart represents a major step in the game. Combinations of shapes and arrows show conditional “if-then” decision points, as well as looping structures in which segments of the program are repeated, perhaps with slight variations in each iteration.

pseudocode for one-potato two-potato game
(Click to enlarge.)
PseudocodeThis term, from the prefix pseudo-, 'false' and the root word code, 'programming instructions', describes a way of representing the detailed steps your program must perform without having to worry about the specific vocabulary or syntax of a specific programming language. You use your knowledge of the basic control structures, common sense and logic to write plain-English statements to explain in detail how you will accomplish each main step. All of the examples shown here and used in class could be considered forms of pseudocode.
Here is an example of pseudocode that describes our One Potato, Two Potato “program”. Notice how it attempts to detail all of the steps, conditional statements and looping segments using simple statements, indents and minimal punctuation brackets.