Docstoc
EXCLUSIVE OFFER FOR DOCSTOC USERS
Try the all-new QuickBooks Online for FREE.  No credit card required.

cs201Question Ans

Document Sample
cs201Question Ans Powered By Docstoc
					                                               1


calloc Function
The syntax of the calloc function is as follows.
void *calloc (size_t n, size_t el_size)
This function takes two arguments. The first argument is the required space in terms
of numbers while the second one is the size of the space. So we can say that we
require n elements of type int. We have read a function sizeof. This is useful in the
cases where we want to write a code that is independent of the particular machines
that we are running on. So if we write like


void calloc(1000, sizeof(int))


malloc Function
malloc is used to dynamically allocate memory in the C programming language. malloc
returns a pointer of type void to a memory buffer of a requested size, or null if it fails. It
may also be used in C++, although new is preferred.


The malloc function takes one argument i.e. the number of bytes to be allocated. The
syntax of the function is void * malloc (size_t size) ; It returns a void pointer to the
starting of the chunk of the memory allocated from the heap in case of the availability of
that memory. If the memory is not available or is fragmented (not in a sequence),.


It is very important to note that whenever we allocate memory from the heap by using
calloc or malloc, it is our responsibility to free the memory when we have done with it.


realloc Function Sometimes, we have allocated a memory space for our use by
malloc function. But we see later that some additional memory is required. For example,
in the previous example, where (for example) after allocating a memory for 35 students,
we wanted to add one more student. So we need same type of memory to store the new
entry. Now the question arises „Is there a way to increase the size of already allocated
memory chunk ? Can the same chunk be increased or not? The answer is yes. In such
situations, we can reallocate the same memory with a new size according to our
requirement. The function that reallocates the memory is realloc. The syntax of realloc is
given below. void realloc (void * ptr, size_t size ) ;
                                               2

Memory Leak
In C/C++, it is possible to allocate space for objects (variables) dynamically during
program execution. After finishing use of a dynamically allocated object, it is necessary
to explicitly release the memory consumed by the object, particularly before pointers to
the object go out of scope. Failure to do so results in a memory leak. Long running
programs or those that allocate memory extensively can consume or occupy enough of a
computers memory to seriously hinder performance when memory leaks are present.


macro vs. an inline function


A preprocessor feature that supports parameter substitution and expansion of
commonly-used code sequences. Also see inline function
// A macro vs. an inline function
#include <iostream.h>
#define MAX( A, B ) ((A) > (B) ? (A) : (B))
inline int max( int a, int b )
{
if ( a > b ) return a; return b;
}
void main()


{
int i, x, y;
x = 23; y = 45;
i = MAX( x++, y++ ); // Side-effect:
// larger value incremented twice
cout << "x = " << x << " y = " << y << '\n';
x = 23; y = 45; i = max( x++, y++ ); // Works as expected
cout << "x = " << x << " y = " << y << '\n';
}


The output of this program is:
x = 24 y = 47 x = 24 y = 46
                                                3



/* Overload functions to print variables of different types */
#include <iostream.h>
void print (int i)
{
cout << "\nThe value of the integer is: " << i;
}


void print (double d)
{
cout << "\nThe value of the double is: " << d;
}
void print (char* s)
{
cout << "\nThe value of the string is: " << s;
}


main (void)
{
int i = 100;
double d = 123.12;
char *s = "This is a test string";
print ( i );
print ( d );
print ( s );


}




The output of the program is:
The value of the integer is: 100
The value of the double is: 123.12
The value of the string is: This is a test string
                                                 4



“Instances of a class are called objects”
With the definition of class, we have a new data type like int, char etc. Here int i; means
„i‟ is an instance of data type int. When we take a variable of a class, it becomes the
instance of that class, called object.


class Date
{
private: // private data and functions


public: // public data and functions


};


Class
A C++ keyword used to declare the fundamental building block of C++ programs. A class has a tag,
members, access control mechanisms, and so on.



Let’s see the example of Date class in detail.
class Date
{


public:


void display();
Date(int, int, int);
private:
int day, month, year;


};




constructor
                                                   5
A function called when a class object comes into scope. The constructor is used to
initialize the object. See allocation, copy constructor, and destructor.


Date::Date(int theDay, int theMonth, int theYear)
{
day = theDay;
month = theMonth;
year = theYear;


}
Default arguments with constructors
We can also use the default arguments with the constructors. In the case of Date,
normally the days and months are changing and the year remains same for one year.
So we can give the default value to year.


Date::Date(int theDay, int theMonth, int theYear = 2002)
{
// The body of the constructor
}




Object
In C++, often refers to an instance of a class. Also more loosely refers to any named declaration
of a variable or other entity that involves storage.


operator : A built-in operation of the C++ language, like addition, or an overloaded
               operator corresponding to a member function of a class.



operator       To treat a C++ operator like << as a function and overload it for particular
overloading parameter types. The assignment of more than one function to a particular
:              operator, with the implication that the operation performed will vary
               depending on the data type (operands) involved.


Friend function
                                            6
A type of declaration used within a class to grant other classes or functions access to
that class.
We use the keyword „friend‟ before the prototype of the function.
friend return_type friend_function_name(int, char);


