Friday, 14 June 2013

Procedural Programming Language

Procedural language is a computer programming language that specifies a series of well-structured steps and procedures within its programming context to compose a program. It contains a systematic order of statements, functions and commands to complete a computational task or program. 

Procedural language is also known as imperative language.
Procedural language, as the name implies, relies on predefined and well-organized procedures, functions or sub-routines in a program’s architecture by specifying all the steps that the computer must take to reach a desired state or output. 

Procedural language segregates a program within variables, functions, statements and conditional operators. Procedures or functions are implemented on the data and variables to perform a task. These procedures can be called/invoked anywhere between the program hierarchy, and by other procedures as well. A program written in procedural language contains one or more procedures. 

Procedural language is one of the most common programming languages in use with notable languages such as C/C++, Java, ColdFusion and PASCAL.

Benefits of Procedural Languages
  • Extensibility. Utilizing the internal PLs enables developers to quickly create custom functions, triggers, and rules to add functionality not already present in the base system. Moreover, once these extensions are enabled, they become available to other SQL statements present in the system.
  • Control structures. By default, the SQL language does not allow the programmer to use the rich set of control structures and conditional evaluations included in other common programming languages. For this reason, the included PLs allow a developer to marry such traditional control structures with the SQL language. This is particularly useful when creating complex computations and triggers.
  • Productivity and compatibility. By using the included PostgreSQL PLs, the developer can have access to all the included data types, operators, and functions already present in the base system. This can significantly increase productivity because the programmer does not need to re-create common elements already defined in PostgreSQL in his or her own custom code. Additionally, the developer can have a high level of assurance that the returned data types and comparison results will be compatible with the PostgreSQL back end.
  • Security. The included PostgreSQL PLs are trusted by the back-end system and only have access to a limited set of system-wide functions. In particular, the included PLs operate, on a system level, with the same permissions granted to the base postgres user. This is because it implies that extraneous file system objects will be safe from any errant code.

One of the advantages of procedural programming is that is has a quicker completion than OOP or Object-Oriented programing. A disadvantage to this technique is a lack of flexibility.

object oriented programming

Object-oriented programming (OOP) is a programming paradigm that represents concepts as "objects" that have data fields (attributes that describe the object) and associated procedures known as methods. Objects, which are usually instances of classes, are used to interact with one another to design applications and computer programs. C++ and Java are examples of object-oriented programming languages.
An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object's behavior. For example, the hand can grip something or a Student (object) can give the name or address
An object oriented program may be viewed as a collection of interacting objects, as opposed to the conventional model, in which a program is seen as a list of tasks (subroutines) to perform. In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects. Each object can be viewed as an independent "machine" with a distinct role or responsibility. Actions (or "methods") on these objects are closely associated with the object. For example, OOP data structures tend to "carry their own operators around with them" (or at least "inherit" them from a similar object or class)—except when they must be serialized.


There are different types of OOPs are used, they are
1.    Object
2.    Class
3.    Data Abstraction & Encapsulation
4.    Inheritance
5.    Polymorphism
6.    Dynamic Binding
7.    Message Passing

1) Object :
Object is the basic unit of object-oriented programming. Objects are identified by its unique name. An object represents a particular instance of a class. There can be more than one instance of an object. Each instance of an object can hold its own relevant data.
An Object is a collection of data members and associated member functions also known as methods.
For example whenever a class name is created according to the class an object should be created without creating object can’t able to use class.
The class of Dog defines all possible dogs by listing the characteristics and behaviors they can have; the object Lassie is one particular dog, with particular versions of the characteristics. A Dog has fur; Lassie has brown-and-white fur.
2) Class :
Classes are data types based on which objects are created. Objects with similar properties and methods are grouped together to form a Class. Thus a Class represents a set of individual objects. Characteristics of an object are represented in a class as Properties. The actions that can be performed by objects become functions of the class and is referred to as Methods.
For example consider we have a Class of Cars under which Santro Xing, Alto and WaganR represents individual Objects. In this context each Car Object will have its own, Model, Year of Manufacture, Colour, Top Speed, Engine Power etc., which form Properties of the Car class and the associated actions i.e., object functions like Start, Move, Stop form the Methods of Car Class.No memory is allocated when a class is created. Memory is allocated only when an object is created, i.e., when an instance of a class is created.

