Thursday, October 16, 2014

C++ Programs



The OOP with C++ is an introductory course to C++ and the best efforts have been taken cover most of the topics specified in the VTU curriculum.

The Notes of OOP with C++ for III Semester CSE/ISE of VTU may refer to the following link:
In case of mistakes, the author (i.e. myself) doesn't take sole loss incurred by any individual after referring to the documents, it is only for academic purposes the notes have been typed and consolidated in its present form, the further versions may be soon released based on the feedback obtained. Thank you and All the Best !.


Mail to get the C++ Notes to:     rajkumar.manju@gmail.com
C++ Lab Programs



Design, develop, and execute a program in C++ to create a class called DATE with methods to accept two valid dates in the form dd/mm/yy and to implement the following operations by overloading the operators + and -. After every operation the results are to be displayed by overloading the operator <<.
i. no_of_days = d1 – d2; where d1 and d2 are DATE objects, d1 >=d2 and no_of_days is an integer.
ii. d2 = d1 + no_of_days; where d1 is a DATE object and no_of_days is an integer.
                   
 


#include < iostream.h >
#include < stdlib.h >
#include < conio.h >
class date{
  int dd,mm,yy;
public:
  int leap;
  date(){dd=0;mm=0;yy=0;}
  date(int d,int m, int y){
    dd=d; mm=m;  yy=y;
    if(y%4==0 || y%400==0 && y%100!=0)
       leap=1;
    else
       leap=0;

    if(!leap && m==2 && d>28)
     {
       cout<<"Non leap year can't have more than 28 days...\n!!!error";
       getch();
       exit(0);
     }
    if(m>13)
     {
       cout<<"Month can't be greater than 12...\n!!!error";
       getch();
       exit(0);
     }
    if(d>get_month_days(m))
     {
       cout<<"Number of days exceeds in the month...\n!!!error";
       getch();
       exit(0);
     }
  }
  date operator+(int days);
  int operator-(date d);
  int get_month_days(int month);
  friend ostream& operator<<(ostream &out, date &d);
};

