PPL 1
PPL 1
                                                 Subject Notes
                                 Department of Computer Science and Engineering
    Subject Name: PPL                                                                    Subject Code:CS6002
                                                       Unit-1
    Language Evaluation Criteria
    The following factors influences Language evaluation criteria
    1) Readability 2) Simplicity 3) Orthogonality 4) Writability 5) Reliability 6) Cost
    1. Readability
    • One of the most important criteria for judging a programming language is the ease with which programs
    can be read and understood.
    • Language constructs were designed more from the point of view of the computer than of computer users
    2. Overall simplicity
    • Language with too many features is more difficult to learn
    • Feature multiplicity is bad. For example: In Java, increment can be performed if four ways as:
                                  Count= count+1
                                     Count+=1
                                      Count++
                                       ++count
    • Next problem is operator overloading, in which single operator symbol has more than one meaning.
    3. Orthogonality
    •     A relatively small set of primitive constructs that can be combined in a relatively small number of ways
    •     Consistent set of rules for combining constructs (simplicity)
    •     Every possible combination is legal
    •     For example, pointers should be able to point to any type of variable or data structure
    •     Makes the language easy to learn and read
    •     Meaning is context independent
    •     Lack of orthogonality leads to exceptions to rules
    •     C is littered with special cases
    Orthogonality is closely related to simplicity. The more orthogonal the design of a language, the fewer
    exceptions the language rules require. Fewer exceptions mean a higher degree of regularity in the design,
    which makes the language easier to learn, read, and understand.
    – Useful control statements
    – Ability to define data types and structures
    – Syntax considerations
    4. Writability - Writability is a measure of how easily a language can be used to create programs for a chosen
    problem domain and can be directly related to:
    – Most readability factors also apply to writability
    – Simplicity and orthogonality
    – Control statements, data types and structures
    – Support for abstraction
    5. Reliability-
    A program is said to be reliable if performs to its specifications under all conditions.
    Type checking
    • Type checking is simply testing for type errors in a given program, either by the compiler or during the
    program execution
    • Because run time type checking is expensive, compile time type checking is more desirable
    • Famous failure of space shuttle experiment due to int / float mix-up in parameter passing.
    Exception handling
    • A ility to intercept run-time errors
    • A ility to use different names to reference the same memory
    • A dangerous feature
    6. Cost-
    The cost is also an important language evaluation criteria. The total cost of a programming is a function of cost
    of training to programmers, cost of writing programs, cost of compiling programs, cost of executing programs,
    cost of maintaining programs.
        structured programming
    Programming Methodologies Influences
     Scientific applications-– Large number of floating point computations. The most common data structures
    Programming Domain
    are arrays and matrices; the most common control structures are counting loops and selections. The first
    language for scientific applications was FORTRAN, ALGOL 60 and most of its descendants. Examples of
    languages best suited: Mathematica and Maple.
    • Business applications- Business languages are characterized by facilities for producing reports, precise
    ways of describing and storing decimal numbers and character data, and ability to specify decimal arithmetic
    operations. Its uses for decimal numbers and characters. COBOL is the first successful high-level language for
    those applications.
    • Artificial intelligence- In AI Symbols rather than numbers are typically manipulated. Symbolic computation is
    more conveniently done with linked lists of data rather than arrays. This kind of programming sometimes
    requires more flexibility than other programming domains. The first AI language was LISP and is still most
    widely used
    • Systems programming- The operating system and all of the programming support tools of a computer
    system are collectively known as systems software. It needs for efficiency because of continuous use and low-
    level features for interfaces to external devices
    • Special-purpose languages
    – RPG (Report Program Generator) : business reports
    – APT (Automatically Programmed Tool) programmable machine tools
    – GPSS (General Purpose Simulation System ) : simulation
    Language Categories-
    The four categories usually recognized are imperative, object-oriented, functional, and logic. Each Language
    category has some special features.
    Programming Paradigms
    1. Imperative- imperative programming is a programming paradigm that uses statements that change a
    program's state.
    In much the same way that the imperative mood in natural languages expresses commands, an imperative
    program consists of commands for the computer to perform. Imperative programming focuses on
    describing how a program operates.
    Examples: C, Pascal
    2. Object-oriented-Stands for "Object-Oriented Programming." OOP refers to a programming methodology
    based on objects, instead of just functions and procedures. These objects are organized into classes, which
    allow individual objects to be group together. Most modern programming languages including Java, C/C++,
    and PHP, are object-oriented languages, and many older programming languages now have object-oriented
    versions.
    An "object" in an OOP language refers to a specific type, or "instance," of a class. Each object has a structure
    similar to other objects in the class, but can be assigned individual characteristics. An object can also call
    functions, or methods, specific to that object. For example, the source code of a video game may include a
    class that defines the structure of characters in the game. Individual characters may be defined as objects,
    which allow them to have different appearances, skills, and abilities. They may also perform different tasks in
    the game, which are run using each object's specific methods.
    Examples: Java, C++
    3. Functional-Functional programming languages are specially designed to handle symbolic computation and
    list processing applications. Functional programming is based on mathematical functions. Some of the popular
    functional programming languages include: Lisp, Python etc.
    Examples: LISP, Scheme
    Functional programming languages are categorized i to t o g oups, i.e. −
     Pure Functional Languages − these t pes of fu tio al la guages suppo t o l the fu tio al pa adig s. Fo
    e a ple − Haskell.
     Impure Functional Languages − these t pes of fu tio al la guages suppo t the fu tio al pa adig s a d
    impe ati e st le p og a      i g. Fo e a ple − LI“P.
    execution of a logic program corresponds to the construction of a proof of the goal statement from the
    axioms.
    Example: Prolog
Source Code
Lexical Analyser
Syntax Analyser
                                                Intermediate Code
                  Symbol                        Generator                           Error
                  Table                                                             Handler
                                                Machine Independent
                                                Code optimizer
Target Code
Source program
Input data
Interpreter
                                                       Result
                                         Figure 1.2 Pure Interpretation Process
Source Code
Lexical Analyzer
Syntax Analyzer
                                               Intermediate Code
                                               Generator
                                                                                 Input data