Classes are generally declared using the keyword class, with the following format:

class class_name {
  access_specifier_1:
    member1;
  access_specifier_2:
    member2;
  ...
  } object_names;

Where class_name is a valid identifier for the class, object_names is an optional list of names for objects of this class. The body of the declaration can contain members, that can be either data or function declarations, and optionally access specifiers.

All is very similar to the declaration on data structures, except that we can now include also functions and members, but also this new thing called access specifier. An access specifier is one of the following three keywords:privatepublic or protected. These specifiers modify the access rights that the members following them acquire:

  • private members of a class are accessible only from within other members of the same class or from theirfriends.
  • protected members are accessible from members of their same class and from their friends, but also from members of their derived classes.
  • Finally, public members are accessible from anywhere where the object is visible.

By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before one other class specifier automatically has private access
3) Data abstraction & Encapsulation :
The wrapping up of data and its functions into a single unit is called Encapsulation.
When using Data Encapsulation, data is not accessed directly, it is only accessible through the functions present inside the class.
Data Abstraction increases the power of programming language by creating user defined data types. Data Abstraction also represents the needed information in the program without presenting the details.
Abstraction refers to the act of representing essential features without including the background details or explanation between them.
For example, a class cuboid would be made up of an length,breadth and height. To build the cuboid class, one does not need to know how the different components work internally, but only how to interface with them, i.e., send messages to them, receive messages from them, and perhaps make the different objects composing the class interact with each other.

class cuboid
{
  int length, breadth, height;
  float area, volume;
  public:
totalarea =2(length+breadth+height);
volume = length*breadth*height;
};
    
4) Inheritance :
Inheritance is the process of forming a new class from an existing class or base class.
The base class is also known as parent class or super class, the new class that is formed is called derived class.
Derived class is also known as a child class or sub class. Inheritance helps in reducing the overall code size of the program, which is an important concept in object-oriented programming.
It is classifieds into different types, they are
  • Single level inheritance
  • Multi-level inheritance
  • Hybrid inheritance
  • Hierarchial inheritance
       example:-
#include <iostream>
using namespace std;

class A {
   int data;
public:
   void f(int arg) { data = arg; }
   int g() { return data; }
};

class B {
public:
   A x;
};

int main() {
   B obj;
   obj.x.f(20);
   cout << obj.x.g() << endl;
//   cout << obj.g() << endl;
}



5) Polymorphism :
Polymorphism allows routines to use variables of different types at different times. An operator or function can be given different meanings or functions. Polymorphism refers to a single function or multi-functioning operator performing in different ways.
Poly a Greek term ability to take more than one form. Overloading is one type of Polymorphism. It allows an object to have different meanings, depending on its context. When an exiting operator or function begins to operate on new data type, or class, it is understood to be overloaded.
#include <iostream>
using namespace std;

class A {
   int data;
public:
   void f(int arg) { data = arg; }
   int g() { return data; }
};

class B {
public:
   A x;
};

int main() {
   B obj;
   obj.x.f(20);
   cout << obj.x.g() << endl;
//   cout << obj.g() << endl;
}

6) Dynamic binding :
It contains a concept of Inheritance and Polymorphism.
7) Message Passing :
It refers to that establishing communication between one place to another.



Thursday, 13 June 2013

Structured Programming Language