date date::operator+(int days)
{
 int i;
 for(i=1;i<=days;i++)
 {
  dd++;
  if(dd>get_month_days(mm) && mm<13 br="">   {
     mm++;
     if (mm==13) {mm=1; yy++;}
     dd=1;
   }
 }
 return *this;
}

int date::operator-(date d2)
{
  int diff=0, mon_days,month;
  if(yy   {
    cout<<"Not possible to find the difference\nSecond date is greater\n";
    return -1;
   }
  int diff=0;
  while(dd!=d2.dd || mm!=d2.mm || yy!=d2.yy)
  {
   d2.dd++;
   if(d2.dd>get_month_days(d2.mm) && d2.mm<13 br="">    {
     d2.mm++;        //incr month if days crosses the no. of days of the month
     if (d2.mm==13) {d2.mm=1; d2.yy++;}   
     d2.dd=1;                //reset days to 1 on incrementing month
    }
    diff++;
   }
return diff;
}

int date::get_month_days(int month)
{  int days;
   switch (month)
   {
    case 1: case 3: case 5: case 7: case 8: case 10: case 12:days=31; break;

    case 2:if(yy%4==0 || yy%400==0 && yy%100!=0)
         days=29;
       else
         days=28;
       break;
    case 4: case 6: case 9: case 11:days=30; break;
   }
   return days;
}
ostream& operator<<(ostream& out,date &d)
{
 out< return out;
}

int main()
{
 int no_of_days=0;
 int days=0;
 int day,mon,year;
 clrscr();
 cout<<"\nEnter the two dates in the format (dd mm yyyy)";
 cout<<"\nEnter first date:";
 cin>>day>>mon>>year;
 date d1(day,mon,year);
 cout<<"\nEnter the second date(less than first date):";
 cin>>day>>mon>>year;
 date d2(day,mon,year);
 cout<<"\nThe dates are:";
 cout< cout< no_of_days=d1-d2;
 cout<<"\nThe difference is :"< cout<<"\nEnter the no. of days to be added:";
 cin>>days;
 d1=d1+days;
 cout<<"\nThe new date is:";
 cout< getch();
return 0;
}



/*Design, develop, and execute a program in C++ to create a class called OCTAL, which has the
characteristics of an octal number.
Implement the following operations by writing an appropriate constructor and an overloaded operator +.
i. OCTAL h = x ; where x is an integer
ii. int y = h + k ; where h is an OCTAL object and k is an integer.
Display the OCTAL result by overloading the operator <<. Also display the values of h and y.
*/
#include < iostream >
#include < cmath >
using namespace std;
class OCTAL{
    int oct;
    int dec;
public:
    OCTAL(){
        oct=0;
        dec=0;
    }
    OCTAL(int n){
        oct = decimal_oct(n);
    }
    int decimal_oct(int);
    int octal_decimal(int);
    int operator+(int);
    friend ostream & operator<<(ostream& out,OCTAL Oct);
};


int OCTAL::decimal_oct(int n)
{
 int rem, i=1, octal=0;
    while (n!=0)            //decimal to octal
    {
        rem=n%8;
        n/=8;
        octal+=rem*i;
        i*=10;
    }
   return octal;
}

int OCTAL::octal_decimal(int n) /* Function to convert octal to decimal */
{
    int decimal=0, i=0, rem;
    while (n!=0)
    {
        rem = n%10;
        n/=10;
        decimal += rem*pow(8,i);
        ++i;
    }
    return decimal;
}

int OCTAL :: operator+(int k)
{
    dec = octal_decimal(oct);
    return (dec+k);
}

ostream & operator <<(ostream &out, OCTAL O)
{
    out<    return out;
}
int main()
{
    int x,k,y;
    cout<<"\nEnter the value of x:";
    cin>>x;

    OCTAL h=x;  //invokes the single parameterized constructor
    cout<<"\nThe output of h=x in octal is:"<
    cout<<"\nEnter the value of k:";
    cin>>k;

    y=h+k;      //invokes the operator +() overloaded function
    cout<<"The output of y=h+k in octal is:"<
    return 0;
}






Design, develop, and execute a program in C++ to create a class called BIN_TREE that represents a Binary Tree, with member functions to perform inorder, preorder and postorder traversals. Create a BIN_TREE object and demonstrate the traversals.


#include < iostream >
#include < cstdlib >
using namespace std;
class TREE
{
 public:
    int data;
    TREE *left;
    TREE *right;
};
class BIN_TREE
{
    TREE *tree;
    public:
        BIN_TREE()
        {
            tree=NULL;
        }
        void insert(int);
        void inorder(TREE *tree);
        void preorder(TREE *tree);
        void postorder(TREE *tree);
        TREE *tree_ret()
        {
            return tree;
        }
};
void BIN_TREE::insert(int item)
{
    TREE *cur,*prev,*temp;
    temp=new TREE;
    temp->data=item;
    temp->left=temp->right=NULL;
    if(tree==NULL)
    tree=temp;
    else
    {
        prev=NULL;
        cur=tree;
        while(cur!=NULL)
        {
            prev=cur;
            if(item
< temp->data)
              cur=cur->left;
            else
              cur=cur->right;
        }
        if(item < temp->data)
          prev->left=temp;
        else
          prev->right=temp;
    }
}
void BIN_TREE::inorder(TREE *tree)
{
    TREE *temp;
    temp=tree;
    if(temp!=NULL)
    {
        inorder(temp->left);
        cout<data<<"\t";
        inorder(temp->right);
    }
}
void BIN_TREE::preorder(TREE *tree)
{
    TREE *temp;
    temp=tree;
    if(temp!=NULL)
    {
        cout<data<<"\t";
        preorder(temp->left);
        preorder(temp->right);
    }
}
void BIN_TREE::postorder(TREE *tree)
{
    TREE *temp;
    temp=tree;
    if(temp!=NULL)
    {
        postorder(temp->left);
        postorder(temp->right);
        cout<data<<"\t";
    }
}

int main()
{
    BIN_TREE BT;
    TREE *tree;
    int ch;
    int item;
    while(1)
    {
        cout<<"\n 1.insert \n 2.display \n3.exit";
        cout<<"\n enter the choice";
        cin>>ch;
        switch(ch)
        {
            case 1:
                cout<<"enter data to insert";
                cin>>item;
                BT.insert(item);
                break;
            case 2:
                cout<<"the contents of BT\n";
                cout<<"\ninorder\n";
                tree=BT.tree_ret();
                BT.inorder(tree);
                cout<<"\npreorder\n";
                tree=BT.tree_ret();
                BT.preorder(tree);
                cout<<"\npostorder\n";
                tree=BT.tree_ret();
                BT.postorder(tree) ;
            break;
            default:
                exit(0);
        }
    }
return 0;
}

Friday, January 29, 2010

EU clears Oracle's takeover of Sun



New York: The European Union's (EU) antitrust watchdog has approved the Sun-Oracle transaction last week saying the deal would not restrict competition in the database's market. In April last year, Oracle has agreed to buy Sun Microsystems for $7.4 billion or $9.50 a share in cash, reports PTI.

The approval from the EU came after months of investigation. Software major Oracle Corp has completed the takeover of hardware company Sun Microsystems for $7.4 billion. The deal, which was announced nine months ago, would transform the IT industry, Oracle said in a statement yesterday. The two companies, which have a significant presence in India, together employs more than 26,000 people in the country. Oracle has more than 25,000 employees in India, while Sun Microsystems has 1,200 people.

The Sun Solaris operating system is the leading platform for the Oracle database, Oracle's largest business. With the acquisition of Sun, Oracle can optimise Oracle database for some of the unique, high-end features of Solaris.

"With the addition of servers, storage, SPARC processors, the Solaris operating system, Java, and the MySQL database to Oracle's portfolio of database, middleware, and business applications, we plan to engineer and deliver open and integrated systems - from applications to disk - where all the pieces fit and work together out of the box," Oracle said.

Sunday, December 13, 2009

Database Management Systems

Hi all,
The main purpose of the blog is to create a lot of interests in the students to try and solve the problems involved in DBMS at undergraduate level as well post graduate

Monday, August 24, 2009

ORACLE CEO's Salary $1



Bangalore: Software giant Oracle has informed in a regulatory filing, to cut the salary of its Chief Executive Larry Ellison to $1 in fiscal 2010 as compared to $1 million in the previous year. But according to Forbes, he will still remain as the fourth richest person in the world.



"The compensation committee recognizes that Ellison has a significant equity interest in Oracle, but believes he should still receive annual compensation because he plays an active and vital role in our operations, strategy and growth. Nevertheless, during fiscal 2010, Ellison agreed to decrease his annual salary to $1," said the company in a filing.

The compensation packages of the CEO include a base salary, an annual cash bonus and stock options.

In fiscal year 2009, the bonus and stock options comprised 97 percent of Ellison's overall compensation. According to the company, only 1.2 percent was his base salary and 1.8 percent was other benefits,.

His new $1 base salary puts him with the likes of Apple CEO Steve Jobs and Google co-founders Sergey Brin and Larry Page, who also take home the same package.

Larry Ellison, 64, had founded Oracle in 1977, and according to the SEC filing, he owns 1.18 billion shares of Oracle, which is 23.4 percent of the company's total stock.

Wednesday, August 12, 2009

Detecting a Memory Leak

To detect a memory leak
1. Create a CMemoryState object and call the Checkpoint member function to get the initial snapshot of memory.

2. After you perform the memory allocation and deallocation operations, create another CMemoryState object and call Checkpoint for that object to get a current snapshot of memory usage.

3. Create a third CMemoryState object, call the Difference member function, and supply the previous two CMemoryState objects as arguments. The return value for the Difference function will be nonzero if there is any difference between the two specified memory states, indicating that some memory blocks have not been deallocated.
The following example shows how to check for memory leaks:
// Declare the variables needed
#ifdef _DEBUG
CMemoryState oldMemState, newMemState, diffMemState;
oldMemState.Checkpoint();
#endif
// do your memory allocations and deallocations...
CString s = "This is a frame variable";
// the next object is a heap object
CPerson* p = new CPerson( "Smith", "Alan", "581-0215" );
#ifdef _DEBUG newMemState.Checkpoint();
if( diffMemState.Difference( oldMemState, newMemState ) )
{
TRACE( "Memory leaked!\n" );
}
#endif
Notice that the memory-checking statements are bracketed by #ifdef _DEBUG / #endif
blocks so that they are compiled only in Win32 Debug versions of your program.
Courtesy: MSDN

Tuesday, April 07, 2009

Embedded SQL

Embedded SQL/Oracle Tutorial

Cursors

By now, if you have been following the tutorials closely, you should be quite familiar with inserting, updating, and deleting database records. The next step is to create querying functions (i.e., to handle SELECT operations).  We have intentionally left querying until last because there often are more steps to perform. Unlike the format of queries we typed into SQL*Plus, embedded SQL requires the use of cursors to successfully output the results of the query.

Cursors were invented to satisfy both the SQL and host programming languages. SQL queries handle sets of rows at a time, while C++, for example, handles only one row at a time. When we type the following SQL query into SQL*Plus:
 

SQL> select    driver_sin, count(exam_score)
   2 from      exam
   3 where     exam_type = 'L'
   4 group by  driver_sin;


we get the following output:

DRIVER_SIN COUNT(EXAM_SCORE)
---------- -----------------
 111111111                 1
 222222222                 2
 333333333                 3
 444444444                 1
In our embedded SQL code, we cannot simply specify:
 
EXEC SQL SELECT    driver_sin, count(exam_score)
         FROM      exam
         WHERE     exam_type = 'L'
         GROUP BY  driver_sin;


and expect C++ to output the results of the query. We have to fetch the results of this query into a cursor, and then output the results one at a time using C.

To use a cursor in embedded SQL, we must first declare it. We do this by using the DECLARE keyword, with the following syntax:
 

EXEC SQL DECLARE <cursor name> CURSOR FOR
SELECT ... FROM ...;


where the SELECT part of the statement specifies the query. Note that the above statement is only a declaration and the SELECT itself has not been executed yet. The declaration must occur before it is used. The scope of a cursor is the entire Pro*C++ program, but cursor statements (DECLARE, OPEN, FETCH, and CLOSE) must occur within the same precompiled unit. Therefore, for the entire program, each <cursor name> must be unique.

Once a cursor is declared, we have to open it in order to execute the query. To do this, we use the OPEN keyword, as follows:


EXEC SQL OPEN <cursor name>;


When we first open a cursor, it points to just before the first row (of the result). To retrieve rows (one at a time) which satisfy the SELECT query, we need to use the FETCH keyword. The syntax of the FETCH statement is:
 

EXEC SQL FETCH <cursor name> INTO :hostvar1, :hostvar2, ...;


Note that we have to first declare and open the cursor with cursor name before being able to use it in a FETCH statement.

After executing the FETCH statement, the cursor is set to point to the beginning of the next row of the answer set. When all rows have been fetched, sqlcode is set to 100 or 1403. Acknowledging this, we can write simple while loops which continuously fetch and print out tuple values for each row by testing sqlcode for the values 100 and 1403. You will see this in the example given below.

After all rows have been fetched, you can close the cursor with the command:
 

EXEC SQL CLOSE <cursor name>


A cursor can always be reused, so if you want to reuse your cursor, all you have to do is reopen it. The FETCH statement only moves forward in tables, so you might want to reopen a cursor to revisit and fetch previous rows in a table.
 
 

Sample Program

You should know enough about cursors by now to complete any homework involving embedded SQL.  Here is the Pro*C++ source code for maintaining the branch relation. In particular, note the subroutine called Show_Branch() which shows information for all branches.
#include <iostream.h>
#include <stdlib.h>                       // needed for atoi()
#include <stdio.h>                        // needed for gets()
#include <string.h>
#include <unistd.h>                       // needed for getpassphrase()
#include <iomanip.h>                      // needed for setw()
#define MAXBUF 50                         // maximum length of buffer
char line[MAXBUF];                        // buffer to hold stdin
EXEC SQL INCLUDE sqlca;                   // declarations for error checking
EXEC SQL WHENEVER SQLERROR    DO  print_error();
EXEC SQL WHENEVER SQLWARNING  DO  print_warning();
EXEC SQL WHENEVER NOTFOUND    DO  print_not_found();
void print_error()
{
  // display the error message returned by Oracle
  cout << "\n!! Unsuccessful operation.  Error code: " << sqlca.sqlcode;
  cout << "\n   Oracle Message: " << sqlca.sqlerrm.sqlerrmc << "\n";
}
void print_warning()
{
  // display the warning message returned by Oracle
  cout << "\n!! A warning occurred.   Error code: " << sqlca.sqlcode;
  cout << "\n   Oracle Message: " << sqlca.sqlerrm.sqlerrmc << "\n";
}
void print_not_found()
{
  // display the "row not found" message returned by Oracle
  cout << "\n!! Warning.  Row not found.  Error code: " << sqlca.sqlcode;
  cout << "\n   Oracle Message: " << sqlca.sqlerrm.sqlerrmc << "\n";
}
void Connect()
{
    // connect to database
    EXEC SQL BEGIN DECLARE SECTION;
        char userid[64];
        char password[64];
        char *DBname = "@ug";
    EXEC SQL END DECLARE SECTION;
    cout << "\nUsername: ";
    gets(userid);
    strcat(userid, DBname);
    strcpy(password, getpassphrase("Password: "));
    EXEC SQL CONNECT :userid IDENTIFIED BY :password;
}
void Insert_Branch()
{
  // Insert a tuple into the branch relation
  EXEC SQL BEGIN DECLARE SECTION;
    int        bid;
    VARCHAR    bname[20];
    VARCHAR    baddr[50];
    VARCHAR    bcity[20];
    int        bphone;
    short int  baddr_ind;
    short int  bphone_ind;
  EXEC SQL END DECLARE SECTION;
   cout << "\nBranch ID: ";
  gets(line);
  bid = atoi(line);
  cout << "\nBranch Name: ";
  gets(line);
  bname.len = strlen(line);
  strncpy((char *) bname.arr, line, bname.len);
  cout << "\nBranch Address: ";
  gets(line);
  baddr.len = strlen(line);
  strncpy((char *) baddr.arr, line, baddr.len);
  cout << "\nBranch City: ";
  gets(line);
  bcity.len = strlen(line);
  strncpy((char *) bcity.arr, line, bcity.len);
  cout << "\nBranch Phone: ";
  gets(line);
  if (strlen(line) != 0)
     bphone = atoi(line);         // phone number is not null
  else
     bphone_ind = -1;             // phone number is null;  set indicator
  EXEC SQL INSERT
           INTO    branch (branch_id, branch_name, branch_addr, branch_city,
                           branch_phone)
           VALUES (:bid, :bname, :baddr:baddr_ind, :bcity, :bphone:bphone_ind);
  //  The WHENEVER statement will handle the error processing, but
  //  to show the sequence of error messages, let's add the following.
  if (sqlca.sqlcode < 0)
     cout << "An error was detected.  The details are described above.\n";
  EXEC SQL COMMIT WORK;
}
void Delete_Branch()
{
  // Delete a tuple from the branch relation, given the branch id
  EXEC SQL BEGIN DECLARE SECTION;
    int  bid;
  EXEC SQL END DECLARE SECTION;
  cout << "Branch ID: ";
  gets(line);
  bid = atoi(line);
  EXEC SQL DELETE
           FROM   branch
           WHERE  branch_id = :bid;
  EXEC SQL COMMIT WORK;
}
 void Update_Branch()
{
  // Update the branch name, given the branch id
  EXEC SQL BEGIN DECLARE SECTION;
    int      bid;
    VARCHAR  bname[20];
  EXEC SQL END DECLARE SECTION;
   cout << "Branch ID: ";
  gets(line);
  bid = atoi(line);
  cout << "New Branch Name: ";
  gets(line);
  bname.len = strlen(line);
  strncpy((char *) bname.arr, line, bname.len);
  EXEC SQL UPDATE branch
           SET    branch_name = :bname
           WHERE  branch_id = :bid;
  EXEC SQL COMMIT WORK;
}
void Show_Branch()
{
  // Display information about branches
  EXEC SQL BEGIN DECLARE SECTION;
    int        bid;
    VARCHAR    bname[20];
    VARCHAR    baddr[50];
    VARCHAR    bcity[20];
    int        bphone;
    short int  baddr_ind;
    short int  bphone_ind;
  EXEC SQL END DECLARE SECTION;
  EXEC SQL DECLARE branch_info CURSOR FOR
           SELECT * FROM BRANCH;
  EXEC SQL OPEN branch_info;
  EXEC SQL FETCH branch_info
           INTO  :bid, :bname, :baddr:baddr_ind, :bcity, :bphone:bphone_ind;
  cout << setiosflags(ios::left);       // left justify the names to come
  cout << setw(10) << "ID"   << setw(15) << "NAME"  << setw(15) << "ADDRESS"
       << setw(15) << "CITY" << setw(15) << "PHONE" << "\n";
  cout << "--------------------------------------------------------------\n";
  while (sqlca.sqlcode >= 0  &&  sqlca.sqlcode != 100  &&
         sqlca.sqlcode != 1403)
   {
     bname.arr[bname.len] = '\0';       // null terminates the VARCHARs
     baddr.arr[baddr.len] = '\0';
     bcity.arr[bcity.len] = '\0';
     // display results;  keep the columns aligned reasonably well
     cout << setw(10) << bid       << setw(15) << bname.arr
          << setw(15) << baddr.arr << setw(15) << bcity.arr << setw(15);
     if (bphone_ind != -1)              // display phone number, if not null
        cout << bphone;
     else
        cout << " ";
     cout << "\n";
     EXEC SQL FETCH branch_info
              INTO  :bid, :bname, :baddr:baddr_ind, :bcity, :bphone:bphone_ind;
   }
  cout << "The last warning just signifies that the cursor fetched the "
       << "final record\n";
  EXEC SQL CLOSE branch_info;
  EXEC SQL COMMIT WORK;
}
int main()
{
  // simple text interface for above functions
  int  choice, quit;
  Connect();                        // connect to Oracle
  quit = 0;
  while (!quit)
    {
      cout << "\nPlease choose one of the following: \n";
      cout << "1. Insert branch\n";
      cout << "2. Delete branch\n";
      cout << "3. Update branch\n";
      cout << "4. Show   branch\n";
      cout << "5. Quit\n>> ";
      gets(line);
      choice = atoi(line);
      printf("\n\n");
      switch (choice)
        {
          case 1:  Insert_Branch();
                   break;
          case 2:  Delete_Branch();
                   break;
          case 3:  Update_Branch();
                   break;
          case 4:  Show_Branch();
                   break;
          case 5:  quit = 1;
          default: exit(0);
        }
     }
  EXEC SQL COMMIT WORK RELEASE;     // Commit and free any locks held.
  // Any additional non-SQL/non-Oracle work can go here.
}
Compile and run the code. You can now test modifications (insert, update, and delete) to the branch relation without having to start up an SQL*Plus session.

Although our example tested sqlca.sqlcode for the values 100 and 1403 in the Show_Branch() function, we could have used error trapping instead and done something like this:
 

EXEC SQL WHENEVER NOTFOUND DO BREAK;
while(1)  {
. . .
EXEC SQL FETCH branch_info
         INTO  :bid, :bname, :baddr:baddr_ind, :bcity, :bphone:bphone_ind;
. . .
}
/* restore WHENEVER NOTFOUND to what we had before */
EXEC SQL WHENEVER NOTFOUND DO print_not_found();



Embedded SQL/Oracle Tutorial  - Cursors