A sample program showing the use of friend function, which access the private data
member of the class.*/
#include <iostream.h>
class myClass
{
friend void increment(myClass *, int);
private:
int topSecret;
public:
void display()


{
cout << "\n The value of the topSecret is " << topSecret;
}
myClass();
};
// constructor of the class
myClass::myClass()
{
topSecret = 100;
}
// Friend function definition
void increment(myClass *a, int i)
{
a->topSecret += i; // Modify private data
}
// showing the use of the friend function void main()
{
myClass x;
x.display();
                                            7
increment(&x, 10);
x.display();
}


The Output of the program is
The Value of the top secret is 100
The value of the top secret is 110


Friend Classes
The following code segment shows the declaration of friend class. It shows that
OtherClass is a friend of ClassOne so it has access to the private data of ClassOne.


class ClassOne
{
friend class OtherClass;
private:
int topSecret;
};
class OtherClass
{
public:
void change( ClassOne co )
};
void OtherClass::change( ClassOne co )
{
co.topSecret++; // Can access private data of class one
}
                                                 8




destructor A function called when a class object goes out of scope. It cleans up the
:               object, freeing resources like dynamic storage.
The destructors can be summarized as the following.
The destructors cannot be overloaded.
The destructors take no arguments.
The destructors don‟t return a value.
So they don‟t have a return type and no return statement in the body.
Date::~Date()
{
cout << "The object has destroyed" << endl;
}


New Operator
Whenever new operator is used, no number of bytes or sizeof operator and no cast is
applied to convert the pointer to the required type.


The memory allocated from free store or heap is a system resource and is not
returned back to the system unless explicitly freed using delete or free operators.


- If   the memory in the free store is not sufficient enough to fulfill the request,
malloc() function returns NULL pointer. Similarly, the new function returns 0 in
case the request could not be fulfilled.




References as Return Values A function itself can return a reference. The syntax of
declaration of such a function will be as under.
datatype& function_name (parameter list)
                                                 9
The use of reference data type is the             implementation of call by reference in an
elegant way.
• We cannot do arithmetic with references like pointers
. • Reference variables must be initialized immediately when they are declared.
• To avoid dangling reference, don‟t return the reference of a local variable from a
function.
• In functions that return reference, use global or static variables.
• The reference data types are used as ordinary variables without any dereference
operator.


Operators to Overload
There are two types of operators to overload:
1. Unary
2. Binary
Unary operators are the ones that require only one operator to work. Unary operators are
applied to the left of the operand. For example, ^, &, ~ and !.
Binary operators require two operands on both sides of the operator. +, -, *, /, %, =, <
and > are examples of binary operators.


The complete list of C++ operators that can be overloaded is as follows:
+ - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= && | | ++
- - -> * , [ ] ( ) new new[ ] delete delete[ ]
The following operators can‟t be overloaded. . : :: .* ? sizeof


String
Let‟s take an example where the operators are performing a non-arithmetical operation.
We are writing a class String for strings manipulation as:
class String
{
private :
char string [ 30 ] ;
public :
String ( )
{
strcpy ( string , "" ) ;
                                            10
}
void getString ( )
{
cout << "Enter the String : " ;
cin >> string ;
}
void displayString ( )
{
cout << "The String Is : " << string << endl ;
}
// Declaration (prototype) of overloaded sum operator


String operator + ( String & s ) ;
};


We have been using a swap function. We want to interchange two things. You know the
technique that we need a third temp-place holder. If we want to swap two integers i and j,
the code will be as under:


Void Swap (int & I, int & j)
{
        int tmp;
        tmp =I;
        j= tmp;
}




template
A combination of a template with a template argument list via the process of template
instantiation.


template<class T>
                                             11

           void swap(T &x, T &y)
         {
               T tmp;
               tmp = x;
               x = y;
               y = tmp;
         }



// A small program shows the use of template function
#include<iostream.h>
// template function of deciding a larger number
template<class T>
T larger(T x, T y)
{
T big;
if (x > y)
big = x;
else
big = y;
return(big);
}
// the main function
void main()
{
int i = 7, j = 12;
double x = 4.5, y = 1.3;
cout << "The larger of " << i << " and " << j << " is " << larger(i, j)<< endl;
cout << "The larger of " << x << " and " << y << " is " << larger(x, y)<< endl;
//cout << "The larger of " << x << " and " << y << " is " << larger(i, y)<< endl;
}


The output of the program is:
The larger of 7 and 12 is 12
The larger of 4.5 and 1.3 is 4.5
                                                12
// An example of overloaded template              functions.
#include<iostream.h>
// template function
Template <class T>
void inverse(T &x, T &y)
{
T temp;
temp = x;
x = y;
y = temp;
}
// overloaded inverse function
template<class T>
T inverse(T x)
{
return (-x);
}
// the main fucntion
void main()
{
int i = 3, j = 5;
// calling the templatized functions
inverse(i);
inverse(i, j);
cout << “i = ” << i << ", j = " << j << endl;
}


The output of the program is:
i = 5.6, j = -3.4