Interpreter
    Programming Environments-
    Integrated Development Environments
    An Integrated Development Environment (IDE) is a software application that provides comprehensive facilities
    to computer programmers for software development. An IDE normally consists of a source code editor, build
    automation tools and a debugger. Most modern IDEs have intelligent code completion. Some IDEs, such
    as NetBeans and Eclipse, contain a compiler, interpreter, or both. The boundary between an integrated
     development environment and other parts of the broader software development environment is not well-
     defined. Sometimes a version control system and various tools to simplify the construction of a Graphical User
     Interface (GUI) are integrated. Many modern IDEs also have a class browser, an object browser, and a class
     hierarchy diagram, for use in object-oriented software development.
     are the following: Lexical analysis (scanning), syntactic analysis (parsing), and Semantic analysis. There are four
     functions in semantic analysis. These as follows:
  1. Symbol-table maintenance.
  2. Insertion of implicit information.
  3. Error detection
  4. Macro processing and compile-time operations.
  Macro is a set of keystrokes and instructions recorded and saved under a short key code. When the key code is
     typed, the program carries out the instructions of the macro. Program users create macros to save time by
     replacing often-used, sometimes lengthy, series of strokes with shorter versions. A compile-time operation is
     an operation to be performed during translation to control the translation of the source program.
   Synthesis of the Object Program- The final stages of translation are concerned with the construction of the
     executable program from the outputs produced by the semantic analyser. It is composed of
     Optimization- The semantic analyser ordinarily produces as output the executable translated program
     represented in some intermediate code.
    Code generation- After the translated program in the internal representation has been optimized; it must be
     formed into the assembly language statements, machine code, or other object program form that is to be the
     output of the translation.
    Linking and loading- In the optional final stage of translation, the pieces of code resulting from separate
     translations of subprograms are coalesced into the final executable program.
  Formal Translation models- The formal definition of the syntax of a programming language is usually
     called grammar. Grammar is a branch of linguistics dealing with the form and structure of words
     (morphology), and their interrelation in sentences (syntax). The study of grammar reveals how language
     works.
 Context Free Grammar- A context-free grammar (CFG) consisting of a finite set of grammar rules is a quadruple
 Example
  The g a       a {A}, {a, , }, P, A , P : A → aA, A → a .
  The g a       a {“, a, }, {a, }, P, “ , P: “ → a“a, “ → “ , “ → ε
  The g a       a {“, F}, { , }, P, “ , P: “ → “ | F, F → F | ε
  Bacus-Naur form is a notation which can be used to give inductive specifications for the syntactic elements of a
    language. The problem we face when we wish to define the rules of syntax (grammar) of a language is that we
    have to use notation (often involving the same alphabet as used in the language) to describe the rules for
    forming strings of symbols. We need to be able to distinguish symbols appearing in the syntax rule which are
    part of the rule itself from symbols which are part of a properly formed string of the language. Bacus and Naur
    developed a notational scheme, called BNF, for such syntax descriptions.
    BNF can be used to inductively define a number of sets of syntactic elements of a language at once. These sets
    are called syntactic categories, or sometimes nonterminals and we write the names of these sets by enclosing
    them in "<" ">" . For example, the list_of_numbers J data type would be a nonterminal and would be written
    as <list_of_numbers>. Each syntactic category is defined by a finite set of rules, or productions. Each rule
    asserts that certain values must be in the syntactic category.
    Example 1
    Here is the BNF definition of the list-of-numbers syntax. This description has two rules.
X Y Z
E + E
E E * E
                                                                  id        id
                                         Figure 1.5 Example of Parse Tree
    Example: Given the following grammar, find a parse tree for the string 1 + 2 * 3:
    <E> --> <D>
    <E> --> ( <E> )
    <E> --> <E> + <E>
    <E> --> <E> - <E>
    <E> --> <E> * <E>
    <E> --> <E> / <E>
    <D> --> 0 | 1 | 2 | ... 9
    The parse tree is:
       E --> E --> N --> 1
             +
             E --> E --> N --> 2
                    *
                    E --> N --> 3
                                                        Subject Notes
                                        Department of Computer Science and Engineering
    Subject Name: PPL                                                                       Subject Code:CS6002
                                                            Unit-2
    Data type:
    A data type defines a collection of data values and a set of predefined operations on those values.
    Design issues for all data types
       i.  What operations are defined and how are they specified.
      ii.  It is convenient, both logically and concurentely, to think of variables in terms of descriptors.
    Descriptor:
    A descriptor is the collection of the attributes of a variable
       i.  A descriptor is used for type checking, allocation and, de-allocation.
      ii.  Static attributes need only be available at compile-time; dynamic attributes need to be available at
           run-time.
Exponent Fraction
                             Sign bit
                                    Figure 2.1 (a) Single Precision floating point format
