Posts

Showing posts from 2016

C++: Working with files -2

Image
More about open(): File ModesGeneral form of open() function
   streamobject.open("filename",mode);
The second argument mode specifies the purpose for which the file is opened.The default value of mode are
ios::in for ifstream function meaning open for reading only
ios::out for ofstream function open for writing only
_________________________________________File Mode Parametersios::app   Appened to end-of-file
ios::ate    Go to end-of-file on opening
ios::binary   Binary file
ios::nocreateOpen fails if file doesn't exist
ios::noreplaceOpen files if file already exist
ios::truncDelete the contents of file if it exists
__________________________________________File Pointers and their ManipulationsEach file has two associated pointers known as file pointer.
1. Input pointer(get pointer) is used for reading the contents of a given file location.
2. Output pointer(put pointer) is used for writing to a file location.Functions for Manipulation of file Pointersseekg() Moves get pointer …

C++:Working With Files -1

Image
A program typically involves either or both of the following kind of data communication:-1. Data transfer between console unit and program2. Data transfer between program and disk file.Input Stream- supplies data to program or reads data from file.Output Stream- recieves data from program or writes data to file.Input operation involves the creation of an input stream and linking it with the program and input file.
________________________________________
Classes for FIle Stream OperationsI/O system of c++ contains a set of classes that defines the file handling methods.These include ifstream, ofstreamand fstream. These classes are derived from fstreambase class and corresponding iostreamclass.
_________________________________________
Opening and Closing of FileThe filename is a string of character conatining two parts - primary name and optional period with extension.
eg.  Input.data
        test.docOpening file using constructorThis method is useful when we use only one file in the st…

C++: Program for calculator using functions

Image
#include<iostream>
using namespace std; float sum(float, float);
float sub(float, float);
float mul(float, float);
float div(float, float); int main()
{
float x, y, res;
char choice;
cout << "Calculator\n\n";
cout << "Enter two numbers\n";
cin >> x >> y;
cout <<
"Operations \n '+' for addition \n '-' for substraction \n '*' for multiplication \n '/' for division \n";
cin >> choice;
switch (choice)
{
case '+':
res = sum(x, y);
cout << "Sum is :" << res;
break;
case '-':
res = sub(x, y);
cout << "Substraction is:" << res;
break;
case '*':
res = mul(x, y);
cout << "Multiplication is:" << res;
break;
case '/':
res = div(x, y);
cout << "Division is :" << res;
break;
default:
cout << "Enter correct choice";
break;
}
return 0;
} float sum(float a, float b)
{

C++: I/O Operations -2

Image
Formatted Console I/O OperationsTo access manipulators the file iomanipshould be included in program.cout.width(w);to define width of a field necessary for output of item.
w is field width(no. of columns)cout.precision(d)to specify no. of digits to be displayed after the decimal point.By default, floating no. are printed with six digits after the decimal point.  cout.precision(3);
  cout<<3.15159<<"\n";
  cout<<2.50032<<"\n";3.142(rounded to nearest cent)
2.5 (no trailing zeros)Unlike width(), precision() retains the setting in effect until it is reset.cout.fill(ch);  to fill unused position by any desired character.By default, the unused positions of the field are filled with the white spaces.  cout.fill("*");
  cout.width(10);
  cout<<5250<<"\n";******5250fill() also stays in effect till we change it. cout.setf(arg1,arg2); 
arg1 is one of the formatting flags specifies the format action required for outp…

C++: I/O Operations -1

Image
C++ StreamsC++ is designed to work with a wide variety of devices. The I/O system supplies an interface to the programmer that is independent of the actual device being used.A stream is a sequence of bytes.The source stream that provides data to the program is called input stream.The destination stream that receives output from program is called output stream.A program extracts bytes from an input stream and inserts bytes into an output stream.
__________________________________________C++ Stream ClassesThe classes are ios, istream, ostream, iostream, streambuf .The class ios is declared as the virtual base class so that only one copy of its members are inherited by the iostream.istreamprovides the facilities for formatted and unformatted input.ostreamprovides the facilities for formatted output.
__________________________________________Unformatted I/O OperationsOverloaded Operators >> and <<:The  >> operator is overloaded in the istreamclass and << is overloade…

C++: Pointers

Image
A Pointer is a special type of variable which holds the address of a value.

C++: Inheritance

Image
div { width: 100%; } .success { background-color: #ccffcc; } Reusability is an  important feature of OOP. It saves our time and increase reliability. C++ strongly supports the concept of reusability. Types of Inheritance: 1) Single Inheritance
2) Multiple Inheritance
3) Hierarchical  Inheritance
4) Multilevel Inheritance
5) Hybrid Inheritance
__________________________________________ Defining Derived Class:   class derived-class-name: visibility-mode base-class-name
  {
       ..........//members of derived class
   }; The colon indicates that the derived-class-name is derived from the base-class-name. The default visibility mode is private. Visibility mode specifies whether the features of the base class are privately derived or publicly derived. When a base class is privately inherited by a derived class, 'public members' of the base class become 'private member' of the derived class and therefore the public members of the base class can only be accessed by the member…

