Tuesday 3 June 2014

Dangling point.

 What is a dangling pointer?
   
A dangling pointer arises when you use 
the address of an object after
its lifetime is over. This may occur 
in situations like returning
addresses of the automatic variables
from a function or using the
address of the memory block after 
it is freed. The following
code snippet shows this:

          class Sample
          {
          public:
                  int *ptr;
                  Sample(int i)
                  {
                   ptr = new int(i);
                  }

                  ~Sample()
                  {
                   delete ptr;
                  }
                  void PrintVal()
                  {
cout << "The value is " << *ptr;
                  }
          };

          void SomeFunc(Sample x)
          {
cout << "Say i am in someFunc " << endl;
          }

          int main()
          {
           Sample s1 = 10;
           SomeFunc(s1);
           s1.PrintVal();
          }

In the above example when PrintVal() function is
called it is called by the pointer that has been
freed by the       destructor in SomeFunc.

void pointer

void *

Sometimes we know we want a pointer, but we don't necessarily know or care what it points to. The C/C++ language provides a special pointer, the void pointer, that allows us to create a pointer that is not type specific, meaning that it can be forced to point to anything.Why is this useful? One common application of void pointers is creating functions which take any kind of pointer as an argument and perform some operation on the data which doesn't depend on the data contained. A function to "zero-out" memory (meaning to turn off all of the bits in the memory, setting each byte to the value 0) is a perfect example of this.

void memzero(void *ptr, size_t len)
{
 for(; len>0; len--) {
  *(char *)ptr = 0;
 }
}
This function takes a pointer to any piece of memory, meaning that we can pass in any kind of pointer we want, and the number of bytes to zero out. It then walks along the memory zeroing out each byte. Without void pointers, it would be more difficult to write a generic function like this.

Other example
void increaseChar (char* charData)
{
    ++(*charData);
}

void increaseInt (int* intData)
{
    ++(*intData);
}

int main ()
{
  char a = 'x';
  int b = 1602;
  increaseChar (&a);
  increaseInt (&b);
  cout << a << ", " << b << endl;
  string str;
  cin >> str;
  return 0;
}

string

C-Strings (Character Arrays)
STRING: It is an array of type char.
Syntax for declaration
char <array/string name> [max. number of characters to be stored +1];
The number of elements that can be stored in a string is always n-1, if the size of the array specified is n. This is because 1 byte is reserved for the NULL character '\0' i.e. backslash zero. A string is always terminated with the NULL character.
Example:
char str[80]; 
In the above example, str can be used to store a string with 79 characters.
Initializing a string
A string can be initialized to a constant value when it is declared.
char str[ ] = "Good";
    Or

char str[]={'G','o','o','d','\0'};
Here. 'G' will be stored in str[0], 'o' in str[1] and so on.
Note: When the value is assigned to the complete string at once, the computer automatically inserts the NULL character at the end of the string. But, if it is done character by character, then we have to insert it at the end of the string.
Reading strings with/without embedded blanks
To read a string without blanks cin can be used
cin>>str;
To read a string with blanks cin.getline() or gets() can be used.
cin.getline(str,80);
   -Or-
gets(str);
Printing strings
cout and puts() can be used to print a string.
cout<<str:
   Or
puts(str);
Note: For gets( ) and puts(), the header file stdio.h has to be included. puts() can be used to display only strings. It takes a line feed after printing the string.
cin
gets()
It can be used to take input of a value of any data type.
It can be used to take input of a string.
It takes the white space i.e. a blank, a tab, or a new line character as a string terminator.
It does not take the white space i.e. a blank, a tab, or a new line character, as a string terminator.
It requires header file iostream.h
It requires the header file stdio.h
Example:
char S[80];
cout<<"Enter a string:”;
cin>>S;
Example:
char S[80];
cout<<"Enter a string:";
gets(S);

cout
puts()
It can be used to display the value of any data type.
It can be used to display the value of a string.
It does not take a line feed after displaying the string.
It takes a line feed after displaying the string.
It requires the header file iostream.h
It requires the header file stdio.h
Example:
char S[80]="Computers";
cout<<S<<S;

Output:
ComputersComputers
Example:
char S[80]="Computers";
puts(S);
puts(S);