11 bits 52 bits
Exponent Fraction
Sign bit
        C. Decimal
           i. for business applications.
          ii. store a fixed number of decimal digits (coded)
          Advantage: accuracy
         Disadvantages: limited range, wastes memory
        D. Boolean types
           i. The range of values has only two elements TRUE or FALSE.
          ii. Booleans types are often used to represent switches or flags in programs
    Character- Character is a symbol in programming language that has meaning. A character can be any letter,
    number, punctuation marks, symbols or whitespace. For example, the word "character" consists of eight
    characters and the phrase "Hello World!" consists of 12 characters including the whitespace and exclamation
    mark. In programming character is a datatype. We can declare a variable as of a character type and store
    characters in the variable. For example, in C and Java, we write,
    Characters when storing in a variable must be inserted between single quotes. String is another datatype in
    programming, which is a modified version of character datatype. Strings are used to store more than one
    character
    Character String Types
           Character string type is one in which the values consist of sequences of characters
    Design issues with the string types
       i.   Should strings be simply a special kind of character array or a primitive type?
      ii.   Should strings have static or dynamic length?
    String Operations
       i.   Assignment ( Java: str1 = str2;) (C: strcpy(pstr1, pstr2);
      ii.   Comparison (=, >, etc.) BASIC: str1 < str2
     iii.   Concatenation, C: strcat (str1,str2), (Java : str2 + str3;)
     iv.    Substring reference
      v. Pattern matching, C: strcmp(str1,str2);
    Implementation
       i. Static length - compile-time descriptor
      ii. Limited dynamic length - may need a run-time descriptor for length (but not in C and C++ because the
          end of a string is marked with the null character)
     iii. Dynamic length - need run-time descriptor; allocation/deallocation is the biggest implementation
          problem
                                                                   Limited dynamic string
                              Length
                                                                          Current Length
                             Address                                         Address
Figure 2.2 Compile and Run time Descriptor for static and dynamic string
    Array
    Array is a data structure, which provides the facility to store a collection of data of same type under single
    variable name. Just like the ordinary variable, the array should also be declared properly. The declaration of
    array includes the type of array that is the type of value we are going to store in it, the array name and
    maximum number of elements.
    Design Issues
       i.   What types are legal for subscripts?
      ii.   Are subscripting expressions in element references range checked?
     iii.   When are subscript ranges bound?
     iv.    When does allocation take place?
      v. Are Jagged or rectangular multidimensioned arrays allowed, or both?
     vi.    Can array objects be initialized?
     vii.   Are any kind of slices allowed?
    Associative
          i. An associative array is an unordered collection of data elements that are indexed by an equal number
               of values called keys.
          ii. Also known as Hash tables
               a. Index by key (part of data) rather than value.
               b. Store both key and value (take more space).
               c. Best when access is by data rather than index.
          iii. Examples:
               Lisp alist:          ((key1 . data1) (key2 . data2) (key3 . data3)
                          $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
    Associative arrays have an index that is not necessarily an integer, and can be sparsely populated. The index
    for an associative array is called the key, and its type is called the Key Type.
    Design Issues
    i. What is the form of references to elements?
    ii. Is the size static or dynamic?
    Record
    A record is a possibly heterogeneous aggregate of data elements in which the individual elements are
    identified by names
    Design Issues
    i. What is the form of references?
    ii. What unit operations are defined? (Assignment, equality, assign corresponding filed)
    4. Record Operations
    i. Assignment
          a. Pascal, Ada, and C allow it if the types are identical
          b. In Ada, the RHS can be an aggregate constant
    ii. Initialization
    Allowed in Ada, using an aggregate constant
    iii. Comparison
    In Ada, = and /=; one operand can be an aggregate constant
    iv. Move Corresponding
          a. In COBOL - it moves all fields in the source record to fields with the same names in the destination
              record
       b. Useful operation in data processing application, where input records are moved to output files after
          same modification.
    Comparing records and arrays
       a. Access to array elements is much slower than access to record fields, because subscripts are dynamic
          (field names are static)
       b. Dynamic subscripts could be used with record field access, but it would disallow type checking and it
          would be much slower.
                                                        Record
                                                         Name
                                 Field 1
                                                          Type
Offset
                                                            .
                                      :
                                                            .
                                      :
                                                         Name
                                                          Type
                                  Field n                Offset
Address
    Union
    Union is a data type with two or more member similar to structure but in this case all the members share a
    common memory location. The size of the union corresponds to the length of the largest member. Since the
    member share a common location they have the same starting address.The real purpose of unions is to
    prevent memory fragmentation by arranging for a standard size for data in the memory. Java has neither
    records nor unions.
    The syntax of union declaration is
    union union_name
    {
    type element 1;
    type element 2;
    ……………..
    type element n;
    };
    This declares a type template. Variables are then declared as:
    union union_name x,y,z;
    For example, the following code declares a union data type called Student and a union variable called stud:
    union student
    {
    int rollno;
    float totalmark;
    };
    Pointer
    Pointer is a variable that represents the location of a data item, such as variable or an array element. Within
    the o puter’s e or , e er stored data ite o upies o e or ore o tiguous e or ells. The u er
    of memory cells required to store a data item depends on the type of the data item. For example, a single
    character will typically be stored in one byte of memory; an integer usually requires two contiguous bytes, a
    floating-point number usually requires four contiguous bytes, and a double precision usually requires eight
    contiguous bytes.
    For example, a C program contains the following declarations.
    int i,*ptri;
    float f,*ptrf;
    The first line declares i to be an integer type variable and ptri to be a pointer variable whose object is an
    integer quantity. The second line declares f to be a floating-point type variable and ptrf to be a pointer
    variable whose object is a floating point quantity.
    Uses
    i. Addressing flexibility (support indirect addressing)
    ii. Dynamic storage management (scoping)
    Design Issues
    What is the scope and lifetime of pointer variables?
    i. What is the lifetime of heap-dynamic variables?
    ii. Are pointers restricted to pointing at a particular type?
    iii. Are pointers used for dynamic storage management, indirect addressing, or both?
    iv. Should a language support pointer types, reference types, or both?
    Variables
    A variable is an abstraction of a memory cell. They have the following characteristics:
    i. Name The identifier that refers to the variable. Variables created dynamically with new or malloc can be
    anonymous.
    ii. Address The location in memory where the variable is stored. A single variable can have multiple different
    addresses as a program runs. It is also possible that multiple variables can refer to the same address. An
    address is so eti es alled a L-Value si e it is eeded for the left-hand side of an assignment.
    iii. Value The o te ts of the aria le. A alue is so eti es alled a R-Value si e it is eeded for the right-
    hand side of an assignment.
    iv. Type Determines what possible values can be stored in the variable and what operations are permitted on
    it. We will discuss types more in the future.
    v. Lifetime The period of time when a variable exists.
    vi Scope The portion of code which can access the variable.
    int main() {
       int a;
       int b;
    }
    The above program creates two variables to reserve two memory locations with names a and b. We created
    these variables using int keyword to specify variable data type which means we want to store integer values in
    these two variables. Similarly, you can create variables to store long, float, char or any other data type
    Binding
    A binding is an association between an entity and an attribute, such as between a variable and its type or
    value, or between a function and its code.
    Binding time is the point at which a binding takes place. There are different times a binding can happen:
    i. Design Time Some binding decisions are made when a language is designed such as the binding of + to
    addition in C, the operations of the String class in Java and so on.
    ii. Compile Time Bindings can also be done while the program is compiled such as binding variables to types in
    C++ or Java.
    iii. Link Time aaasLink time is when compiled code is combined into a full program for C and C++. At this time,
    global and static variables are bound to addresses.
    iv. Run Time Many bindings happen at run time including most values being bound to variables. In dynamically
    typed languages like Python, types are bound at run time as well.
    Any binding that happens at run time is called dynamic, and any that happens before run time is called static.
    Things that are statically bound can not change as a program runs, and those that are dynamically bound can
    change.
    What bindings take place in the following C code?
    count = count + 5;
           The type of count is bound at compile time
           The set of possible values of count is bound at design time
           The meaning of the operator symbol + is bound at compile time, when the types of its operands have
             been determined.
           The internal representation of the literal 5 is bound at design time.
           The value of count is bound at execution time with this statement
    print(total)
    This ode pri ts 0 i stead of 5050". This t pe of error a       e diffi ult to de ug.
    TYPE CHECKING
    Type checking is the process of verifying and enforcing the constraints of types, and it can occur either at
    compile time (i.e. statically) or at runtime (i.e. dynamically). Type checking is all about ensuring that the
    program is type-safe, meaning that the possibility of type errors is kept to a minimum. A type error is an
    erroneous program behavior in which an operation occurs (or trys to occur) on a particular data type that it’s
    not meant to occur on. This could be a situation where an operation is performed on an integer with the
    intent that it is a float, or even something such as adding a string and an integer together:
    Strong Typing
    A strongly typed language is one in which each name in a program in the language has a single type associated
    with it, and that type is known as compile time. The essence of this definition is that all types are statically
    bound. The weakness of this definition is that it ignores the possibility that the storage location to which it is
    bound may store values of different types at different times. We define a programming language to
    be strongly typed if type errors are always detected.
    Type Compatibility
    There are two types of compatibility methods: name compatibility and structure compatibility.
    Name type compatibility means that 2 variables have compatible types only if they are in either the same
    declaration or in declarations that use the same type name.
    Example: int x; int y; // x and y are name type compatible (if the variables are declared using the same
    declaration or the same type)
    Structure type compatibility means that 2 variables have compatible types if either type has identical
    structures.
    Example struct foo { int x; float y; };
            struct bar { int x; float y;};
            foo a; bar b; // a and b are structure type compatible (if the variables have the same structure even
    though they are of differently named type)
    Named constants- a constant is a value that cannot be altered by the program during normal execution, i.e.,
    the value is constant. When associated with an identifier, a constant is said to be "named," although the terms
    "constant" and "named constant" are often used interchangeably. This is contrasted with a variable, which is
    an identifier with a value that can be changed during normal execution, i.e., the value is variable. Constants
    are useful for both programmers and compilers: for programmers they are a form of self-documenting code
    and allow reasoning about correctness; while for compilers they allow compile-time and run-time checks that
    constancy assumptions are not violated, and allow or simplify some compiler optimizations.
    Variable initialization- A variable provides us with named storage that our programs can manipulate. Each
    variable in Java has a specific type, which determines the size and layout of the variable's memory; the range
    of values that can be stored within that memory; and the set of operations that can be applied to the variable.
    Initialization is often done on the declaration statement, e.g., in Java
             int sum = 0;
    There are three ki ds of aria les i Ja a −
                  (a) Local variables
                  (b) Instance variables
                  (c) Class/Static variables
    Local Variables
         1. Local variables are declared in methods, constructors, or blocks.
         2. Local variables are created when the method, constructor or block is entered and the variable will be
             destroyed once it exits the method, constructor, or block.
         3. Access modifiers cannot be used for local variables.
         4. Local variables are visible only within the declared method, constructor, or block.
         5. Local variables are implemented at stack level internally.
    Instance Variables
        1. Instance variables are declared in a class, but outside a method, constructor or any block.
        2. When a space is allocated for an object in the heap, a slot for each instance variable value is created.
        3. Instance variables are created when an object is created with the use of the keyword 'new' and
            destroyed when the object is destroyed.
        4. Instance variables hold values that must be referenced by more than one method, constructor or
            block, or essential parts of an object's state that must be present throughout the class.
    Class/Static Variables
        1. Class variables also known as static variables are declared with the static keyword in a class, but
            outside a method, constructor or a block.
        2. There would only be one copy of each class variable per class, regardless of how many objects are
            created from it.
        3. Static variables are rarely used other than being declared as constants. Constants are variables that are
            declared as public/private, final, and static. Constant variables never change from their initial value.
        4. Static variables are stored in the static memory. It is rare to use static variables other than declared
            final and used as either public or private constants.
    Sequence control with Expressions: -The control of the order of execution of the operations both primitive
    and user defined.
    Implicit: determined      by   the    order    of   the    statements     in    the    source    program
    or by the built-in execution model
    Explicit: the     programmer     uses    statements     to    change    the      order    of    execution
    (e.g. uses If statement)
    Conditional Statements-
    In the programs that we have examined to this point, each of the statements is executed once, in the order
    given. Most programs are more complicated because the sequence of statements and the number of times
    each is executed can vary. We use the term control flow to refer to statement sequencing in a program.
    If Statement
    The simplest if structure involves a single executable statement. Execution of the statement occurs only if the
    condition is true.
    Syntax:
                   if (condition)
                    statement;
    If-else statement
    In if-else statement if the condition is true, then the true statement(s), immediately following the if-statement
    are executed otherwise the false statement(s) are executed. The use of else basically allows an alternative set
    of statements to be executed if the condition is false.
    Syntax:
                 If (condition)
                {
                        Statement(s);
                 }
                else
                {
                       statement(s);
                 }
    IF -else if statement
    It can be used to choose one block of statements from many blocks of statements. The condition which is true
    only its block of statements is executed and remaining are skipped.
    Syntax:
                   if (condition)
                   {
                       statement(s);
                   }
                 else if (condition)
                 {
                        statement(s);
                  }
                   else
                  {
                       (statement);
                  }
    Switch Statement
    Switch statement is alternative of nested if-else.it is executed when there are many choices and only one is to
    be executed.
    Syntax:
    switch(expression)
    {
    case 1:
    statement;
    break;
    case 2:
    statement;
    break;
    .
    .
    .
    .
    case N:
    statement;
    break;
    default:
    statement;
    }
    Loops
    Looping statement are the statements execute one or more statement repeatedly several number of times. In
    C programming language there are three types of loops; while, for and do-while.
    Advantage with looping statement
    i. Reduce length of Code
    ii. Take less memory space.
    iii. Burden on the developer is reducing.
    iv. Time consuming process to execute the program is reduced.
    Types of Loops.
    There are three types of Loops available in 'C' programming language.
    while loop-
             Syntax-
             While(expression)
             { Block of statements;       }
    for loop
    Syntax
             for ( expression1; expression2; expression3)
             {
             Single statement
             or
             Block of statements;
             }
    do..while
    Syntax-
             do
             {
               Single statement
               or
               Block of statements;
             }while(expression);
    Exception handling-
    An exception is a problem that arises during the execution of a program. A C++ exception is a response to an
    exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
    Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is
    built upon three keywords: try, catch, and throw.
    Throw − A progra thro s a e eptio he a pro le sho s up. This is do e usi g a throw keyword.
    Catch − A progra at hes a e eptio           ith a e eptio ha dler at the pla e i a progra         here ou a t
    to handle the problem. The catch keyword indicates the catching of an exception.
    Try − A try block identifies a block of code for which particular exceptions will be activated. It's followed by
    one or more catch blocks.
    Unit-3
    General Subprogram Characteristics
    int main()
    {
      printf("%d", g());
      printf("\n");
      return 0;
    }
    Output :
    10
    Dynamic Scoping: With dynamic scope, a global identifier refers to the identifier associated with the most
    recent environment, and is uncommon in modern languages. In technical terms, this means that each
    identifier has a global stack of bindings and the occurrence of a identifier is searched in the most recent
    binding.
    In simpler terms, in dynamic scoping the compiler first searches the current block and then successively all the
    calling functions.
    // Since dynamic scoping is very uncommon in
    // the familiar languages, we consider the
    // following pseudo code as our example. It
    // prints 20 in a language that uses dynamic
    // scoping.
    int x = 10;
    // Called by g()
    int f()
    {
      return x;
    }
    // g() has its own variable
    // named as x and calls f()
    int g()
    {
      int x = 20;
      return f();
    }
    main()
    {
        printf(g());
    }
    Output
    20
    return 0;
    }
    ii.Pass by Result
    With pass-by-result, no value is transmitted to the subprogram. Instead, the formal parameter acts like a local
    variable, and before control is transferred back to the caller the variables value is transmitted back to the
    actual parameter, because no data is transferred to the subprogram, but it transmits data back to the actual
    parameter it is an out-mode semantic. Most typically pass-by-result uses a copy conceptual model.
    iii.Pass-by-value-result
    This passing method is actually a combination of pass-by-value and pass-by-result. The value of the actual
    parameter is used to initialize the corresponding formal parameter, which then acts as a local variable. The
    formal parameters must have local storage associated with the called subprogram. At termination, the
    subprogram transmits the value of the formal parameter back to the actual parameter. As such, it uses in out-
    mode semantics and copy passing conceptual model. Also, pass-by-value-result has the same advantages and
    disadvantages as pass-by-value and pass-by-result with some more advantages. The largest extra advantage of
    pass-by-value-result is that it solves pass-by- efe e e s aliasi g p o le s.
    iv.Pass-by-reference
    With pass-by-reference an address (reference to the memory location of the actual parameter) is passed to
    the subprogram. It is another example of an inout-mode semantic.
    Advantage- It is efficient in both time and space. This is no duplicate space required or copying.
    Disadvantage – It increase the time to access formal parameters because of the additional level of indirect
    addressing.
    // Illustration of pass by reference
    #include <iostream.h>
    void square (int *x)
    {
    *x = (*x) * (*x);
    }
    int main ( )
    {
    int num = 10;
    square(&num);
    cout<<" Value of num is "<<num; // Value of num is 100
    return 0;
    }
    As you can see the result will be that the value of a is 100. The idea is simple: the argument passed is the
    add ess of the a ia le u . The pa a ete of s ua e fu tio is a poi te poi ti g to t pe i tege . The
    add ess of u is assig ed to this poi te . You a a al ze it as follo s: & u is passed to i t * , the efo e it
    is the same as:
    int *x = #
    This ea s that is a poi te to an integer and has the address of the variable num.
    2. Type-Checking Parameters
    It is now widely accepted that software reliability demands that the types of actual parameters be checked for
    consistency with the types of the corresponding formal parameters.
    Example
    Result = sub1 (1)
     The actual parameter is an integer constant. If the formal parameter of sub1 is a floating-point type, no
     Early languages, such as Fortran 77 and the original version of C, did not require parameter type checking.
         error will be detected without parameter type checking.
         The question is what referencing environment for executing the past subprogram should be used.
             subprogram names that are passed as parameters.
    Shallow Binding: The referencing environment of that execution is that of sub4, so the reference to x in sub2
    is bound to the local x in sub4, and the output of the program is 4.
    Deep Binding: The efe e i g e i o e t of su s e e utio is that of su , so the efe e e so the
    reference to x in sub2 is bound to the local x in sub1 and the output is 1.
    Ad hoc: The binding is to the local x in sub3, and the output is 3.
    Shallow binding is not appropriate for static-scoped languages with nested subprograms.
    5. Overloaded Subprograms
         An overloaded operator is one that has multiple meanings. The types of its operands determine the
         For example, if the * operator has two floating-point operands in a Java program, it specifies floating-
           meaning of a particular instance of an overloaded operator.
         But if the same operator has two integer operands, it specifies integer multiplication.
           point multiplication.
 An overloaded subprogram is a subprogram that has the same name as another subprogram in the
         Every version of an overloaded subprogram must have a unique protocol; that is, it must be different
           same referencing environment.
         The meaning of a call to an overloaded subprogram is determined by the actual parameter list.
           from the others in the number, order, or types of its parameters, or in its return if it is a function.
 Users are also allowed to write multiple versions of subprograms with the same name in ADA, Java,
         Overloaded subprograms that have default parameters can lead to ambiguous subprogram calls.
           C++, and C#.
    Function Overloading
    If any class has multiple functions with same names but different parameters then they are said to be
    overloaded. Function overloading allows you to use the same name for different functions, to perform, either
    same or different functions in the same class.
    Function overloading is usually used to enhance the readability of the program. If you have to perform one
    single operation but with different number or types of arguments, then you can simply overload the function.
    Example - int sum (int x, int y)
    {
    cout<<x+y;
    }
 A programmer should not need to write four different sort subprograms to sort four arrays that differ
            FORTRAN 77, Pascal and Modula-2 functions allow only unstructured types to be returned.
           restrict the type that can be returned by their functions.
            C allows any type to be returned by its functions except arrays and functions.
            C++ also allows any type to be returned by functions including class.
    Co-routines
        A co-routine is a subprogram that has multiple entries and controls them itself
        Also called symmetric control: caller and called co-routines are on a more equal basis
        A co-routine call is named a resume
        The first resume of a co-routine is to its beginning, but subsequent calls enter at the point just after the
        Co-routines provide quasi-concurrent execution of program units (the co-routines); their execution is
           interleaved, but not overlapped