STRUCTURED PROGRAMMING LANGUAGE

 A set of quality standards that make programs more verbose but more readable, reliable, and easily maintained. The goal of structured programming is to avoid spaghetti code(Spaghetti code is a pejorative term for source code that has a complex and tangled control structure, especially one using many GOTOs, exceptions, threads, or other "unstructured" branching constructs) caused by overreliance on GOTO statements, a problem often found in BASIC and FORTRAN programs. Structured programming-such as that promoted by C, Pascal Modula-2, and the dBASE software command language - insists that the overall program structure reflect what the program is supposed to do, beginning with the first task and proceeding logically. Indentations help make the logic clear, and the programmer is encouraged to use loops and branch control structures and named procedures rather than GOTO statements.
STRUCTURED PROGRAMMING is the foundation of Modular programming and Object Oriented Programming.
Structured programming frequently employs a top-down design model, in which developers map out the overall program structure into separate subsections. A defined function or set of similar functions is coded in a separate module or submodule, which means that code can be loaded into memory more efficiently and that modules can be reused in other programs. After a module has been tested individually, it is then integrated with other modules into the overall program structure.
Program flow follows a simple hierarchical model that employs looping constructs such as "for," "repeat," and "while." Use of the "Go To" statement is discouraged.
Structured programming was first suggested by Corrado Bohm and Guiseppe Jacopini. The two mathematicians demonstrated that any computer program can be written with just three structures: decisions, sequences, and loops.
·         "Sequence" refers to an ordered execution of statements.
·         In "selection" one of a number of statements is executed depending on the state of the program. This is usually expressed with keywords such as if..then..else..end ifswitch, or case. In some languages keywords cannot be written verbatim, but must be stropped.
·         In "repetition" a statement is executed until the program reaches a certain state, or operations have been applied to every element of a collection. This is usually expressed with keywords such as whilerepeatfor or do..until. Often it is recommended that each loop should only have one entry point (and in the original structural programming, also only one exit point, and a few languages enforce this).

 Edsger Dijkstra's subsequent article, Go To Statement Considered Harmful was instrumental in the trend towards structured programming. The most common methodology employed was developed by Dijkstra. In this model (which is often considered to be synonymous with structured programming, although other models exist) the developer separates programs into subsections that each have only one point of access and one point of exit.
Almost any language can use structured programming techniques to avoid common pitfalls of unstructured languages. Unstructured programming must rely upon the discipline of the developer to avoid structural problems, and as a consequence may result in poorly organized programs. Most modern procedural languages include features that encourage structured programming. Object-oriented programming (OOP) can be thought of as a type of structured programming, uses structured programming techniques for program flow, and adds more structure for data to the model.

Rules for Structured Programming

Lines  
1.  Put only one statement on a line.
2.  Split long lines so that they fit on the page without running over. Indent line continuation.

Identifiers
3.  Use meaningful variable names and function names.
4.  Use all CAPITALS for names of constants. Use lowercase or mixed capital and lowercase for names of variables and other identifiers.
5.  Some instructors prefer a capital letter at the beginning of a class name—for example, class Book.

Comments

