Tuesday 4 June 2013

Example Program in C++ Using file handling to perform following operations:


1)      add new record
2)      View all records
3)      Delete particular record
4)      Search record
5)      Update record

#include<iostream>
#include<fstream>
#include<conio.h>
#include<iomanip>
#include<stdio.h>
#include<string.h>
using namespace std;
int menu();
class Book
{
      private:
              int bookid;
              char title[20];
              float price;
      protected:
                int allotbookid();
                void showheader();
      public:
             void getbook();
             void showbook();
             void addbook();
             void viewbook();
             void searchbook();
             void deletebook();
             void modifybook();
};
int Book::allotbookid()
{
    ifstream fin;
    Book temp;
    int id=0;
    fin.open("bookfile.txt",ios::in|ios::binary);
    if(!fin)
            return(id+1);
    else
    {
        fin.read((char*)&temp,sizeof(temp));
        while(!fin.eof())
        {
         id=temp.bookid;
         fin.read((char*)&temp,sizeof(temp));
        }
        id++;
        return(id);
    }
}

                        
void Book::showheader()
{
     cout<<left;
     cout<<"\n"<<setw(10)<<"BOOK ID"<<setw(10)<<"Price"<<setw(10)<<"Title\n";
}
void Book::getbook()
{
     cout<<"Enter Book Title: ";
     fflush(stdin);
     gets(title);
     cout<<"Price of Book: ";
     cin>>price;
     bookid=allotbookid();
}
void Book::showbook()
{
     cout<<left;
     cout<<"\n"<<setw(10)<<bookid<<setw(10)<<price<<setw(10)<<title;
}
void Book::addbook()
{
     ofstream fout;
     fout.open("bookfile.txt",ios::out|ios::app|ios::binary);
     if(!fout)
              cout<<"File can not open";
     else
              fout.write((char*)this,sizeof(*this));
     fout.close();
}
void Book::viewbook()
{
     ifstream fin;
     fin.open("bookfile.txt",ios::in|ios::binary);
     if(!fin)
             cout<<"File not found";
     else
     {
         showheader();
         fin.read((char*)this,sizeof(*this));
         while(!fin.eof())
         {
          showbook();
          fin.read((char*)this,sizeof(*this));
         }
     }
     fin.close();
}
void Book::searchbook()
{
     ifstream fin;
     char str[20];
     fin.open("bookfile.txt",ios::in|ios::binary);
     cout<<"Enter the name of book to search:";
     fflush(stdin);
     gets(str);
     if(!fin)
             cout<<"File not found";
     else
     {
         fin.read((char*)this,sizeof(*this));
         while(!fin.eof())
         {
                 
          if(!strcmp(this->title,str))
          {
            showheader();
            showbook();
            break;
          }
          fin.read((char*)this,sizeof(*this));
         }
         if(fin.eof())
          cout<<"\nRecord not found";
     }
     fin.close();
}
void Book:: modifybook()
{
     int id,r=0;
     fstream file;
     file.open("bookfile.txt",ios::in|ios::out|ios::ate|ios::binary);
     cout<<"\nEnter record number to modify (bookid): ";
     cin>>id;
     file.seekg(0);
     if(!file)
             cout<<"File not found";
     else
     {
         file.read((char*)this,sizeof(*this));
        
         while(!file.eof())
         {
           r++;
           if(bookid==id)
           {
             showheader();
             showbook();
             cout<<"\nRe-enter book details:\n";
             cout<<"Enter book title:";
             fflush(stdin);
             gets(title);
             cout<<"Enter book price";
             cin>>price;
             file.seekp((r-1)*sizeof(Book),ios::beg);
             file.write((char*)this,sizeof(*this));
             break;
           }
           file.read((char*)this,sizeof(*this));
         }
         if(file.eof())
                      cout<<"Record not found";
     }     
         file.close();
}
void Book:: deletebook()
{
     ifstream fin;
     ofstream fout;
     int id;
     char x;
     fin.open("bookfile.txt",ios::in|ios::binary);
     fout.open("tempfile.txt",ios::out|ios::app|ios::binary);
     cout<<"Enter bookid to delete record";
     cin>>id;
     if(!fin)
             cout<<"File not found";
     else
     {
         fin.read((char*)this,sizeof(*this));
         while(!fin.eof())
         {
          if(this->bookid==id)
          {
            cout<<"Record you want to delete is:\n\n";
            showheader();
            showbook();
            cout<<"\nAre you sure you want to delete this record(y/n): ";
            fflush(stdin);
            cin>>x;
            if(x=='n')
                         fout.write((char*)this,sizeof(*this));
            else
                         cout<<"\nRecord is deleted";
          }
          else
              fout.write((char*)this,sizeof(*this));
          fin.read((char*)this,sizeof(*this));
         }
         fin.close();
         fout.close();     
        
        
                      system("erase bookfile.txt");
                      getch();
                      system("rename tempfile.txt bookfile.txt");
        
        
     }
}
int menu()
{
    system("cls");
    cout<<"\n1. Add new book";
    cout<<"\n2. View all books";
    cout<<"\n3. Search book";
    cout<<"\n4. modify book";
    cout<<"\n5. delete book";
    cout<<"\n6. Exit";
    cout<<"\n\nEnter your choice";
    int ch;
    cin>>ch;
    return(ch);
}
int main()
{
    Book b;
    int ch;
    while(1)
    {
           ch=menu();
           switch(ch)
           {
                     case 1:
                            b.getbook();
                            b.addbook();
                            break;                        
                     case 2:
                            b.viewbook();
                            break;
                     case 3:
                            b.searchbook();
                            break;
                     case 4:
                            b.modifybook();
                            break;
                     case 5: 
                            b.deletebook();
                            break;
                     case 6:
                            exit(0);
                     default:
                            cout<<"Enter Valid choice";
           }
           getch();
    }
}  
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Sunday 2 June 2013