A B
Resume
Resume B Resume A
From master
Resume B Resume A
Resume B Resume A
From master
First resume
                                       Resume B
                                                                                         Resume A
                                                             subsquent
                                                             resume
                                                          Unit 4
    Abstract Data Type
    Abstract data types are mathematical models of a set of data values or information that share similar
    behaviour or qualities and that can be specified and identified independent of specific implementations.
    Abstract data types, or ADTs, are typically used in algorithms. It is defined in term of its data items or its
    associated operations rather than by its implementation.
    An abstract data structure or type "is defined indirectly, only by the operations that may be performed on it
    and by mathematical constraints on the effects (and possibly cost) of those operations."
    Abstraction
    Abstraction is a process where ou sho o l rele a t data a d hide u e essar details of a o je t fro
    the user. Consider your mobile phone, you just need to know what buttons are to be pressed to send a
    message or make a call, what happens when you press a button, how your messages are sent, how your calls
    are connected is all abstracted away from the user.
    Encapsulation
    Encapsulation is the process of combining data and functions into a single unit called class. In Encapsulation,
    the data is not accessed directly; it is accessed through the functions present inside the class. In simpler words,
    attributes of the class are kept private and public getter and setter methods are provided to manipulate these
    attributes. Thus, it makes the concept of data hiding possible.
    C++ supports the properties of encapsulation and data hiding through the creation of user-defined types,
    called classes. We already have studied that a class can contain
      public:
        double getVolume(void) {
          return length * breadth * height;
        }
      private:
       double length; // Length of a box
       double breadth; // Breadth of a box
       double height; // Height of a box
    };
    The variables length, breadth, and height are private. This means that they can be accessed only by other
    members of the Box class, and not by any other part of your program
    class Adder{
      public:
        // constructor
        Adder(int i = 0) {
          total = i;
        }
       // constructor
       Adder(int i = 0) {
          total = i;
       }
         // interface to outside world
       void addNum(int number) {
          total += number;
       }
       // interface to outside world
       int getTotal() {
          return total;
       };
       private:
       // hidden data from outside world
       int total;
     };
     int main() {
        Adder a;
         a.addNum(10);
        a.addNum(20);
        a.addNum(30);
        cout << "Total " << a.getTotal() <<endl;
        return 0;
     }
    Storage Management
    Static Storage Management
    It is the simplest form of allocation i.e an allocation which remain fixed through out the execution.
    Properties of static storage management
         1. Storage for all variables allocated in static block.
         2. Allocation can be done by translator.
         3. Memory reference can be calculated during run time.
         4. Subprogram variables uses space even subprogram never called.
         5. Recursion is not possible.
         6. All storage known at translator time, and memory reference are calculated.
         7. Activation records are directly associated with code segment.
         8. Procedure call and return straight forward.
    Advantage
          Time or space is not expanded for storage management during execution.
          The translator can directly generate values address for all data item.
    Disadvantage
        In compatible with recursive subprograms or any data structure whose size, is dependent on computed
          or input data.
    subprogram and that is a system controlled storage management. Some language use stack to create local
    referencing environment which will vanish on the exit of the procedure.
    A stack has two basic operations : Push and Pop.
    Push : adds a node to the top.
    Pop : Removes and return current top (LIFO).
    The stack is implemented with a little more than just push and pop. The length of a stack can also returned as
    a     parameter       top[1]    can      return     the     top     element     without       removing      it.
    Advantages
        As data is added and removed by LIFO. So, allocation is simpler and faster.
        Memory on the stack is automatically reclaimed with the function exits.
     Disadvantage
         A stack can be very small and is dynamically grow and shrink in size. So, sometimes allocating more
           memory on the stack than available can result in crash due to overflow.
      ii.   Garbage :- It is opposite to dangling reference, if the access path is destroyed with the object still
            allocated to the memory and storage is recovered but it is not a part of the free list and not available
            for reuse. If garbage accumulate, available storage is reduced until the program halts due to lack of
            free space.
    2. Reference counts :- It is an easy way to recognize garbage and makes its space reusable for new cells. In
    that, each heap cell is argument by count field, which record the total number of pointer which points to the
    particular cell. when an item is initially allocated, the reference count is set to 1, and every time a new pointer
    points to the object the counter is increased by 1 and each time, a pointer is destroyed the reference counts is
    decreased by 1. If counter sets to 0, we can reuse the cell by placing it on a free list and non-zero reference
    counts indicate that the structure still accessible and a free command cannot access that.
    Garbage collection
    The basic principle of how a garbage collector works are :
         determine what data objects in a program will not be accessed in future.
         and after determination, will reclaim the resources used by those objects.
         We sat that dangling reference is bigger problem of two, they both are associated with the freeing of
    storage. In dangling reference, the memory is freed too early and in garbage memory is freed too late and it is
    better to have garbage in a program rather than dangling reference. So, we avoid dangling and allow garbage
    to be created. Which creates problem when the heap is full so garbage collection occurs once heap is full and
    process is called rarely. So it is allowable for the procedure to be fairly costly. Two stages are involved.
        1. Mark :- Initially the garbage collection bit is set to 1 and elements are either active or garbage and
            after checking it will change the garbage collection bit of active element to 'O'. Thus every garbage is
            now marked as "on".
        2. Sweep :- After a sequential scan, the garbage collection bit is checked and the elements whose
            garbage collection bit is "on" has been added to the free space list.
          The marking procedure has to check all outside pointers and pointers from active members that means
    they are not garbage. For marking we have three critical assumption :-
         Any active element must be reachable by a chain of pointers beginning outside the heap.
         It must be possible to identify every pointer outside the heap that points to an element inside the
            heap.
         It must be possible to identify within any active heap element the fields that contain pointers to other
            heap elements.
     Advantages
        1. Dangling pointer bugs are reduced.
        2. Double free bugs are reduced : which attempt to free a region that already freed.
    Disadvantage
    It adds overhead that can affect program performance. Thus more CPU time is used to free memory space.
    Smalltalk-
    Smalltalk was the first language to include complete support for the object-oriented programming paradigm.
    General Characteristics
        A program in Smalltalk consists entirely of objects.
        All objects are treated uniformly. They all have local memory, inherent processing ability, the capability
           to communicate with other objects, and the possibility of inheriting methods and instance variables
           from ancestors.
        All Smalltalk objects are allocated from the heap and are referenced through reference variables, which
           are implicitly de-referenced.
        The Smalltalk system integrates a program editor, compiler, the usual features of an operating system,
           and a virtual machine into a single system.
        Smalltalk methods are constructed from expressions. An expression specifies an object, which happens
           to be the value of the expression.
        The most common literals are numbers, strings and keywords.
        Smalltalk variables come in two varieties: private, which means they are local to an object, and shared,
           which means they are visible outside the object in which they are declared
        All Smalltalk variables are references; they can only refer to objects or classes.
        Instance variables are either named or indexed.
        Messages have the form of expressions. They provide the means of communicating among objects and
           are the way operations of an object are requested.
    C++
    C++ supports the object-oriented programming, the four major pillar of object oriented programming used in
    C++ are:
       1. Inheritance
       2. Polymorphism
       3. Encapsulation
       4. Abstraction
    Example of Inheritance
     #include <iostream>
     using namespace std;
     //Base class
     class Parent
     {
        public:
         int id_p;
     };
     //main function
     int main()
       {
Child obj1;
         return 0;
      }
    Output:
    Child id is 7
    Parent id is 91
    Usage of C++
    By the help of C++ programming language, we can develop different types of secured and robust applications:
        o Window application
        o Client-Server application
        o Device drivers
        o Embedded firmware etc.
    Java
    Java is a high level, platform independent, robust, secured and object-oriented programming language.
    Types of Java Applications
    There are mainly 4 types of applications that can be created using java programming:
    1) Standalone Application
    It is also known as desktop application or window-based application. An application that we need to install on
    every machine such as media player, antivirus etc. AWT and Swing are used in java for creating standalone
    applications.
    2) Web Application
    An application that runs on the server side and creates dynamic page, is called web application. Currently,
    servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java.
    3) Enterprise Application
    An application that is distributed in nature, such as banking applications etc. It has the advantage of high level
    security, load balancing and clustering. In java, EJB is used for creating enterprise applications.
    4) Mobile Application
    An application that is created for mobile devices. Currently Android and Java ME are used for creating mobile
    applications.
    Example of Polymorphism
    public Class BowlerClass{
    void bowlingMethod()
    {
    System.out.println(" bowler ");
    }
    public Class FastPacer{
    void bowlingMethod()
    {
    System.out.println(" fast bowler ");
    }
    Public static void main(String[] args)
    {
    FastPacer obj= new FastPacer();
    obj.bowlingMethod();
    }
    }
    C#
    C# is a modern, general-purpose, object-oriented programming language developed by Microsoft and
    approved by European Computer Manufacturers Association (ECMA) and International Standards
    Organization (ISO). It is designed for Common Language Infrastructure (CLI), which consists of the executable
    code and runtime environment that allows use of various high-level languages on different computer
    platforms and architectures.
    C# offers full support for OOP including inheritance, encapsulation, abstraction, and polymorphism:
    Encapsulation is when a group of related methods, properties, and other members are treated as a single
    object.
    Inheritance is the a ilit to re ei e i herit      ethods a d properties fro a e isti g lass.
    Polymorphism is when each class implements the same methods in varying ways, but you can still have
    several classes that can be utilized interchangeably.
    Abstraction is the process by which a developer hides everything other than the relevant data about an
    object in order to simplify and increase efficiency.
    Example of Inheritance in C##
    using System;
    namespace RectangleApplication {
     class Rectangle {
//member variables
    PHP
          PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
          PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic
    content, databases, session tracking, even build entire e-commerce sites.
           It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase,
    Informix, and Microsoft SQL Server.
    Example of Inheritance in PHP
    <?php
    class Animal
    {
       private $family;
       private $food;
       public function __construct($family, $food)
       {
         $this->family = $family;
         $this->food = $food;
       }
       public function get_family()
       {
         return $this->family;
       }
       public function set_family($family)
       {
         $this->family = $family;
       }
       public function get_food()
       {
         return $this->food;
       }
       public function set_food($food)
       {
         $this->food = $food;
       }
    }
    ?>
    <?php
    class Cow extends Animal
    {
       private $owner;
       public function __construct($family, $food)
       {
         parent::__construct($family, $food);
       }
       public function set_owner($owner)
       {
         $this->owner = $owner;
       }
       public function get_owner()
       {
         return $this->owner;
       }
    }
    ?>
    <?php
    class Lion extends Animal
    {
       public function __construct($family, $food)
       {
         parent::__construct($family, $food);
       }
    }
    ?>
    Perl
    Perl is a general-purpose programming language originally developed for text manipulation and now used for
    a wide range of tasks including system administration, web development, network programming, GUI
    development, and more. It is a stable, cross platform programming language.
    Example of Inheritance in Perl
    #!/usr/bin/perl
    package Employee;
    use Person;
    use strict;
    our @ISA = qw(Person); # inherits from Person
#!/usr/bin/perl
use Employee;
    Output
    First Name is Mohammad
    Last Name is Saleem
    SSN is 23234345
    Before Setting First Name is : Mohammad
    Before Setting First Name is : Mohd.
Concurrency
       
    Concurrency can be divided into different levels
            Instruction level is the execution of two or more machine instructions simultaneously.
       
       
            Statement level is the execution of two or more statements simultaneously.
       
            Unit level is the execution of two or more subprogram units simultaneously.
            Program level is the execution of two or more programs simultaneously.
     Concurrent control methods increase programming flexibility
Categories of Concurrency
        Physical concurrency happens when several program units from the same program execute
    There are two distinct categories of concurrent unit control, physical concurrency and logical concurrency.
        Logical concurrency, happens when the execution of several programs takes place in an interleaving
       simultaneously on more than one processor.
         A task or process is a program unit that can be in concurrent execution with other program units
    Introduction to Subprogram level Concurrency
Task Synchronization
        Cooperation synchronization is required between two tasks that when the second task must wait for
    Synchronization is a mechanism that controls the order in which tasks execute.
        Competition synchronization is required between two tasks when both require the use of the same
           the first task to finish executing before it may proceed.
    Semaphores
    Semaphores are used to restrict the number of threads than can access some (physical or logical) resource. It
    is devices used to help with synchronization. If multiple processes share a common resource, they need a way
    to be able to use that resource without disrupting each other. You want each process to be able to read from
    and write to that resource uninterrupted. A semaphore will either allow or disallow access to the resource,
    depending on how it is set up. One example setup would be a semaphore which allowed any number of
    processes to read from the resource, but only one could ever be in the process of writing to that resource at a
    time.
    It is used to share a common memory space and to share access to files
    Type of Semaphores
    Counting semaphores are used when you might have multiple devices (like 3 printers or multiple memory
    buffers).
    Binary semaphores are used to gain exclusive access to a single resource (like the serial port, a non-reentrant
    library routine, or a hard disk drive). A counting semaphore that has a maximum value of 1 is equivalent to a
    binary semaphore (because the semaphore's value can only be 0 or 1).
    Mutex semaphores are optimized for use in controlling mutually exclusive access to a resource. There are
    several implementations of this type of semaphore.
    Monitors
    Monitors provide a structured concurrent programming, which is used by processes to ensure exclusive access
    to resources, and for synchronizing and communicating among users. A monitor module encapsulates both a
    resource definition and operations/ procedures that exclusively manipulate it. Those procedures are the
    gateway to the shared resource and called by the processes to access the resource. Only one call to a monitor
    procedure can be active at a time and this protects data inside the monitor from simultaneous access by
    multiple users. Thus mutual exclusion is enforced among tasks using a monitor. Processes that attempt
    monitor entry while the monitor is occupied are blocked on a monitor entry queue.
    To synchronize tasks within the monitor, a condition variable is used to delay processes executing in a
    monitor. It may be declared only within a monitor and has no numeric value like semaphores do. Two
    operations wait and signal are defined on condition variables. The wait operation suspends/blocks execution
    of the calling process if a certain condition is true. Then the monitor is unlocked and allows another task to use
    the monitor. When the same condition becomes false, then the signal operation resumes execution of some
    process suspended after a wait on that condition, by placing it in the processor ready queue. If there are
    several such processes, choose one of them; if there are no waiting processes, the signal operator is ignored.
    Therefore, the introduction of condition variables allows more than one process to be in the same monitor at
    the same time, although only one of them will be actually active within that monitor.
    A condition variable is associated with a queue of the processes that are currently waiting on that condition.
    First-in-first-out (FIFO) discipline is generally used with queues, but priority queues can also be implemented
    by specifying the priority of the process to be delayed as a parameter in the wait operation. (Condition
    variables are assumed to be fair in the sense that a process will not remain suspended forever on a condition
    variable that is signaled infinitely often.) Therefore, monitors allow flexibility in scheduling of the processes
    waiting in queues.
    General Structure of a Monitor
    Note that a monitor is not a process, but a static module of data and procedure declarations. The actual
    processes which use the monitor need to be programmed separately.
    Message Passing
    Message passing is a type of communication between processes or objects in computer science. In this model,
    processes or objects can send and receive messages (signals, functions, complex data structures, or data
    packets) to other processes or objects.
    Definition
    Message passing is a form of communication between objects, processes or other resources used in object-
    oriented programming, inter-process communication and parallel computing. It can be synchronous or
    asynchronous. Synchronous message passing systems require the sender and receiver to wait for each other
    while transferring the message. In asynchronous communication the sender and receiver do not wait for each
    other and can carry on their own computations while transfer of messages is being done.
    The concept of message passing makes it easier to build systems that model or simulate real-world problems.
    Java Threads
    Java is a multi-threaded programming language which means we can develop multi-threaded program using
    Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle
    a different task at the same time making optimal use of the available resources especially when your computer
    has multiple CPUs.
    By definition, multitasking is when multiple processes share common processing resources such as a CPU.
    Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations
    within a single application into individual threads. Each of the threads can run in parallel. The OS divides
    processing time not only among different applications, but also among each thread within an application.
    Life Cycle of a Thread
    A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies.
    The following diagram shows the complete life cycle of a thread.
    Thread Priorities
    Every Java thread has a priority that helps the operating system determine the order in which threads are
    scheduled.
    Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant
    of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
    Threads with higher priority are more important to a program and should be allocated processor time before
    lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are
    very much platform dependent.
    Create a Thread by Implementing a Runnable Interface
    If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable
    interface. You will need to follow three basic steps −
    Step 1
    As a first step, you need to implement a run () method provided by a Runnable interface. This method provides
    an entry point for the thread and you will put your complete business logic inside this method. Following is a
    simple syntax of the run       ethod −
    public void run( )
    Step 2
    As a se o d step, ou ill i sta tiate a Thread o je t usi g the follo i g o stru tor −
    Thread (Runnable threadObj, String threadName);
    Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the
    name given to the new thread.
    Step 3
    Once a Thread object is created, you can start it by calling start() method, which executes a call to run( )
       ethod. Follo i g is a si ple s ta of start       ethod −
    void start();
    Example
    Here is a e a ple that reates a e thread a d starts ru i g it −
    class RunnableDemo implements Runnable {
      private Thread t;
      private String threadName;
    C# Thread
    A thread is defined as the execution path of a program. Each thread defines a unique flow of control. If your
    application involves complicated and time consuming operations, then it is often helpful to set different
    execution paths or threads, with each thread performing a particular job.
    Threads are lightweight processes. One common example of use of thread is implementation of concurrent
    programming by modern operating systems. Use of threads saves wastage of CPU cycle and increase
    efficiency of an application
    Thread Life Cycle
    The life cycle of a thread starts when an object of the System.Threading. Thread class is created and ends
    when the thread is terminated or completes execution.
    Follo i g are the arious states i the life   le of a thread −
         The Unstarted State − It is the situatio      he the i sta e of the thread is reated ut the “tart
             method is not called.
         The Ready State − It is the situatio   he the thread is read to ru and waiting CPU cycle.
         The Not Runnable State − A thread is ot e e uta le, he
                 o Sleep method has been called
                 o Wait method has been called
                 o Blocked by I/O operations
         The Dead State − It is the situatio  he the thread o pletes e e utio or is a orted.
    The Main Thread
    In C#, the System.Threading.Thread class is used for working with threads. It allows creating and accessing
    individual threads in a multithreaded application. The first thread to be executed in a process is called
    the main thread.
    When a C# program starts execution, the main thread is automatically created. The threads created using
    the Thread class are called the child threads of the main thread. You can access a thread using
    the CurrentThread property of the Thread class.
    The following program de o strates ai thread e e utio −
    using System;
    using System.Threading;
    namespace MultithreadingApplication {
     class MainThreadProgram {
       static void Main(string[] args) {
         Thread th = Thread.CurrentThread;
         th.Name = "MainThread";
                                                          Unit 5
    Exception Handling
    Exceptions - An exception (or exceptional event) is a problem that arises during the execution of a program.
    When an exception occurs the normal flow of the program is disrupted and the program/application
    terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.
    Exception Propagation
    An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the
    previous method, If not caught there, the exception again drops down to the previous method, and so on until
    they are caught or until they reach the very bottom of the call stack. This is called exception propagation.
    Example
    class ExceptionPropagation{
      void m(){
        int data = 10/0;
      }
      void n(){
        m();
      }
      void p(){
       try{
        n();
       }catch(Exception e){
         System.out.println("exception handled");
       }
      }
      public static void main(String args[]){
       ExceptionPropagation obj = new ExceptionPropagation();
       obj.p();
       System.out.println("normal flow...");
      }
    }
    Output:
     exception handled
      normal flow...
           Syntax
           try
       {
               statements;
               ... ... ...
               throw exception;
           }
    Multiple catch exception statements are used when a user wants to handle different exceptions differently. For
    this, a user must include catch statements with different declaration.
    Syntax
    try
    {
      body of try block
    }
      }
      catch (int e)
      {
        cout << "Exception: Division by zero";
      }
      catch (char st)
      {
        cout << "Exception: Division is less than 1";
      }
      catch(...)
      {
        cout << "Exception: Unknown";
      }
      getch();
      return 0;
    }
    This program demonstrates how exceptions are handled in C++. This program performs division operation. Two
    numbers are entered by user for division operation. If the dividend is zero, then division by zero will cause
    exception which is thrown into catch block. If the answer is less than 0, then exception "Division is less than 1"
    is thrown. All other exceptions are handled by the last catch block throwing "Unknown" exception.
    Output
    Enter 2 numbers: 8 5
    a/b = 1.6
    Enter 2 numbers: 9 0
    Exception: Division by zero
    Enter 2 numbers: -1 10
    Exception: Division is less than 1
    Throws/Throw Keywords
    If a method does not handle a checked exception, the method must declare it using the throws keyword. The
    throws keyword appears at the end of a method's signature.
    You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the
    throw keyword.
    throws is used to postpone the handling of a checked exception and throw is used to invoke an exception
    explicitly.
    The following method declares that it throws a RemoteException −
    Example
    import java.io.*;
    public class className {
    Finally Block
    The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of
    occurrence of an Exception.
    Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what
    happens in the protected code.
    A finally block appears at the end of the catch blocks and has the following syntax −
    Syntax
    try {
      // Protected code
    }catch(ExceptionType1 e1) {
      // Catch block
    }catch(ExceptionType2 e2) {
      // Catch block
    }catch(ExceptionType3 e3) {
      // Catch block
    }finally {
      // The finally block always executes.
    }
    Example
    public class ExcepTest {
      }
    }
    This will produce the following result −
    Output
    Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 3
    First element value: 6
    The finally statement is executed
    Logic Programming
    Logic programming is a computer programming paradigm in which program statements expresses facts and
    rules about problems within a system of formal logic. Rules are written as logical clauses with a head and a
    body; for instance, "H is true if B1, B2, and B3 are true." Facts are expressed similar to rules, but without a
    body; for instance, "H is true."
    Some logic programming languages such as Data log and Answer Set Programming (ASP) are purely declarative
    they allow for statements about what the program should accomplish, with no explicit step-by-step
    instructions about how to do so. Others, such as Prolog, are a combination of declarative and imperative —
         Like LISP, LP is about manipulation of symbols, and thus has potential in AI applications.
            specification.
    Prolog consists of a series of rules and facts. A program is run by presenting some query and seeing if this can
    be proved against these known rules and facts.
    Simple Facts
    In Prolog we can make some statements by using facts. Facts either consist of a particular item or a relation
    between items. For example we can represent the fact that it is sunny by writing the program:
    sunny.
    We can now ask a query of Prolog by asking
    ?- sunny.
    ?- is the Prolog prompt. To this query, Prolog will answer yes. sunny is true because (from above) Prolog
    matches it in its database of facts.
    Facts have some simple rules of syntax. Facts should always begin with a lowercase letter and end with a full
    stop. The facts themselves can consist of any letter or number combination, as well as the underscore _
    character. However, names containing the characters -,+,*,/, or other mathematical operators should be
    avoided.
    Examples of Simple Facts
    Here are some simple facts about an imaginary world. /* and */ are comment delimiters
    john_is_cold.                   /* john is cold */
    raining.                    /* it is raining */
    john_Forgot_His_Raincoat.                /* john forgot his raincoat */
    Rule Statements
    • Used for the hypotheses
    • Headed Horn clause
    • Right side: antecedent (if part)
        – May be single term or conjunction
    • Left side: consequent (then part)
          – Must be single term
    • Conjunction: multiple terms separated by logical AND operations (implied)
    Example Rules
    Ancestor (mary,shelley):- mother(mary,shelley).
    • Can use variables (universal objects) to generalize meaning:
    parent(X,Y):- mother(X,Y).
     parent(X,Y):- father(X,Y).
     grandparent(X,Z):- parent(X,Y), parent(Y,Z).
     sibling(X,Y):- mother(M,X), mother(M,Y),
     father(F,X), father(F,Y).
     Functional programming languages are specially designed to handle symbolic computation and list processing
     applications. Functional programming is based on mathematical functions. Some of the popular functional
     programming languages include: LISP, Python etc. Functional programming languages are categorized into two
     groups, i.e. −
         Pure Functional Languages − These t pes of fu tio al la guages support o l the fu tio al
           paradig s. For e a ple − Haskell.
         Impure Functional Languages − These t pes of fu tio al languages support the functional paradigms
           a d i perati e st le progra  i g. For e a ple − LISP.
       •   Referential Transparency - In an FPL, the evaluation of a function always produces the same result given
           the same parameters.
    Introduction to 4GL
    A fourth-generation programming language (4GL) is any computer programming language that belongs to a
    class of languages envisioned as advancement upon third-generation programming languages (3GL). Each of
    the programming language generations aims to provide a higher level of abstraction of the internal computer
    hardware details, making the language more programmer-friendly, powerful and versatile. While the definition
    of 4GL has changed over time, it can be typified by operating more with large collections of information at
    once rather than focusing on just bits and bytes. Languages claimed to be 4GL may include support for
    database management, report generation, mathematical optimization, GUI development, or web
    development. Some researchers state that 4GLs are a subset of domain-specific languages
    Advantages of 4GL
       1. Programming productivity is increased. One line of 4GL code is equivalent to several lines of 3GL code.
       2. System development is faster.
       3. Program maintenance is easier.
       4. The finished system is more likely to be what the user envisaged, if a prototype is used and the user is
          involved throughout the development.
       5. End user can often develop their own applications.
       6. Programs developed in 4GLs are more portable than those developed in other generation of languages.
       7. Documentation is improved because many 4GLs are self documenting.
    Disadvantages of 4GL
       1. The programs developed in the 4GLs are executed at a slower speed by the CPU.
       2. The programs developed in these programming languages need more space in the memory of the
          computer system.