class=Section2>
6.  Every program and every function must have a comment at the beginning that tells what it does.
7.  Do not comment closing braces  (// end while).  [However, some instructors like this type of comment.]

Functions
8.  Divide program into functions.
9.  Each function should perform one task.
10.  Each function must have a comment.
11. Put all prototypes above main.  [Some instructors want a comment labeling the prototype section.  For example, // here are the function prototypes ]
12. Put all user-defined functions after main().  [Some instructors may suggest putting user-defined functions before main(), but most prefer that these functions are all after main().]
13. Do not use global items except for file declarations and class definitions. [Some instructors do not permit any global variables at all, including filenames.]

Blank Lines
14. Skip a line between functions.
15. Skip a line after the declaration section in main() and in each function.
16. Skip lines when useful for clarity, but do not double-space your program.

Braces  (there are some alternative rules shown below)
17. Never put more than one closing } on a line.
18. Put each opening { on a line by itself.
19. For loops and if statements, you may put { on the line with the keyword and put } on a line by itself aligned under the keyword.
20. With a few exceptions (such as following rule 18), align { and }.
21. For functions, put { and } on separate lines. 

Indenting
22. Follow rules of indenting.

         How to indent:
               a. Each indent must be at least 5 spaces (some instructors say 3 spaces are enough).
               b. Each time a construct (loop, if statement) occurs inside another construct, indent
                   5 (or 3) more spaces.
              c. Move back out at the end of the construct.
              d. Align statements that are indented at the same level.


         What to indent:
              a. Indent body of main and body of a function (not the header or comment).
              b. Indent body of a loop.
              c. Indent body of an if statement or an else statement.
              d. Indent statements in a switch statement (indent each case, and further indent
                  each action).
              e. Indent items within a class definition.
              f. Indent continued lines.


Example

// Program gives examples of structured programming techniques
// follows brace style identified in rules 17-21
#include <iostream>
using namepace std;
void readarr(int &,int &);
void changearr(int &,int);
void printarr(int arr,int n);
const int SIZE=50;
class justtoshowone {
     int firstitem;
     string seconditem;
     double thirditem;
};

int main()
{
     int n,arr[SIZE];
     justtoshowone example;

     readarr(arr,n);
     changearr(arr,n);
     sum = sumarray(arr,n);
     cout << "the sum of the array is" << sum << endl;
     printarr(arr,n);
     return 0;
}

// reads n and then reads n values into an array, printing the values read in
void readarr(int &n,int arr[])
{
     cin >> n;
     while (n < 0 || n >= SIZE)
          cin >> n;
     for(int i = 0; i < n; i++) {
          cin >> arr[i];
          cout << arr[i] << endl;
     }
     return;
}

// changes array values based on sign of original value;
// counts changes
void changearr(int arr[],int n)
{
      int increased=0, decreased=0,negated=0;

      for(int i = 0; i < n; i++) {
          if (arr[i] == 0) {
               arr[i]++;
               increased++;
          }
          else if (arr[i] < 0) {
              arr[i] = -arr[i];
              negated++;
          }
          else {
              arr[i]--;
              decreased++;
          }
     }
     cout << "# increased is " << increased <<
          << "# decreased is " << decreased <<
          << "# negated is " << negated << endl;
     return;
}

// prints resulting array
void printarr(int arr[],int n)
{
     for(int i = 0; i < n; i++)
          cout << arr[i];
     return;
}


23. There are alternate acceptable forms for indenting and placement of braces, such as the following. Whatever method you choose, be consistent.

      a. Alternate indenting forms and brace placement for if else:

          i. Cascading if statement
 
          if (arr[i] == 0) {
               arr[i]++;
               increased++;
          }
          else if (arr[i] < 0) {
                    arr[i] = -arr[i];
                    negated++;
               }
               else {
                    arr[i]--;
                    decreased++;
               }

          if (arr[i] == 0) {
               arr[i]++;
               increased++;
          }
          else if (arr[i] < 0) {
                    arr[i] = -arr[i];
                    negated++;
               }
               else {
                    arr[i]--;
                    decreased++;
               }


     ii. Braces on same lines with else:

           if (arr[i] == 0) {
               arr[i]++;
               increased++;
           } else if (arr[i] < 0) {
                      arr[i] = -arr[i];
                      negated++;
                 } else {
                        arr[i]--;
                        decreased++;
                 }

     iii. Braces on separate lines (this can be combined with various indenting styles):

           if (arr[i] == 0)
          {
               arr[i]++;
               increased++;
          }
          else if (arr[i] < 0)
               {
                    arr[i] = -arr[i];
                    negated++;
               }
               else
                    {
                         arr[i]--;
                         decreased++;
                    }

b. Alternate brace placement for a loop header:

     for(int i = 0; i < n; i++)
     {
          cin >> arr[i];
          cout << arr[i] << endl;
     }