Output:
Computers
Computers
Counting the number of characters in a string and printing it backwards
#include<iostream.h>
#include<stdio.h>
int main( )
{
  char str[80];
  cout<<"Enter a string:";
  gets(str);
  for(int l=0; str[l]!='\0';l++);  //Loop to find length
    cout<<"The length of the string is : "<<l<<endl ;
  for(int i=l-1;i>=0;i--)    //Loop to display the string backwards
    cout<<str[i];
  return 0;
}
Function to count the number of words in a string
void count(char S[])
{
  int words=0;
  for(int i=0;S[i]!='\0';i++)
  {
    if (S[i]==' ')
      words++;                   //Checking for spaces
  }
  cout<<"The number of words="<<words+1<<endl;
}
Function to find the length of a string
int length(char S[ ])
{
  for(int i=0;S[i]!='\0';i++);
     return i;
}
Function to copy the contents of string S2 to S1
void copy(char S1[ ], char S2[ ])
{
   for(int i=0;S2[i]!='\0';i++)
      S1[i]=S2[i];
   S1[i]='\0';
}
Function to concatenate the contents of string S2 to S1
void concat(char S1[ ], char S2[ ])
{
   for(int l=0;S1[l]!='\0';l++);
     for(int i=0;S2[i]!='\0';i++)
         S1[l++]=S2[i];
     S1[l]='\0';
}
Function to compare strings STR1 to STR2.
The function returns a value>0 if //STR1>STR2, a value<0 if STR1<STR2, and value 0 if STR1=STR2
int compare(char STR1[ ],char STR2[])
{
  for(int I=0;STR1[I]==STR2[I] && STR1[I]!='\0'&&STR2[I]!='\0'; I++);
     return STR1[I]-STR2[I];
}
To reverse the contents of string S and store it in string Rev
void Reverse(char S[], char Rev[])
{
   for(int C1=0; S[C1]!='\0'; C1++);
      C1--;
   for(int C2=0;C1>=0;C2++,C1--)
      Rev[C2]=S[C1];
   Rev[C2]='\0';
}
Function to check whether a string S is a palindrome or not
int Palin(char S[])
{
   for(int L=0;S[L]!='\0';L++);    //To find length
      for(int C=0;(C<L/2) && (S[C]==S[L-C-1]);C++);
         return (C==L/2)?1:0; //Returns 1 if Palindrome else 0
}
Function to change the case of string S to uppercase
void Upper(char S[])
{
   for(int i=0;S[i]!='\0';i++)
      S[i] = (S[i]>='a' && S[i]<='z')?(S[i]-32):S[i];
}
Function to change the case of string S to lower case
void Lower(char S[])
{
   for(int i=0;S[i]!='\0';i++)
       S[i] = (S[i]>='A' && S[i]<='Z')?(S[i]+32):S[i];
}
Function to extract n characters from left side of the string and store it in a different string.
Example: 4 characters from ENVIRONMENT=ENVI
int SLeft(char S[ ], int n, char result[ ])
{
   for(int l=0;S[l]!='\0';l++);
     if(n<=I)    //characters extracted should be <=length
     {
        for(int i=0;i<n;i++)
            result[i]=S[i];
        result[i]='\0';
        return 1;
     }
     else
        return 0;
}
Function to extract n characters from right side of the string and store it in a different string.
Example: 4 characters from ENVIRONMENT=MENT
int SRight(char S[ ], int n, char result[ ])
{
   for(int l=0;S[l]!='\0';l++);
     if(n<=I)     //characters extracted should be <=length
     {
        for(int j=0;i=l-n;S[i]!=’/0’;i++,j++)
            result[j]=S[i];
        result[j]='\0';
        return 1;
     }
     else
        return 0;
}
Function to extract n characters from specified location loc of the string and store it in a different  string.
Example: 4 characters from third location in string ENVIRONMENT= VIRO
int substring(char S[ ], int n, int loc, char result[ ])
{
  for(int l=0;S[l]!='\0';l++);
     if(n<=I)      //characters extracted should be <=length
     {
        for(int j=0;i=l-n;S[i]!=’/0’;i++,j++)
           result[j]=S[i];
        result[j]='\0';
        return 1;
     }
     else
        return 0;
}


