Author: Saim Khalid

  • Environment

    This chapter discusses setting up the execution environment for Dart on the Windows platform.

    Executing Script Online with DartPad

    You may test your scripts online by using the online editor at https://dartpad.dev/. The Dart Editor executes the script and displays both HTML as well as console output. The online editor is shipped with a set of preset code samples.

    A screenshot of the Dartpad editor is given below −

    Dartpad

    Dartpad also enables to code in a more restrictive fashion. This can be achieved by checking the Strong mode option on the bottom right of the editor. Strong mode helps with −

    • Stronger static and dynamic checking
    • Idiomatic JavaScript code generation for better interoperability.

    You may try the following example using Dartpad

    void main() { 
       print('hello world'); 
    }

    The code will display the following output

    hello world
    

    Setting Up the Local Environment

    In this section, let us see how to set up the local environment.

    Using the Text Editor

    Examples of a few editors include Windows Notepad, Notepad++, Emacs, vim or vi, etc. Editors may vary from one Operating System to another. The source files are typically named with the extension “.dart”.

    Installing the Dart SDK

    The current stable version of Dart is 1.21.0. The dart sdk can be downloaded from −

    • https://www.dartlang.org/install/archive
    • http://www.gekorm.com/dart-windows/

    A screenshot of the Dart SDK installation is given below −

    Dart Installation

    On completion of the SDK installation, set the PATH environment variable to −

    <dart-sdk-path>\bin 
    

    Verifying the Installation

    To verify if Dart has been successfully installed, open the command prompt and enter the following command −

    Dart 
    

    If installation is successful, it will show the dart runtime.

    IDE Support

    A plethora of IDEs support scripting in Dart. Examples include Eclipse, IntelliJ, and WebStorm from Jet brains.

    Given below are the steps for configuring the Dart environment using WebStrom IDE.

    Installing WebStorm

    The installation file for WebStorm can be downloaded from https://www.jetbrains.com/webstorm/download/#section=windows-version.

    The WebStorm installation file is available for Mac OS, Windows and Linux.

    After downloading the installation files, follow the steps given below −

    • Install the Dart SDK: Refer to the steps listed above
    • Create a new Dart project and configure Dart support
    • To create a new Dart project,
      • Click Create New Project from the Welcome Screen
      • In the next dialog box, click Dart
    • If there is no value specified for the Dart SDK path, then provide the SDK path. For example, the SDK path may be <dart installation directory>/dart/dartsdk.

    Add a Dart File to the Project

    To add a Dart file to the Project −

    • Right-click on the Project
    • New → Dart File
    • Enter the name of the Dart Script

    A screenshot of the WebStorm Editor is given below −

    Dart File

    The dart2js Tool

    The dart2js tool compiles Dart code to JavaScript. Compiling Dart code to JS enables running the Dart script on browsers that do not support the Dart VM.

    The dart2js tool is shipped as a part of the Dart SDK and can be found in the /dartsdk/bin folder.

    To compile Dart to JavaScript, type the following command in the terminal

    dart2js - - out = <output_file>.js  <dart_script>.dart
    

    This command produces a file that contains the JavaScript equivalent of your Dart code. A complete tutorial on using this utility can be found on the official Dart website.

  • Environment

    In order to run Elixir, you need to set it up locally on your system.

    To install Elixir, you will first require Erlang. On some platforms, Elixir packages come with Erlang in them.

    Installing Elixir

    Let us now understand the installation of Elixir in different Operating Systems.

    Windows Setup

    To install Elixir on windows, download installer from https://elixir-lang.org/install.html#windows and simply click Next to proceed through all steps. You will have it on your local system.

    If you have any problems while installing it, you can check this page for more info.

    Mac Setup

    If you have Homebrew installed, make sure that it is the latest version. For updating, use the following command −

    brew update
    

    Now, install Elixir using the command given below −

    brew install elixir
    

    Ubuntu/Debian Setup

    The steps to install Elixir in an Ubuntu/Debian setup is as follows −

    Add Erlang Solutions repo −

    wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb && sudo 
    dpkg -i erlang-solutions_1.0_all.deb 
    sudo apt-get update 
    

    Install the Erlang/OTP platform and all of its applications −

    sudo apt-get install esl-erlang 
    

    Install Elixir −

    sudo apt-get install elixir
    

    Other Linux Distros

    If you have any other Linux distribution, please visit this page to set up elixir on your local system.

    Testing the Setup

    To test the Elixir setup on your system, open your terminal and enter iex in it. It will open the interactive elixir shell like the following −

    Erlang/OTP 19 [erts-8.0] [source-6dc93c1] [64-bit] 
    [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]  
    
    Interactive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help) 
    iex(1)>
    

    Elixir is now successfully set up on your system.

  • Overview

    Dart is an object-oriented language with C-style syntax which can optionally trans compile into JavaScript. It supports a varied range of programming aids like interfaces, classes, collections, generics, and optional typing.

    Dart can be extensively used to create single-page applications. Single-page applications apply only to websites and web applications. Single-page applications enable navigation between different screens of the website without loading a different webpage in the browser. A classic example is GMail ─ when you click on a message in your inbox, browser stays on the same webpage, but JavaScript code hides the inbox and brings the message body on screen.

    Google has released a special build of Chromium – the Dart VM. Using Dartium means you don’t have to compile your code to JavaScript until you’re ready to test on other browsers.

    The following table compares the features of Dart and JavaScript.

    FeatureDartJavaScript
    Type systemOptional, dynamicWeak, dynamic
    ClassesYes, single inheritancePrototypical
    InterfacesYes, multiple interfacesNo
    ConcurrencyYes, with isolatesYes, with HTML5 web workers

    This tutorial provides a basic level understanding of the Dart programming language.

  • Overview

    Elixir is a dynamic, functional language designed for building scalable and maintainable applications. It leverages the Erlang VM, known for running low-latency, distributed and fault-tolerant systems, while also being successfully used in web development and the embedded software domain.

    Elixir is a functional, dynamic language built on top of Erlang and the Erlang VM. Erlang is a language that was originally written in 1986 by Ericsson to help solve telephony problems like distribution, fault-tolerance, and concurrency. Elixir, written by José Valim, extends Erlang and provides a friendlier syntax into the Erlang VM. It does this while keeping the performance of the same level as Erlang.

    Features of Elixir

    Let us now discuss a few important features of Elixir −

    • Scalability − All Elixir code runs inside lightweight processes that are isolated and exchange information via messages.
    • Fault Tolerance − Elixir provides supervisors which describe how to restart parts of your system when things go wrong, going back to a known initial state that is guaranteed to work. This ensures your application/platform is never down.
    • Functional Programming − Functional programming promotes a coding style that helps developers write code that is short, fast, and maintainable.
    • Build tools − Elixir ships with a set of development tools. Mix is one such tool that makes it easy to create projects, manage tasks, run tests, etc. It also has its own package manager − Hex.
    • Erlang Compatibility − Elixir runs on the Erlang VM giving developers complete access to Erlang’s ecosystem.
  • C++ Data Structures

    C/C++ arrays allow you to define variables that combine several data items of the same kind, but structure is another user defined data type which allows you to combine data items of different kinds.

    Structures are used to represent a record, suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −

    • Title
    • Author
    • Subject
    • Book ID

    Defining a Structure

    To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member, for your program. The format of the struct statement is this −

    struct [structure tag] {
       member definition;
       member definition;
       ...
       member definition;
    } [one or more structure variables];  
    

    The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure’s definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure −

    struct Books {
       char  title[50];
       char  author[50];
       char  subject[100];
       int   book_id;
    } book;  
    

    Accessing Structure Members

    To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. Following is the example to explain usage of structure −

    #include <iostream>
    #include <cstring>
     
    using namespace std;
     
    struct Books {
       char  title[50];
       char  author[50];
       char  subject[100];
       int   book_id;
    };
     
    int main() {
       struct Books Book1;        // Declare Book1 of type Book
       struct Books Book2;        // Declare Book2 of type Book
     
       // book 1 specification
       strcpy( Book1.title, "Learn C++ Programming");
       strcpy( Book1.author, "Chand Miyan"); 
       strcpy( Book1.subject, "C++ Programming");
       Book1.book_id = 6495407;
    
       // book 2 specification
       strcpy( Book2.title, "Telecom Billing");
       strcpy( Book2.author, "Yakit Singha");
       strcpy( Book2.subject, "Telecom");
       Book2.book_id = 6495700;
     
       // Print Book1 info
       cout << "Book 1 title : " << Book1.title <<endl;
       cout << "Book 1 author : " << Book1.author <<endl;
       cout << "Book 1 subject : " << Book1.subject <<endl;
       cout << "Book 1 id : " << Book1.book_id <<endl;
    
       // Print Book2 info
       cout << "Book 2 title : " << Book2.title <<endl;
       cout << "Book 2 author : " << Book2.author <<endl;
       cout << "Book 2 subject : " << Book2.subject <<endl;
       cout << "Book 2 id : " << Book2.book_id <<endl;
    
       return 0;
    }

    When the above code is compiled and executed, it produces the following result −

    Book 1 title : Learn C++ Programming
    Book 1 author : Chand Miyan
    Book 1 subject : C++ Programming
    Book 1 id : 6495407
    Book 2 title : Telecom Billing
    Book 2 author : Yakit Singha
    Book 2 subject : Telecom
    Book 2 id : 6495700
    

    Structures as Function Arguments

    You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the similar way as you have accessed in the above example −

    #include <iostream>
    #include <cstring>
     
    using namespace std;
    void printBook( struct Books book );
    
    struct Books {
       char  title[50];
       char  author[50];
       char  subject[100];
       int   book_id;
    };
     
    int main() {
       struct Books Book1;        // Declare Book1 of type Book
       struct Books Book2;        // Declare Book2 of type Book
     
       // book 1 specification
       strcpy( Book1.title, "Learn C++ Programming");
       strcpy( Book1.author, "Chand Miyan"); 
       strcpy( Book1.subject, "C++ Programming");
       Book1.book_id = 6495407;
    
       // book 2 specification
       strcpy( Book2.title, "Telecom Billing");
       strcpy( Book2.author, "Yakit Singha");
       strcpy( Book2.subject, "Telecom");
       Book2.book_id = 6495700;
     
       // Print Book1 info
       printBook( Book1 );
    
       // Print Book2 info
       printBook( Book2 );
    
       return 0;
    }
    void printBook( struct Books book ) {
       cout << "Book title : " << book.title <<endl;
       cout << "Book author : " << book.author <<endl;
       cout << "Book subject : " << book.subject <<endl;
       cout << "Book id : " << book.book_id <<endl;
    }

    When the above code is compiled and executed, it produces the following result −

    Book title : Learn C++ Programming
    Book author : Chand Miyan
    Book subject : C++ Programming
    Book id : 6495407
    Book title : Telecom Billing
    Book author : Yakit Singha
    Book subject : Telecom
    Book id : 6495700
    

    Pointers to Structures

    You can define pointers to structures in very similar way as you define pointer to any other variable as follows −

    struct Books *struct_pointer;
    

    Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the & operator before the structure’s name as follows −

    struct_pointer = &Book1;
    

    To access the members of a structure using a pointer to that structure, you must use the -> operator as follows −

    struct_pointer->title;
    

    Let us re-write above example using structure pointer, hope this will be easy for you to understand the concept −

    #include <iostream>
    #include <cstring>
     
    using namespace std;
    void printBook( struct Books *book );
    
    struct Books {
       char  title[50];
       char  author[50];
       char  subject[100];
       int   book_id;
    };
    int main() {
       struct Books Book1;        // Declare Book1 of type Book
       struct Books Book2;        // Declare Book2 of type Book
     
       // Book 1 specification
       strcpy( Book1.title, "Learn C++ Programming");
       strcpy( Book1.author, "Chand Miyan"); 
       strcpy( Book1.subject, "C++ Programming");
       Book1.book_id = 6495407;
    
       // Book 2 specification
       strcpy( Book2.title, "Telecom Billing");
       strcpy( Book2.author, "Yakit Singha");
       strcpy( Book2.subject, "Telecom");
       Book2.book_id = 6495700;
     
       // Print Book1 info, passing address of structure
       printBook( &Book1 );
    
       // Print Book1 info, passing address of structure
       printBook( &Book2 );
    
       return 0;
    }
    
    // This function accept pointer to structure as parameter.
    void printBook( struct Books *book ) {
       cout << "Book title : " << book->title <<endl;
       cout << "Book author : " << book->author <<endl;
       cout << "Book subject : " << book->subject <<endl;
       cout << "Book id : " << book->book_id <<endl;
    }

    When the above code is compiled and executed, it produces the following result −

    Book title : Learn C++ Programming
    Book author : Chand Miyan
    Book subject : C++ Programming
    Book id : 6495407
    Book title : Telecom Billing
    Book author : Yakit Singha
    Book subject : Telecom
    Book id : 6495700
    

    The typedef Keyword

    There is an easier way to define structs or you could “alias” types you create. For example −

    typedef struct {
       char  title[50];
       char  author[50];
       char  subject[100];
       int   book_id;
    } Books;
    

    Now, you can use Books directly to define variables of Books type without using struct keyword. Following is the example −

    Books Book1, Book2;
    

    You can use typedef keyword for non-structs as well as follows −

    typedef long int *pint32;
     
    pint32 x, y, z;
    

    x, y and z are all pointers to long ints.

  • C++ Basic Input/Output

    The C++ standard libraries provide an extensive set of input/output capabilities which we will see in subsequent chapters. This chapter will discuss very basic and most common I/O operations required for C++ programming.

    C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called input operation and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc., this is called output operation.

    I/O Library Header Files

    There are following header files important to C++ programs −

    Sr.NoHeader File & Function and Description
    1<iostream>This file defines the cin, cout, cerr and clog objects, which correspond to the standard input stream, the standard output stream, the un-buffered standard error stream and the buffered standard error stream, respectively.
    2<iomanip>This file declares services useful for performing formatted I/O with so-called parameterized stream manipulators, such as setw and setprecision.
    3<fstream>This file declares services for user-controlled file processing. We will discuss about it in detail in File and Stream related chapter.

    The Standard Output Stream (cout)

    The predefined object cout is an instance of ostream class. The cout object is said to be “connected to” the standard output device, which usually is the display screen. The cout is used in conjunction with the stream insertion operator, which is written as << which are two less than signs as shown in the following example.

    #include <iostream>
     
    using namespace std;
     
    int main() {
       char str[] = "Hello C++";
     
       cout << "Value of str is : " << str << endl;
    }

    When the above code is compiled and executed, it produces the following result −

    Value of str is : Hello C++
    

    The C++ compiler also determines the data type of variable to be output and selects the appropriate stream insertion operator to display the value. The << operator is overloaded to output data items of built-in types integer, float, double, strings and pointer values.

    The insertion operator << may be used more than once in a single statement as shown above and endl is used to add a new-line at the end of the line.

    The Standard Input Stream (cin)

    The predefined object cin is an instance of istream class. The cin object is said to be attached to the standard input device, which usually is the keyboard. The cin is used in conjunction with the stream extraction operator, which is written as >> which are two greater than signs as shown in the following example.

    #include <iostream>
     
    using namespace std;
     
    int main() {
       char name[50];
     
       cout << "Please enter your name: ";
       cin >> name;
       cout << "Your name is: " << name << endl;
     
    }

    When the above code is compiled and executed, it will prompt you to enter a name. You enter a value and then hit enter to see the following result −

    Please enter your name: cplusplus
    Your name is: cplusplus
    

    The C++ compiler also determines the data type of the entered value and selects the appropriate stream extraction operator to extract the value and store it in the given variables.

    The stream extraction operator >> may be used more than once in a single statement. To request more than one datum you can use the following −

    cin >> name >> age;
    

    This will be equivalent to the following two statements −

    cin >> name;
    cin >> age;
    

    The Standard Error Stream (cerr)

    The predefined object cerr is an instance of ostream class. The cerr object is said to be attached to the standard error device, which is also a display screen but the object cerr is un-buffered and each stream insertion to cerr causes its output to appear immediately.

    The cerr is also used in conjunction with the stream insertion operator as shown in the following example.

    #include <iostream>
     
    using namespace std;
     
    int main() {
       char str[] = "Unable to read....";
     
       cerr << "Error message : " << str << endl;
    }

    When the above code is compiled and executed, it produces the following result −

    Error message : Unable to read....
    

    The Standard Log Stream (clog)

    The predefined object clog is an instance of ostream class. The clog object is said to be attached to the standard error device, which is also a display screen but the object clog is buffered. This means that each insertion to clog could cause its output to be held in a buffer until the buffer is filled or until the buffer is flushed.

    The clog is also used in conjunction with the stream insertion operator as shown in the following example.

    #include <iostream>
     
    using namespace std;
     
    int main() {
       char str[] = "Unable to read....";
     
       clog << "Error message : " << str << endl;
    }

    When the above code is compiled and executed, it produces the following result −

    Error message : Unable to read....
    

    You would not be able to see any difference in cout, cerr and clog with these small examples, but while writing and executing big programs the difference becomes obvious. So it is good practice to display error messages using cerr stream and while displaying other log messages then clog should be used.

  • C++ Date and Time

    The C++ standard library does not provide a proper date type. C++ inherits the structs and functions for date and time manipulation from C. To access date and time related functions and structures, you would need to include <ctime> header file in your C++ program.

    There are four time-related types: clock_t, time_t, size_t, and tm. The types – clock_t, size_t and time_t are capable of representing the system time and date as some sort of integer.

    The structure type tm holds the date and time in the form of a C structure having the following elements −

    struct tm {
       int tm_sec;   // seconds of minutes from 0 to 61
       int tm_min;   // minutes of hour from 0 to 59
       int tm_hour;  // hours of day from 0 to 24
       int tm_mday;  // day of month from 1 to 31
       int tm_mon;   // month of year from 0 to 11
       int tm_year;  // year since 1900
       int tm_wday;  // days since sunday
       int tm_yday;  // days since January 1st
       int tm_isdst; // hours of daylight savings time
    }
    

    Following are the important functions, which we use while working with date and time in C or C++. All these functions are part of standard C and C++ library and you can check their detail using reference to C++ standard library given below.

    Sr.NoFunction & Purpose
    1time_t time(time_t *time);This returns the current calendar time of the system in number of seconds elapsed since January 1, 1970. If the system has no time, .1 is returned.
    2char *ctime(const time_t *time);This returns a pointer to a string of the form day month year hours:minutes:seconds year\n\0.
    3struct tm *localtime(const time_t *time);This returns a pointer to the tm structure representing local time.
    4clock_t clock(void);This returns a value that approximates the amount of time the calling program has been running. A value of .1 is returned if the time is not available.
    5char * asctime ( const struct tm * time );This returns a pointer to a string that contains the information stored in the structure pointed to by time converted into the form: day month date hours:minutes:seconds year\n\0
    6struct tm *gmtime(const time_t *time);This returns a pointer to the time in the form of a tm structure. The time is represented in Coordinated Universal Time (UTC), which is essentially Greenwich Mean Time (GMT).
    7time_t mktime(struct tm *time);This returns the calendar-time equivalent of the time found in the structure pointed to by time.
    8double difftime ( time_t time2, time_t time1 );This function calculates the difference in seconds between time1 and time2.
    9size_t strftime();This function can be used to format date and time in a specific format.

    Current Date and Time

    Suppose you want to retrieve the current system date and time, either as a local time or as a Coordinated Universal Time (UTC). Following is the example to achieve the same −

    #include <iostream>
    #include <ctime>
    
    using namespace std;
    
    int main() {
       // current date/time based on current system
       time_t now = time(0);
       
       // convert now to string form
       char* dt = ctime(&now);
    
       cout << "The local date and time is: " << dt << endl;
    
       // convert now to tm struct for UTC
       tm *gmtm = gmtime(&now);
       dt = asctime(gmtm);
       cout << "The UTC date and time is:"<< dt << endl;
    }

    When the above code is compiled and executed, it produces the following result −

    The local date and time is: Sat Jan  8 20:07:41 2011
    
    The UTC date and time is:Sun Jan  9 03:07:41 2011
    

    Format Time using struct tm

    The tm structure is very important while working with date and time in either C or C++. This structure holds the date and time in the form of a C structure as mentioned above. Most of the time related functions makes use of tm structure. Following is an example which makes use of various date and time related functions and tm structure −

    While using structure in this chapter, I’m making an assumption that you have basic understanding on C structure and how to access structure members using arrow -> operator.

    #include <iostream>
    #include <ctime>
    
    using namespace std;
    
    int main() {
       // current date/time based on current system
       time_t now = time(0);
    
       cout << "Number of sec since January 1,1970 is:: " << now << endl;
    
       tm *ltm = localtime(&now);
    
       // print various components of tm structure.
       cout << "Year:" << 1900 + ltm->tm_year<<endl;
       cout << "Month: "<< 1 + ltm->tm_mon<< endl;
       cout << "Day: "<< ltm->tm_mday << endl;
       cout << "Time: "<< 5+ltm->tm_hour << ":";
       cout << 30+ltm->tm_min << ":";
       cout << ltm->tm_sec << endl;
    }

    When the above code is compiled and executed, it produces the following result −

    Number of sec since January 1,1970 is:: 1588485717
    Year:2020
    Month: 5
    Day: 3
    Time: 11:31:57
    
  • Database Interface

    As of now, we have learnt the use of files in COBOL. Now, we will discuss how a COBOL program interacts with DB2. It involves the following terms −

    • Embedded SQL
    • DB2 Application Programming
    • Host Variables
    • SQLCA
    • SQL Queries
    • Cursors

    Embedded SQL

    Embedded SQL statements are used in COBOL programs to perform standard SQL operations. Embedded SQL statements are preprocessed by the SQL processor before the application program is compiled. COBOL is known as the Host Language. COBOL-DB2 applications are those applications that include both COBOL and DB2.

    Embedded SQL statements work like normal SQL statements with some minor changes. For example, the output of a query is directed to a predefined set of variables which are referred as Host Variables. An additional INTO clause is placed in the SELECT statement.

    DB2 Application Programming

    Following are rules to be followed while coding a COBOL-DB2 program −

    • All the SQL statements must be delimited between EXEC SQL and ENDEXEC..
    • SQL statements must be coded in Area B.
    • All the tables that are used in a program must be declared in the WorkingStorage Section. This is done by using the INCLUDE statement.
    • All SQL statements other than INCLUDE and DECLARE TABLE must appear in the Procedure Division.

    Host Variables

    Host variables are used for receiving data from a table or inserting data in a table. Host variables must be declared for all values that are to be passed between the program and the DB2. They are declared in the Working-Storage Section.

    Host variables cannot be group items, but they may be grouped together in host structure. They cannot be Renamed or Redefined. Using host variables with SQL statements, prefix them with a colon (:)..

    Syntax

    Following is the syntax to declare host variables and include tables in the Working-Storage section −

    DATA DIVISION.
       WORKING-STORAGE SECTION.
       
       EXEC SQL
       INCLUDE table-name
       END-EXEC.
    
       EXEC SQL BEGIN DECLARE SECTION
       END-EXEC.
       
       01 STUDENT-REC.
    
      05 STUDENT-ID PIC 9(4).
      05 STUDENT-NAME PIC X(25).
      05 STUDENT-ADDRESS X(50).
    EXEC SQL END DECLARE SECTION END-EXEC.

    SQLCA

    SQLCA is a SQL communication area through which DB2 passes the feedback of SQL execution to the program. It tells the program whether an execution was successful or not. There are a number of predefined variables under SQLCA like SQLCODE which contains the error code. The value ‘000’ in SQLCODE states a successful execution.

    Syntax

    Following is the syntax to declare an SQLCA in the Working-Storage section −

    DATA DIVISION.
    WORKING-STORAGE SECTION.
    	EXEC SQL
    	INCLUDE SQLCA
    	END-EXEC.
    

    SQL Queries

    Let’s assume we have one table named as ‘Student’ that contains Student-Id, Student-Name, and Student-Address.

    The STUDENT table contains the following data −

    Student Id		Student Name		Student Address
    1001 			   Mohtashim M.		Hyderabad
    1002			   Nishant Malik		Delhi
    1003 			   Amitabh Bachan		Mumbai
    1004			   Chulbul Pandey		Lucknow
    

    The following example shows the usage of SELECT query in a COBOL program −

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    
    DATA DIVISION.
       WORKING-STORAGE SECTION.
       EXEC SQL
    
      INCLUDE SQLCA
    END-EXEC. EXEC SQL
      INCLUDE STUDENT
    END-EXEC. EXEC SQL BEGIN DECLARE SECTION END-EXEC.
      01 WS-STUDENT-REC.
         05 WS-STUDENT-ID PIC 9(4).
         05 WS-STUDENT-NAME PIC X(25).
         05 WS-STUDENT-ADDRESS X(50).
    EXEC SQL END DECLARE SECTION END-EXEC. PROCEDURE DIVISION. EXEC SQL
      SELECT STUDENT-ID, STUDENT-NAME, STUDENT-ADDRESS
      INTO :WS-STUDENT-ID, :WS-STUDENT-NAME, WS-STUDENT-ADDRESS FROM STUDENT
      WHERE STUDENT-ID=1004
    END-EXEC. IF SQLCODE = 0
      DISPLAY WS-STUDENT-RECORD
    ELSE DISPLAY 'Error' END-IF. STOP RUN.

    JCL to execute the above COBOL program −

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP001  EXEC PGM = IKJEFT01
    //STEPLIB  DD DSN = MYDATA.URMI.DBRMLIB,DISP = SHR
    //SYSPRINT DD SYSOUT=*
    //SYSUDUMP DD SYSOUT=*
    //SYSOUT   DD SYSOUT=*
    //SYSTSIN  DD *
       DSN SYSTEM(SSID)
       RUN PROGRAM(HELLO) PLAN(PLANNAME) -
       END
    /*

    When you compile and execute the above program, it produces the following result −

    1004 Chulbul Pandey		Lucknow
    

    The following example shows the usage of INSERT query in a COBOL program −

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    
    DATA DIVISION.
       WORKING-STORAGE SECTION.
       EXEC SQL
       INCLUDE SQLCA
       END-EXEC.
       
       EXEC SQL
       INCLUDE STUDENT
       END-EXEC.
       
       EXEC SQL BEGIN DECLARE SECTION
       END-EXEC.
    
      01 WS-STUDENT-REC.
         05 WS-STUDENT-ID PIC 9(4).
         05 WS-STUDENT-NAME PIC X(25).
         05 WS-STUDENT-ADDRESS X(50).
    EXEC SQL END DECLARE SECTION END-EXEC. PROCEDURE DIVISION. MOVE 1005 TO WS-STUDENT-ID. MOVE 'TutorialsPoint' TO WS-STUDENT-NAME. MOVE 'Hyderabad' TO WS-STUDENT-ADDRESS. EXEC SQL
      INSERT INTO STUDENT(STUDENT-ID, STUDENT-NAME, STUDENT-ADDRESS)
      VALUES (:WS-STUDENT-ID, :WS-STUDENT-NAME, WS-STUDENT-ADDRESS)
    END-EXEC. IF SQLCODE = 0
      DISPLAY 'Record Inserted Successfully'
      DISPLAY WS-STUDENT-REC
    ELSE DISPLAY 'Error' END-IF. STOP RUN.

    JCL to execute the above COBOL program −

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP001  EXEC PGM = IKJEFT01
    //STEPLIB  DD DSN = MYDATA.URMI.DBRMLIB,DISP=SHR
    //SYSPRINT DD SYSOUT = *
    //SYSUDUMP DD SYSOUT = *
    //SYSOUT   DD SYSOUT = *
    //SYSTSIN  DD *
       DSN SYSTEM(SSID)
       RUN PROGRAM(HELLO) PLAN(PLANNAME) -
       END
    /*

    When you compile and execute the above program, it produces the following result −

    Record Inserted Successfully
    1005 TutorialsPoint		Hyderabad
    

    The following example shows the usage of UPDATE query in a COBOL program −

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    
    DATA DIVISION.
       WORKING-STORAGE SECTION.
       
       EXEC SQL
       INCLUDE SQLCA
       END-EXEC.
       
       EXEC SQL
       INCLUDE STUDENT
       END-EXEC.
       
       EXEC SQL BEGIN DECLARE SECTION
       END-EXEC.
    
      01 WS-STUDENT-REC.
         05 WS-STUDENT-ID PIC 9(4).
         05 WS-STUDENT-NAME PIC X(25).
         05 WS-STUDENT-ADDRESS X(50).
    EXEC SQL END DECLARE SECTION END-EXEC. PROCEDURE DIVISION. MOVE 'Bangalore' TO WS-STUDENT-ADDRESS. EXEC SQL
      UPDATE STUDENT SET STUDENT-ADDRESS=:WS-STUDENT-ADDRESS
      WHERE STUDENT-ID = 1003
    END-EXEC. IF SQLCODE = 0
      DISPLAY 'Record Updated Successfully'
    ELSE DISPLAY 'Error' END-IF. STOP RUN.

    JCL to execute the above COBOL program −

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP001  EXEC PGM = IKJEFT01
    //STEPLIB  DD DSN = MYDATA.URMI.DBRMLIB,DISP = SHR
    //SYSPRINT DD SYSOUT = *
    //SYSUDUMP DD SYSOUT = *
    //SYSOUT   DD SYSOUT = *
    //SYSTSIN  DD *
       DSN SYSTEM(SSID)
       RUN PROGRAM(HELLO) PLAN(PLANNAME) -
       END
    /*

    When you compile and execute the above program, it produces the following result −

    Record Updated Successfully
    

    The following example shows the usage of DELETE query in a COBOL program −

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    
    DATA DIVISION.
    WORKING-STORAGE SECTION.
    
       EXEC SQL
       INCLUDE SQLCA
       END-EXEC.
       
       EXEC SQL
       INCLUDE STUDENT
       END-EXEC.
       
       EXEC SQL BEGIN DECLARE SECTION
       END-EXEC.
    
      01 WS-STUDENT-REC.
         05 WS-STUDENT-ID PIC 9(4).
         05 WS-STUDENT-NAME PIC X(25).
         05 WS-STUDENT-ADDRESS X(50).
    EXEC SQL END DECLARE SECTION END-EXEC. PROCEDURE DIVISION. MOVE 1005 TO WS-STUDENT-ID. EXEC SQL
      DELETE FROM STUDENT
      WHERE STUDENT-ID=:WS-STUDENT-ID
    END-EXEC. IF SQLCODE = 0
      DISPLAY 'Record Deleted Successfully'
    ELSE DISPLAY 'Error' END-IF. STOP RUN.

    JCL to execute the above COBOL program −

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP001  EXEC PGM = IKJEFT01
    //STEPLIB  DD DSN = MYDATA.URMI.DBRMLIB,DISP=SHR
    //SYSPRINT DD SYSOUT = *
    //SYSUDUMP DD SYSOUT = *
    //SYSOUT   DD SYSOUT = *
    //SYSTSIN  DD *
       DSN SYSTEM(SSID)
       RUN PROGRAM(HELLO) PLAN(PLANNAME) -
       END
    /*

    When you compile and execute the above program, it produces the following result −

    Record Deleted Successfully
    

    Cursors

    Cursors are used to handle multiple row selections at a time. They are data structures that hold all the results of a query. They can be defined in the Working-Storage Section or the Procedure Division. Following are the operations associated with Cursor −

    • Declare
    • Open
    • Close
    • Fetch

    Declare Cursor

    Cursor declaration can be done in the Working-Storage Section or the Procedure Division. The first statement is the DECLARE statement which is a nonexecutable statement.

    EXEC SQL
       DECLARE STUDCUR CURSOR FOR
       SELECT STUDENT-ID, STUDENT-NAME, STUDENT-ADDRESS FROM STUDENT
       WHERE STUDENT-ID >:WS-STUDENT-ID
    END-EXEC.

    Open

    Before using a cursor, Open statement must be performed. The Open statement prepares the SELECT for execution.

    EXEC SQL
       OPEN STUDCUR
    END-EXEC.

    Close

    Close statement releases all the memory occupied by the cursor. It is mandatory to close a cursor before ending a program.

    EXEC SQL
       CLOSE STUDCUR
    END-EXEC.

    Fetch

    Fetch statement identifies the cursor and puts the value in the INTO clause. A Fetch statement is coded in loop as we get one row at a time.

    EXEC SQL
       FETCH STUDCUR
       INTO :WS-STUDENT-ID, :WS-STUDENT-NAME, WS-STUDENT-ADDRESS
    END-EXEC.

    The following example shows the usage of cursor to fetch all the records from the STUDENT table −

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    
    DATA DIVISION.
       WORKING-STORAGE SECTION.
       
       EXEC SQL
       INCLUDE SQLCA
       END-EXEC.
       
       EXEC SQL
       INCLUDE STUDENT
       END-EXEC.
       
       EXEC SQL BEGIN DECLARE SECTION
       END-EXEC.
    
      01 WS-STUDENT-REC.
         05 WS-STUDENT-ID PIC 9(4).
         05 WS-STUDENT-NAME PIC X(25).
         05 WS-STUDENT-ADDRESS X(50).
    EXEC SQL END DECLARE SECTION END-EXEC. EXEC SQL
      DECLARE STUDCUR CURSOR FOR
      SELECT STUDENT-ID, STUDENT-NAME, STUDENT-ADDRESS FROM STUDENT
      WHERE STUDENT-ID &gt;:WS-STUDENT-ID
    END-EXEC. PROCEDURE DIVISION. MOVE 1001 TO WS-STUDENT-ID. PERFORM UNTIL SQLCODE = 100 EXEC SQL
      FETCH STUDCUR
      INTO :WS-STUDENT-ID, :WS-STUDENT-NAME, WS-STUDENT-ADDRESS
    END-EXEC DISPLAY WS-STUDENT-REC END-PERFORM STOP RUN.

    JCL to execute the above COBOL program −

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP001  EXEC PGM=IKJEFT01
    //STEPLIB  DD DSN=MYDATA.URMI.DBRMLIB,DISP=SHR
    //SYSPRINT DD SYSOUT=*
    //SYSUDUMP DD SYSOUT=*
    //SYSOUT   DD SYSOUT=*
    //SYSTSIN  DD *
       DSN SYSTEM(SSID)
       RUN PROGRAM(HELLO) PLAN(PLANNAME) -
       END
    /*

    When you compile and execute the above program, it produces the following result −

    1001 Mohtashim M.		Hyderabad
    1002 Nishant Malik		Delhi
    1003 Amitabh Bachan		Mumbai
    1004 Chulbul Pandey		Lucknow
    
  • C++ References

    A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable.

    References vs Pointers

    References are often confused with pointers but three major differences between references and pointers are −

    • You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage.
    • Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time.
    • A reference must be initialized when it is created. Pointers can be initialized at any time.

    Creating References in C++

    Think of a variable name as a label attached to the variable’s location in memory. You can then think of a reference as a second label attached to that memory location. Therefore, you can access the contents of the variable through either the original variable name or the reference. For example, suppose we have the following example −

    int i = 17;
    

    We can declare reference variables for i as follows.

    int& r = i;
    

    Read the & in these declarations as reference. Thus, read the first declaration as “r is an integer reference initialized to i” and read the second declaration as “s is a double reference initialized to d.”. Following example makes use of references on int and double −

    #include <iostream>
     
    using namespace std;
     
    int main () {
       // declare simple variables
       int    i;
       double d;
     
       // declare reference variables
       int&    r = i;
       double& s = d;
       
       i = 5;
       cout << "Value of i : " << i << endl;
       cout << "Value of i reference : " << r  << endl;
     
       d = 11.7;
       cout << "Value of d : " << d << endl;
       cout << "Value of d reference : " << s  << endl;
       
       return 0;
    }

    When the above code is compiled together and executed, it produces the following result −

    Value of i : 5
    Value of i reference : 5
    Value of d : 11.7
    Value of d reference : 11.7
    

    References are usually used for function argument lists and function return values. So following are two important subjects related to C++ references which should be clear to a C++ programmer −

    Sr.NoConcept & Description
    1References as ParametersC++ supports passing references as function parameter more safely than parameters.
    2Reference as Return ValueYou can return reference from a C++ function like any other data type.
  • C++ Pointers

    C++ pointers are easy and fun to learn. Some C++ tasks are performed more easily with pointers, and other C++ tasks, such as dynamic memory allocation, cannot be performed without them.

    As you know every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator which denotes an address in memory. Consider the following which will print the address of the variables defined −

    #include <iostream>
    
    using namespace std;
    int main () {
       int  var1;
       char var2[10];
    
       cout << "Address of var1 variable: ";
       cout << &var1 << endl;
    
       cout << "Address of var2 variable: ";
       cout << &var2 << endl;
    
       return 0;
    }

    When the above code is compiled and executed, it produces the following result −

    Address of var1 variable: 0xbfebd5c0
    Address of var2 variable: 0xbfebd5b6
    

    What are Pointers?

    pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is −

    type *var-name;
    

    Here, type is the pointer’s base type; it must be a valid C++ type and var-name is the name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration −

    int    *ip;    // pointer to an integer
    double *dp;    // pointer to a double
    float  *fp;    // pointer to a float
    char   *ch     // pointer to character
    

    The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.

    Using Pointers in C++

    There are few important operations, which we will do with the pointers very frequently. (a) We define a pointer variable. (b) Assign the address of a variable to a pointer. (c) Finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations −

    #include <iostream>
    
    using namespace std;
    
    int main () {
       int  var = 20;   // actual variable declaration.
       int  *ip;        // pointer variable 
    
       ip = &var;       // store address of var in pointer variable
    
       cout << "Value of var variable: ";
       cout << var << endl;
    
       // print the address stored in ip pointer variable
       cout << "Address stored in ip variable: ";
       cout << ip << endl;
    
       // access the value at the address available in pointer
       cout << "Value of *ip variable: ";
       cout << *ip << endl;
    
       return 0;
    }

    When the above code is compiled and executed, it produces result something as follows −

    Value of var variable: 20
    Address stored in ip variable: 0xbfc601ac
    Value of *ip variable: 20
    

    Pointers in C++

    Pointers have many but easy concepts and they are very important to C++ programming. There are following few important pointer concepts which should be clear to a C++ programmer −

    Sr.NoConcept & Description
    1Null PointersC++ supports null pointer, which is a constant with a value of zero defined in several standard libraries.
    2Pointer ArithmeticThere are four arithmetic operators that can be used on pointers: ++, –, +, –
    3Pointers vs ArraysThere is a close relationship between pointers and arrays.
    4Array of PointersYou can define arrays to hold a number of pointers.
    5Pointer to PointerC++ allows you to have pointer on a pointer and so on.
    6Passing Pointers to FunctionsPassing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.
    7Return Pointer from FunctionsC++ allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well.