Programming interview questions and answers(C)

Q.Can you think of a situation where your program would crash without reaching the breakpoint which you set at the beginning of main()? 
A.
C++ allows for dynamic initialization of global variables before main() is invoked. It is possible that initialization of global will invoke some function. If this function crashes the crash will occur before main() is entered. 


Q.Name two cases where you MUST use initialization list as opposed to assignment in constructors. A.Both non-static const data members and reference data members cannot be assigned values; instead, you should use initialization list to initialize them.

Q.Can you overload a function based only on whether a parameter is a value or a reference? 

A.No. Passing by value and by reference looks identical to the caller.

Q.What are the differences between a C++ struct and C++ class? 

A.The default member and base class access specifiers are different.
The C++ struct has all the features of the class. The only differences are that a struct defaults to public member access and public base class inheritance, and a class defaults to the private access specifier and private base class inheritance.
Q.What does extern "C" int func(int *, Foo) accomplish? A.It will turn off "name mangling" for func so that one can link to code compiled by a C compiler. 


Q.How do you access the static member of a class? A.<ClassName>::<StaticMemberName>

Q.What is multiple inheritance(virtual inheritance)? What are its advantages and disadvantages? A.Multiple Inheritance is the process whereby a child can be derived from more than one parent class. The advantage of multiple inheritance is that it allows a class to inherit the functionality of more than one base class thus allowing for modeling of complex relationships. The disadvantage of multiple inheritance is that it can lead to a lot of confusion(ambiguity) when two base classes implement a method with the same name. 


Q.What are the access privileges in C++? What is the default access level? A.The access privileges in C++ are private, public and protected. The default access level assigned to members of a class is private. Private members of a class are accessible only within the class and by friends of the class. Protected members are accessible by the class itself and it's sub-classes. Public members of a class can be accessed by anyone.

Q.What is a nested class? Why can it be useful? 

A.A nested class is a class enclosed within the scope of another class. For example:
// Example 1: Nested class
//
class OuterClass
{
class NestedClass
{
// ...
};
// ...
};
Nested classes are useful for organizing code and controlling access and dependencies. Nested classes obey access rules just like other parts of a class do; so, in Example 1, if NestedClass is public then any code can name it as OuterClass::NestedClass. Often nested classes contain private implementation details, and are therefore made private; in Example 1, if NestedClass is private, then only OuterClass's members and friends can use NestedClass.
When you instantiate as outer class, it won't instantiate inside class.

Q.What is a local class? Why can it be useful?

A.local class is a class defined within the scope of a function -- any function, whether a member function or a free function. For example:
// Example 2: Local class
//
int f()
{
class LocalClass
{
// ...
};
// ...
};
Like nested classes, local classes can be a useful tool for managing code dependencies.

Q.Can a copy constructor accept an object of the same class as parameter, instead of reference of the object? 

A.No. It is specified in the definition of the copy constructor itself. It should generate an error if a programmer specifies a copy constructor with a first argument that is an object and not a reference. 

Q.What are C++ storage classes? 
A.
auto register
static
extern
auto: the default. Variables are automatically created and initialized when they are defined and are destroyed at the end of the block containing their definition. They are not visible outside that block
register: a type of auto variable. a suggestion to the compiler to use a CPU register for performance
static: a variable that is known only in the function that contains its definition but is never destroyed and retains its value between calls to that function. It exists from the time the program begins execution
extern: a static variable whose definition and placement is determined when all object and library modules are combined (linked) to form the executable code file. It can be visible outside the file where it is defined.

Q.What are storage qualifiers in C++ ?

A.They are..
const
volatile
mutable
Const keyword indicates that memory once initialized, should not be altered by a program.
Volatile keyword indicates that the value in the memory location can be altered even though nothing in the program
code modifies the contents. for example if you have a pointer to hardware location that contains the time, where hardware changes the value of this pointer variable and not the program. The intent of this keyword to improve the optimization ability of the compiler.
Mutable keyword indicates that particular member of a structure or class can be altered even if a particular structure variable, class, or class member function is constant.
struct data
{
char name[80];
mutable double salary;
}
const data MyStruct = { "Satish Shetty", 1000 }; //initlized by complier
strcpy ( MyStruct.name, "Shilpa Shetty"); // compiler error
MyStruct.salaray = 2000 ; // complier is happy allowed

Q.What is reference ?

A.reference is a name that acts as an alias, or alternative name, for a previously defined variable or an object.
prepending variable with "&" symbol makes it as reference.
for example:
int a;
int &b = a;

Q.What is passing by reference?

A.Method of passing arguments to a function which takes parameter of type reference.
For example:
void swap( int & x, int & y )
{
int temp = x;
x = y;
y = temp;
}
int a=2, b=3;
swap( a, b );
Basically, inside the function there won't be any copy of the arguments "x" and "y" instead they refer to original variables a and b. so no extra memory needed to pass arguments and it is more efficient.

Q.When do use "const" reference arguments in function?
A.
a) Using const protects you against programming errors that inadvertently alter data.
b) Using const allows function to process both const and non-const actual arguments, while a function without const in the prototype can only accept non constant arguments.
c) Using a const reference allows the function to generate and use a temporary variable appropriately.