Two Dimensional Array

Two Dimensional Array
It is a collection of data elements of same data type arranged in rows and columns (that is, in two dimensions).
Declaration of Two-Dimensional Array
Type arrayName[numberOfRows][numberOfColumn];
For example,
int Sales[3][5];
Initialization of Two-Dimensional Array
An two-dimensional array can be initialized along with declaration. For two-dimensional array initialization, elements of each row are enclosed within curly braces and separated
by commas. All rows are enclosed within curly braces.
int A[4][3] = {{22, 23, 10},
              {15, 25, 13},
              {20, 74, 67},
              {11, 18, 14}};
Referring to Array Elements
To access the elements of a two-dimensional array, we need a pair of indices: one for
the row position and one for the column position. The format is as simple as:
name[rowIndex][columnIndex]

Examples:
cout<<A[1][2];      //print an array element
A[1][2]=13;         // assign value to an array element
cin>>A[1][2];       //input element
Using Loop to input an Two-Dimensional Array from user
int mat[3][5], row, col ;
for (row = 0; row < 3; row++)
  for (col = 0; col < 5; col++)
    cin >> mat[row][col];
Arrays as Parameters
Two-dimensional arrays can be passed as parameters to a function, and they are passed by reference. When declaring a two-dimensional array as a formal parameter, we can omit the size of the first dimension, but not the second; that is, we must specify the number of columns. For example:
   void print(int A[][3],int N, int M)
In order to pass to this function an array declared as:
   int arr[4][3];
we need to write a call like this:
   print(arr);