Definition of Matrix Constructor
Let‟s start with the default constructor. Its prototype is as under:
Matrix(int = 0, int = 0); // default constructor
                                              13
We are using the default argument values        here. In the definition of this function, we
will not repeat the default values. Default values are given at one place. The definition
code is as:
Matrix::Matrix(int row, int col) //default constructor
{
numRows = row;
numCols = col;
elements = new (double *) [numRows];
for (int i = 0; i < numRows; i++)
{
elements[i] = new double [ numCols];
for(int j = 0; j < numCols; j++)
elements[i][j] =0.0; // Initialize to zero
}
}




Destructor of Matrix Class
Destructor‟ is relatively simple. It becomes necessary after the use of new in the
constructor. While creating objects, a programmer gets memory from the free store. So in
the destructor, we have to return it. We will do it as:
                delete [] elements;


Utility Functions of Matrix
The functions getRows() and getCols() are relatively simple. They do not change
anything in the object but only read from the object. Therefore we have made this
function constant by writing the const keyword in the end. It means that it does not
change anything. The code of the getRows() functions is as follows:
int Matrix :: getRows ( ) const
{
return numRows;
}


Input Functions
                                             14
Input functions are also of two types like     output functions. The first function takes
input from the keyboard while the other takes input from the file. The function that takes
input from the keyboard is written in a polite manner because humans are interacting with
it. We will display at the screen”Input Matrix size: 3 rows by 3 to columns” and it will
ask “Please enter 3 values separated by spaces for row no. 1” for each row.


The other input function reads from the file. We have also stored the number of rows and
number of columns in the file. The code of this function is:


const Matrix & Matrix::input(ifstream &is)
{
int Rows, Cols;
is >> Rows;
is >> Cols;
if(Rows > 0 && Cols > 0)
{
Matrix temp(Rows, Cols);
*this = temp;
for(int i = 0; i < numRows; i++)
{
for(int j = 0; j < numCols; j++)
{
is >> elements[i][j];
}
}
}
return *this;
}


Transpose Function
The transpose of a matrix will interchange rows into columns. There are two alternative
requirements. In the first case, we have a square matrix i.e. the number of rows is equal to
number of columns. In this situation, we don‟t need extra storage to do this. If the number
of rows is not equal to the number of columns, then we have to deal it in a different way.
                                             15
We can use general case for both purposes         but you will notice that it is slightly
insufficient. Here is the code of the function.
const Matrix & Matrix::transpose()
{
if(numRows == numCols){ // Square matrix
double temp;
for(int i = 0;i < numRows; i++)
{
for(int j = i+1; j < numCols; j++)
{
temp = elements[i][j];
elements[i][j] = elements[j][i];
elements[j][i] = temp;
}


}
}
else // not a square matrix
{
Matrix temp(numCols, numRows);
for(int i = 0; i < numRows; i++)
{
for(int j = 0; j < numCols; j++)
{
temp.elements[j][i] = elements[i][j];
}
}
*this = temp;
}
return *this;
}


Plus-equal (+=) Operator Function
Now we will discuss the += operator. Whenever a programmer writes a += b, he will
come across a different scenario as compared to the one witnessed in the case of the
                                               16
addition operator. In a way, now „a’ itself      is being changed. So if a is going to
change, we can return a reference to a. The conformability check remains the same as in
ordinary addition. That means both matrices must have the same number of rows and
columns. There is no need of creating a temporary matrix. Here we can return reference
to left-hand side matrix. Here one finds that there is reuse and efficiency in the code. The
+= operator is defined as under.
        const Matrix & Matrix::operator += (Matrix &m)
        {
        *this = *this + m;
        return *this;
        }


Minus Operator (-) Function
The same discussion of plus (+) operator applies to the minus (-) operator as both are
identical. We see the difference between these operators when we do a + d. In case of
addition, it will be the same as that of d + a. However, while dealing with minus case, the
result of a - d will be obviously different from the result of d - a.


Multiplication Operator (*) Function
The most complicated operator out of all these arithmetic manipulators for matrices is the
multiplication (*) operator. How do we multiply two matrices together?
The code of the function for * operator is defined as below.


Matrix Matrix::operator* ( const Matrix& m)
{
Matrix temp(numRows,m.numCols);
if(numCols == m.numRows)
{
        for ( int i = 0; i < numRows; i++)
{
        for ( int j = 0; j < m.numCols; j++)
        {
        temp.elements[i][j] = 0.0;
        for( int k = 0; k < numCols; k++)
        {
                                             17
        temp.elements[i][j] +=                  elements[i][k] * m.elements[k][j];
        }
        }
        }
        }
                return temp;
}


Rules for Programming
We need simply three constructs to solve any problem.
1) Things should be executed sequentially. That means the statements are executed in a
sequence i.e. the second statement follows the first and so on.
2) We need to have a decision. The decision means if something is true, the program
executes it. Otherwise, it tries doing something else. So there is simple decision or if-else
decision.
3) The third construct is loop, which is a repetition structure that performs the same task
repeatedly with different values.

				
DOCUMENT INFO
Shared By:
Categories:
Tags: CS201
Stats:
views:11
posted:12/26/2010
language:English
pages:17