C++:Program Swapping variables

Image
How to swap three nos. without another variable.
let input be a=2,b=3 and c=4
and output=a=4,b=2and c=3

#include<iostream>
using namespace std;

int main(){
int a,b,c;
cout<<"Enter three nos."<<endl;
cin>>a>>b>>c;
a=a+b+c; //now a=9
b=a-(b+c); //b=2
c=a-(b+c); //c=3
a=a-(b+c); //a=4
cout<<"a="<<a<<" b="<<b<<" c="<<c;
return 0;
} This method will not work for large value of integers.            < Happy Coding >

C++: Operator Overloading

Defining Operator Overloading:We can specify what operator means in relation to the class to which the operator is applied, with the help of operator function.     return type classname::operator(op-arglist)
     {
         function body //task assigned
     }op is the operator being overloaded.Operator functions must be either member function(non-static) or friend function.A friend function will have only one argument for unary operators and two for binary operators.A member function has no arguments for unary operator and only one for binary operators.   vector operator+(vector) //vector addition
   vector operator-();            //unary minus
   friend vector operator+(vector,vector); //vector addition
   friend vector opertaor-(vector);  //unary minusFor friend function overloaded operator function can be invoked by expression such as
   op x or x op    for unary operator
  x op y              for binary operatorin case of member function
   operator op (x,y)_____________________…

C++: Program to enter integers in 2D Array

Program to enter numbers in 2-D 5*5 array. #include<iostream>
usingnamespacestd; int main()
{
int a[5][5];
cout<<"Enter numbers in array"<<endl;
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
cin>>a[i][j];
  }
}
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
cout<<a[i][j]<<" ";
  }
cout<<endl;
}
return0;
}

C++: Program to enter integers in 1D Arrray

Image
Program to enter numbers in an 1-D array of length 5. #include<iostream>
usingnamespacestd; int main()
{
int a[5];
cout<<"Enter numbers in array"<<endl;
for(int i=0;i<5;i++){
cin>>a[i];
}
for(int i=0;i<5;i++){
cout<<a[i]<<" ";
}
return0;
}

C++: Program to print pattern

Image
Q. Write a program to print the pattern

1
22
333
4444
55555 Ans. #include<iostream>
usingnamespacestd; int main()
{
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
cout<<i;
  }
cout<<endl;
}
return0;
} Any better solution or suggention is welcomed. < Happy Coding >

C++: Constructors and Destructors

Constructors:It enables an object to initialize itself when it is created and knows as automatic initialization.
Its name is same as the class and it is invoked whenever an object of its associated class is created.   class integer {
              int m,n;
      public:
              integer(void);  //constructor declared
             ...........
        };
    integer::integer(void){ //constructor defined
             m=0;
             n=0;
         }Now object is created
        integer int1;
Here data members m and n are initialized to zero.A constructor that accepts no parameters is called the default constructor.
eg
   for class A is A::A()If no constructor is defined, then the compiler supplies a default constructor.
Thus
         A a;
invokes default constructor.Special characteristics of constructor function:They should be declared in the public section.They do not have any return type, even void.They cannot be inherited, though a derived class can call the base class constru…

C++: Constructors and Destructors-1

Image
Constructors: It enables an object to initialize itself when it is created and knows as automatic initialization.
Its name is same as the class and it is invoked whenever an object of its associated class is created.    class integer {
              int m,n;
      public:
              integer(void);  //constructor declared
             ...........
        };
    integer::integer(void){ //constructor defined
             m=0;
             n=0;
         } Now object is created
        integer int1;
Here data members m and n are initialized to zero. A constructor that accepts no parameters is called the default constructor.
eg
   for class A is A::A() If no constructor is defined, then the compiler supplies a default constructor.
Thus
         A a;
invokes default constructor. Special characteristics of constructor function: They should be declared in the public section. They do not have any return type, even void. They cannot be inherited, though a derived class can call the base class…

C++: Classes & Objects-2

Image
Private Member Functions:A private member function can only be called by another function that is a member of its class.An object cannot invoke a private function using the dot operator.eg:
     class demo{
                   void read(); 
            public:
                   void update();
     };
if s1 is object
   s1.read(); //won't work   void sample::update(){
              read();
       }
__________________________________________Memory allocation for Objects:The member functions are created and placed in the memory space only once when they are defined as a part of a class specification.No seperate space is allocated for member function when objects are created.Only space for member variables is alocated seperately for each object, because the member variables will hold different data values for different objects.
__________________________________________Static Data Member:It is initialized to zero when the first object of its class is created. no other initialization …