Here is a complete example: 
#include <iostream>
using namespace std;
void print(int A[][3],int N, int M)
{
  for (R = 0; R < N; R++)
    for (C = 0; C < M; C++)
       cout << A[R][C];
}
int main ()
{
  int arr[4][3] ={{12, 29, 11},
                  {25, 25, 13},
                  {24, 64, 67},
                  {11, 18, 14}};
  print(arr,4,3);
  return 0;
}
Function to read the array A
void Read(int A[][20], int N, int M)
{
  for(int R=0;R<N;R++)
    for(int C=0;C<M;C++)
    {
      cout<<"(R<<','<<")?";
      cin>>A[R][C];
     }
}
Function to display content of a two dimensional array A
void Display(int A[][20],int N, int M)
{
  for(int R=0;R<N;R++)
  {
     for(int C=0;C<M;C++)
        cout<<setw(10)<<A[R][C];
     cout<<endl;
   }
}
Function to find the sum of two dimensional arrays A and B
void Addition(int A[][20], int B[][20],int N, int M)
{
  for(int R=0;R<N;R++)
    for(int C=0;C<M;C++)
      C[R][C]=A[R][C]+B[R][C];
}
Function to multiply two dimensional arrays A and B of order NxL and LxM
void Multiply(int A[][20], int B[][20], int C[][20],int N, int L, int M)
{
  for(int R=0;R<N;R++)
   for(int C=0;C<M;C++)
   {
      C[R][C]=0;
      for(int T=0;T<L;T++)
        C[R][C]+=A[R][T]*B[T][C];
    }
}
Function to find & display sum of rows & sum of cols. of a 2 dim. array A
void SumRowCol(int A[][20], int N, int M)
{
  for(int R=0;R<N;R++)
  {
     int SumR=0;
     for(int C=0;C<M;C++)
       SumR+=A[R][C];
     cout<<"Row("<<R<<")="<<SumR<<endl;
   }
  for(int R=0;R<N;R++)
  {
    int SumR=0;
    for(int C=0;C<M;C++)
      SumR+=A[R][C];
    cout<<"Row("<<R<<")="<<SumR<<endl;
   }
}
Function to find sum of diagonal elements of a square matrix A
void Diagonal(int A[][20], int N, int &Rdiag, int &LDiag)
{
  for(int I=0,Rdiag=0;I<N;I++)
    Rdiag+=A[I][I];
  for(int I=0,Ldiag=0;I<N;I++)
    Ldiag+=A[N-I-1][I];
}
Function to find out transpose of a two dimensional array A
void Transpose(int A[][20], int B[][20],int N, int M)
{
  for(int R=0;R<N;R++)
    for(int C=0;C<M;C++)
       B[R][C]=A[C][R];


Array

Array
An array is a collection of data elements of same data type. It is described by a single name and each element of an array is referenced by using array name and its subscript no.
Declaration of Array
Type arrayName[numberOfElements];
For example,
int Age[5] ;
float cost[30];
Initialization of One Dimensional Array
An array can be initialized along with declaration. For array initialization it is required to place the elements separated by commas enclosed within braces.
int A[5] = {11,2,23,4,15};
It is possible to leave the array size open. The compiler will count the array size.
int B[] = {6,7,8,9,15,12};
Referring to Array Elements
In any point of a program in which an array is visible, we can access the value of any of its elements individually as if it was a normal variable, thus being able to both read and modify its value. The format is as simple as:
name[index]

Examples:
cout<<age[4];      //print an array element
age[4]=55;         // assign value to an array element
cin>>age[4];       //input element 4
Using Loop to input an Array from user
int age [10], i ;
for (i=0 ; i<10; i++)
{
  cin>>age[i];
}
Arrays as Parameters
At some moment we may need to pass an array to a function as a parameter. In C++ it is not possible to pass a complete block of memory by value as a parameter to a function, but we are allowed to pass its address.
For example, the following function:
void print(int A[])
accepts a parameter of type "array of int" called A.
In order to pass to this function an array declared as:
int arr[20];
we need to write a call like this:
print(arr);

Here is a complete example: 
#include <iostream>
using namespace std;
 
void print(int A[], int length)
{
  for (int n=0; n<length; n++)
    cout << A[n] << " ";
  cout << "\n";
}
int main ()
{
  int arr[] = {5, 10, 15};
  print(arr,3);
  return 0;
}
Basic Operation on One Dimensional Array
Function to traverse the array A
void display(int A[], int n)
{
       cout<<"The elements of the array are:\n";
       for(int i=0;i<n;i++)
              cout<<A[i];
}
Function to Read elements of the array A
Void Input (int A[], int n)
{
 
      cout<<"Enter the elements:";
      for(int i=0;i<n;i++)
            cin>>A[i];
}
Function to Search for an element from A by Linear Search
void lsearch(int A[], int n, int data)
{
      int i;
 
      for(i=0; i<n; i++)
      {
            if(A[i]==data)
            {
                  cout<<"Data Found at : "<<i;
                  return;
            }
      }
      cout<<"Data Not Found in the array"<<endl;
}
Function to Search for an element from Array A by Binary Search
int BsearchAsc(int A[], int n, int data)
{
       int Mid,Lbound=0,Ubound=n-1,Found=0;
       while((Lbound<=Ubound) && !(Found))
       {
              Mid=(Lbound+Ubound)/2;        //Searching The Item
              if(data>A[Mid])
                     Lbound=Mid+1;
              else if(data<A[Mid])
                     Ubound=Mid-1;
              else
                     Found++;
       }
       if(Found)
              return(Mid+1);        //returning 1ocation, if present
       else
              return(-1);        //returning -1,if not present
}
Function to Sort the array A by Bubble Sort
void BSort(int A[], int n)
{
    int I,J,Temp;
    for(I=0;I<n-1;I++) //sorting
   {
       for(J=0;J<(n-1-I);J++)
            if(A[J]>A[J+1])
           {
               Temp=A[J]; //swapping
               A[J]=A[J+1];
               A[J+1]=Temp;
           }
    }
}
Function to Sort the array ARR by Insertion Sort
void ISort(int A[], int n)
{
       int I,J,Temp;
       for(I=1;I<n;I++) //sorting
       {
           Temp=A[I];
           J=I-1;
           while((Temp<A[J]) && (J>=0))
           {
               A[J+1]=A[J];
               J--;
           }
           A[J+1]=Temp;
       }
}
Function to Sort the array by Selection Sort
void SSort(int A[], int n)
{
    int I,J,Temp,Small;
    for(I=0;I<n-1;I++)
    {
         Small=I;
         for(J=I+1;J<n;J++) //finding the smallest element
         if(A[J]<A[Small])
              Small=J;
         if(Small!=I)
        {
            Temp=A[I]; //Swapping
            A[I]=A[Small];
            A[Small]=Temp;
        }
     }
}
Function to merge A and B arrays of lenghts N and M
void Merge(int A[], int B[], int C[], int N, int M, int &K)
{
      int I=0, J=0;
      K=0;             //Initialisation of counters for A, B, and C
      while (I<N && J<M)
      {
            if (A[I]<B[J])
                  C[K++]=A[I++];
            else if (A[I]>B[J])
                  C[K++]=B[J++];
            else
            {
                  C[K++]=A[I++];
                  J++;
            }
      }
      for (int T=I;T<N;T++)
            C[K++]=A[T];
      for (T=J;T<M;T++)
            C[K++]=B[T];
}


Monday 2 June 2014

Data File Handling In C++

Data File Handling In C++
File. The information / data stored under a specific name on a storage device, is called a file.
Stream. It refers to a sequence of bytes.
Text file. It is a file that stores information in ASCII characters. In text files, each line of text is terminated with a special character known as EOL (End of Line) character or delimiter character. When this EOL character is read or written, certain internal translations take place.
Binary file. It is a file that contains information in the same format as it is held in memory. In binary files, no delimiters are used for a line and no translations occur here.    
Classes for file stream operation
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
Opening a file
OPENING FILE USING CONSTRUCTOR
ofstream fout(“results”);    //output only
ifstream fin(“data”);  //input only
OPENING FILE USING open()
Stream-object.open(“filename”, mode)
      ofstream ofile;
      ofile.open(“data1”);
     
      ifstream ifile;
      ifile.open(“data2”);
File mode parameter
Meaning
ios::app
Append to end of file
ios::ate
go to end of file on opening
ios::binary
file open in binary mode
ios::in
open file for reading only
ios::out
open file for writing only
ios::nocreate
open fails if the file does not exist
ios::noreplace
open fails if the file already exist
ios::trunc
delete the contents of the file if it exist
All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open():
fstream file;
file.open ("example.bin", ios::out | ios::app | ios::binary);
Closing File
   fout.close();
   fin.close();
INPUT AND OUTPUT OPERATION
put() and get() function
the function put() writes a single character to the associated stream. Similarly, the function get() reads a single character form the associated stream.
example :
file.get(ch);
file.put(ch);
write() and read() function
write() and read() functions write and read blocks of binary data.
example:
file.read((char *)&obj, sizeof(obj));
file.write((char *)&obj, sizeof(obj));
ERROR HANDLING FUNCTION
FUNCTION
RETURN VALUE AND MEANING
eof()
returns true (non zero) if end of file is encountered while reading; otherwise return false(zero)
fail()
return true when an input or output operation has failed
bad()
returns true if an invalid operation is attempted or any unrecoverable error has occurred.
good()
returns true if no error has occurred.

File Pointers And Their Manipulation
All i/o streams objects have, at least, one internal stream pointer:
ifstream, like istream, has a pointer known as the get pointer that points to the element to be read in the next input operation.
ofstream, like ostream, has a pointer known as the put pointer that points to the location where the next element has to be written.
Finally, fstream, inherits both, the get and the put pointers, from iostream (which is itself derived from both istream and ostream).

These internal stream pointers that point to the reading or writing locations within a stream can be manipulated using the following member functions:
seekg()
moves get pointer(input) to a specified location
seekp()
moves put pointer (output) to a specified location
tellg()
gives the current position of the get pointer
tellp()
gives the current position of the put pointer

The other prototype for these functions is:
seekg(offset, refposition );
seekp(offset, refposition );
The parameter offset represents the number of bytes the file pointer is to be moved from the location specified by the parameter refposition. The refposition takes one of the following three constants defined in the ios class.
ios::beg          start of the file
ios::cur          current position of the pointer
ios::end          end of the file
example:
file.seekg(-10, ios::cur);
2
Basic Operation On Text File In C++
Program to write in a text file
#include<fstream.h>
int main()
{
     ofstream fout;
     fout.open("out.txt");
     char str[300]="Time is a great teacher but unfortunately it kills all its pupils. Berlioz";
     fout<<str;
     fout.close();
     return 0;
}
Program to read from text file and display it
#include<fstream.h>
#include<conio.h>
int main()
{
     ifstream fin;
     fin.open("out.txt");
     char ch;
     while(!fin.eof())
     {
          fin.get(ch);
          cout<<ch;
     }
     fin.close();
     getch();
     return 0;
}
Program to count number of characters.
#include<fstream.h>
#include<conio.h>
int main()
{
     ifstream fin;
     fin.open("out.txt");
     clrscr();
     char ch; int count=0;
     while(!fin.eof())
     {
          fin.get(ch);
          count++;
     }
     cout<<"Number of characters in file is "<<count;
     fin.close();
     getch();
     return 0;
}
Program to count number of words
#include<fstream.h>
#include<conio.h>
int main()
{
     ifstream fin;
     fin.open("out.txt");
     char word[30]; int count=0;
     while(!fin.eof())
     {
          fin>>word;
          count++;
     }
     cout<<"Number of words in file is "<<count;
     fin.close();
     getch();
     return 0;
}
Program to count number of lines
#include<fstream.h>
#include<conio.h>
int main()
{
     ifstream fin;
     fin.open("out.txt");
     char str[80]; int count=0;
     while(!fin.eof())
     {
          fin.getline(str,80);
          count++;
     }
     cout<<"Number of lines in file is "<<count;
     fin.close();
     getch();
     return 0;
}
Program to copy contents of file to another file.
#include<fstream.h>
int main()
{
     ifstream fin;
     fin.open("out.txt");
     ofstream fout;
     fout.open("sample.txt");
     char ch;
     while(!fin.eof())
     {
          fin.get(ch);
          fout<<ch;
     }
     fin.close();
     return 0;
}
Basic Operation On Binary File In C++
class student
{
            int admno;
            char name[20];
public:
          void getdata()
          {
                     cout<<"\nEnter The admission no. ";
                     cin>>admno;
                     cout<<"\n\nEnter The Name of The Student ";
                     gets(name);
          }
          void showdata()
          {
                     cout<<"\nAdmission no. : "<<admno;
                     cout<<"\nStudent Name : ";
                     puts(name);
          }
          int retadmno()
          {
                     return admno;
          }
};

function to write in a binary file
void write_data()
{
          student obj;
          ofstream fp2;
          fp2.open("student.dat",ios::binary|ios::app);
          obj.getdata();
          fp2.write((char*)&obj,sizeof(obj));
          fp2.close();
}
function to display records of file
void display()
{
          student obj;
          ifstream fp1;
          fp1.open("student.dat",ios::binary);
          while(fp1.read((char*)&obj,sizeof(obj)))
          {
                     obj.showdata();
          }
}
          fp.close();
}
Function to search and display from binary file
void search (int n)
{
          student obj;
          ifstream fp1;
          fp1.open("student.dat",ios::binary);
          while(fp1.read((char*)&obj,sizeof(obj)))
          {
                     if(obj.retadmno()==n)
                                obj.showdata();
          }
          fp1.close();
}
Function to delete a record
void deleterecord(int n)
{
          student obj;
          ifstream fp1;
          fp1.open("student.dat",ios::binary);
          ofstream fp2;
          fp2.open("Temp.dat",ios::out|ios::binary);
          while(fp1.read((char*)&obj,sizeof(obj)))
          {
                      if(obj.retadmno!=n)
                                    fp2.write((char*)&obj,sizeof(obj));
          }
          fp1.close();
          fp2.close();
          remove("student.dat");
          rename("Temp.dat","student.dat");
}
Function to modify a record
void modifyrecord(int n)
{
          fstream fp;
          student obj;
          int found=0;
          fp.open("student.dat",ios::in|ios::out);
          while(fp.read((char*)&obj,sizeof(obj)) && found==0)
          {
                     if(obj.retadmno()==n)
                     {
                              obj.showdata();
                              cout<<"\nEnter The New Details of student";
                              obj.getdata();
                              int pos=-1*sizeof(obj);
                              fp.seekp(pos,ios::cur);
                              fp.write((char*)&obj,sizeof(obj));
                              found=1;
                    }
          }
          fp.close();
}