Monday, November 19, 2012

Functions in C++


Functions


A function is a single comprehensive unit that performs a specified task. This specified task is repeated each time the function is called. Functions break large programs into smaller tasks. They increase the modularity of the programs and reduce code redundancy.
Like in C, C++ programs also should contain a main function, where the program always begins execution. The main function may call other functions, which in turn will again call other functions.
When a function is called, control is transferred to the first statement of the function body. Once the statements of the function get executed (when the last closing bracket is encountered) the program control return to the place from where this function was called.

Function Prototype (Function declaration)
Function prototype lets the compiler know the structure of function in terms of its name, number and type of arguments and its return type.
            Syntax:
                        return-type function-name(datatype1, datatype2, …,datatype n);

Function Call

Function call is the process of making use of function by providing it with the parameters it needs. We call a function as follows.
                        function-name (argument1, argument2, .. ,argument n);

Function Definition

Function definition is a process of defining how it does what it does or in other words, during function definition, we list the series of codes that carry out the task of the function. A function is defined as follows,

return-type function-name(datatype1 variable1, datatype2 var2, …., datatype n var n)
{
            ……………… ;
            ………………….; //body of the function
            ……………….;
}
           

 

Default Arguments


In C++, a function can be called without specifying all its arguments. But it does not work on any general function. The function declaration must provide default values for those arguments that are not specified. When the arguments are missing from function call, default value will be used for calculation.

#include<iostream.h>
float interest(int p, int t = 5, float r = 5.0);
main()
{
            float rate, i1,i2,i3;
            int pr , yr;
            cout<<”Enter principal, rate and year”;
            cin>>pr>>rate>>yr;
i1=interest(pr ,yr ,rate);
i2=interest(pr , yr);
i3=interest(pr);
cout<<i1<<i2<<i3;
return(0);
}

float interest(int p, int t, float r)
{
            return((p*t*r)/100);
}

In the above program, t and r has default arguments. If we give, as input, values for pr, rate and yr as 5000, 10 and 2, the output will be
                        1000 500 1250

NOTE: The default arguments are specified in function declaration only and not in function definition.
Only the trailing arguments can have default values. We must add defaults from right to left. We cannot provide a default value to a particular argument at the middle of an argument list. Default arguments are used in the situation where some arguments have same value. For eg., interest rate in a bank remains same for all customers for certain time.

Inline Functions

We say that using function s in a program is to save some memory space because all the calls to the functions cause the same code to be executed. However, every time a function is called, it takes a lot of extra time in executing a series of instructions. Since the tasks such as jumping to the function, saving registers, pushing arguments into the stack and returning to the calling function are carried out when a function is called. When a function is small, considerable amount of time is spent in such overheads.

C++ has a solution for this problem. To eliminate the cost of calls to small functions, C++ proposed a new feature called INLINE function.
When a function is defined as inline, compiler copies it s body where the function call is made, instead of transferring control to that function.
A function is made inline by using a keyword “inline” before the function definition.
            Eg.
                        inline void calculate_area(int l,int b)
                        {
                                    return(l * b);
}










It should be noted that, the inline keyword merely sends request, not a command, to a compiler. The compiler may not always accept this request. Some situations where inline expansion may not work are
-          for functions having loop, switch or goto statements
-          for recursive functions
-          functions with static variables
-          for functions not returning values, if a return statement exists
Inline functions must be defined before they are called.
Eg.
            #include<iostream.h>
           
inline float lbtokg(float lbs)
            {
                        return (0.453 * lbs);
}

           
main()
{
            float lbs, kgs;
            cout<<”Enter weight in lbs:”;
            cin>>lbs;
            kgs=lbtokg(lbs);
            cout<<”Weight in kg is ”<<kgs;
            return (0);
}


Exercise:
            When do we use inline function? Explain with example.
            When do we use default argument? Explain with example.
           

Function Overloading


Function that share the same name are said to be overloaded functions and the process is referred to as function overloading. i.e. function overloading is the process of using the same name for two or more functions. Each redefinition of a function must use different type of parameters, or different sequence of parameters or different number of parameters. The number, type or sequence of parameters for a function is called the function signature. When we call the function, appropriate function is called based on the parameter passed. Two functions differing only in their return type can not be overloaded. For eg-
int add(int , int ) and float add(int, int)

A function call first matches the declaration having the same number and type of arguments and then calls the appropriate function for execution. A best match must be unique. The function selection will involve the following steps:
-          the compiler first tries to find an exact match in which the types of actual arguments are the same and uses that function
-          if an exact match is not found, the compiler uses the integral promotion to the actual parameters, such as,
§  char to int
§  float to double to find the match
-          If both of the above fail, the compiler tries to use the built-in conversions and then uses the function whose match is unique.

#include<iostream.h>
//function declaration
float perimeter(float);
int perimeter(int,int);
int perimeter(int,int,int);

main()
{
            cout<<”Perimeter of a circle: ”<<perimeter(2.0)<<endl;
            cout<<”Perimeter of a rectangle: ”<<perimeter(10,10)<<endl;
            cout<<”Perimeter of a triangle: ”<<perimeter(5,10,15);
            return (0);
}

//function definition
float perimeter(float r)
{
            return(2*3.14*r);
}
int perimeter(int l,int b)
{
            return(2*(l+b));
}
int perimeter(int a,int b,int c)
{
            return(a+b+c);
}

In the above program, a function “perimeter” has been overloaded. The output will be as follows:
            Perimeter of a circle 12.56
            Perimeter of a rectangle 40
Perimeter of a triangle 30

Sunday, November 18, 2012

Basic program constructs in C++



Basic program constructs in C++

Following is a sample program in C++ that prints a string on the string.

#include<iostream.h>
int main()
{
            cout<<”Hi Everybody”;
            return 0;
}

Like in C, functions are the basic building block in C++. The above example consists of a single function called main ().

When a C++ program executes, the first statement that executes will be the first statement in main () function. The main function calls member functions of various classes (using objects) to carry out the real work. It may also call other stand-alone functions.

In C++, the return type of the main function is ‘int’. So, it returns one integer value to the operating system. Since the return type int is default, the keyword ‘int’ in main () is optional. So,

            main ()
            {
                …….// also valid
            }

Compilers generate error if no value is returned. Many operating systems test the return values. If the exit value is zero (0), the operating system will understand that the program ran successfully. If the returned value (exit value) is non zero, it would mean that there was problem.

Comment syntax
In C++, comments start with a double slash (//) symbol and end at the end of the line. A comment may start at the beginning of a line or anywhere in the line and whatever follows till the end of that line is ignored. There is no closing symbol. If we need to comment multiple lines, we can write as
// this is an
// example
// of multi line comments

The C comment style /*………….*/ may also be used for multi line comments.

The output operator
The statement – cout<<”Hi Everybody”; in the above example prints the phrase in quotation marks on the screen.

Here, the identifier ‘cout’, pronounced as see out, is a predefined object of standard stream in C++. The operator << is called ‘insertion’ or ‘put to’ operator. It inserts the content on its right to the object on its left.
            cout<<a
In the above case, the statement will display the content of the variable ‘a’.

The input operator
A statement
                        cin>>a;
is an input statement.  This causes the program to wait for the user to type and give some input. The given input is stored in the variable a.
Here, the identifier ‘cin’, pronounced as ‘see in’ is an object of standard input stream. The operator ‘>>’ is called ‘extraction’ or ‘get from’ operator. It extracts or gets value from keyboard and assigns it to the variable on its right.

Cascading I/O operators
The i/o operators can be used repeatedly in a single i/o statements as follows.
            cout<<a<<b<<c;
            cin>>x>>y>>z;
These are perfectly legal. The above cout statement first sends the value of ‘a’ to cout, then sends the value of b and then sends the value of c. Similarly, the cin statement first reads a value and stores in x, then reads again and stores in y and then in z. The multiple uses of i/o operators in one statement is called cascading.

The iostream header file
The directive ‘#include<iostream.h>’ causes the preprocessor to add the contents of iostream.h file to the program. It contains the declarations of identifiers cout, cin and the operators << and >>. So, the header file iostream should always be included at the beginning if we need to use cin, cout, << and >> operators in our program.

Tokens: Tokens are the smallest individual units in a program. Keywords, identifiers, constants, strings and operators are tokens in C++.

Keywords: Keywords are explicitly reserved identifiers and can not be used as names for the program variables or other user-defined program elements. Some keywords are int, auto, switch, case, do, else, public, default, continue etc.

Functions

A function is a single comprehensive unit that performs a specified task. This specified task is repeated each time the function is called. Functions break large programs into smaller tasks. They increase the modularity of the programs and reduce code redundancy.
Like in C, C++ programs also should contain a main function, where the program always begins execution. The main function may call other functions, which in turn will again call other functions.
When a function is called, control is transferred to the first statement of the function body. Once the statements of the function get executed (when the last closing bracket is encountered) the program control return to the place from where this function was called.

Data types in C++


Fig. Hierarchy of C++ Data types

Enumerated Data Types
Like structures, enumerated data type is another user defined data type. Enumerated means that all the values are listed. They are used when we know a finite list of values that a data type can take on or it is an alternative way for creating symbolic constants. The ‘enum’ keyword automatically lists a list of words and assign them values 0,1,2…

Eg.  enum shape  {circle, square, triangle};
        enum Boolean  {true, false};
        enum switch  {on, off};

The above example is equivalent to
            const  circle = 0;
            const square = 1;
            const triangle = 2;
We can even use standard arithmetic operator on enum types. We can also use relational operators when suitable. This is because, the enum data types are internally treated as integers.
Once we specify the data type, we need to define variables of that type.
            Eg. shape s1,s2;
Now the variables s1, s2 can hold only the members of ‘shape’ data type (those are circle, square and triangle) and can not hold anything except these values. If other values are given, error will be generated.

An example
#include<iostream.h>
#include<conio.h>
enum days {sun, mon, tue, wed, thur, fri, sat};
void main()
{
            days d1,d2;
            d1 = sun;
            d2 = thur;
            int diff = d2-d1;  // using arithmetic operator
            cout<<”Days between”<<diff<<endl;
            if(d1<d2)   // using relational operator
                        cout<<”d1 comes first”;
            getch();
}

Reference variables
Reference variables are new type of variable introduced in C++. It provides an alias (another name) for a previously defined variable. A syntax to create a reference variable is
            data-type  &reference-name = variable name;
eg-
            float total = 100;
            float &sum = total; // creating reference variable for ‘total’.

In the above example, we are creating a reference variable ‘sum’ for an existing variable ‘total’. Now these can be used interchangeably. Both of these names refer to same data object in memory. If the value is manipulated and changed using one name then it will change for another also. Eg- the statement
            total = total + 200; will change value of ‘total’ to 300. And it will also change for ‘sum’. So the statements
cout<<sum;
cout<<total; both will print 300. This is because both the variables use same data object in memory.

-          A reference variable must be initialized at the time of declaration, since this will establish correspondence between the reference and the data object which it names.
-          The symbol & is not an address operator here. The notation int & means reference to integer type data.
-          References can also be created for user defined data types like structures and classes.
-          Another application of reference variable is in passing arguments to function.

In general, arguments are passed by value. The called function creates a new value of the same type as the argument and copies the argument value into it. The function does not access the actual value. Although this provides security to the actual data, it is not suitable if we need to modify actual data. For such situations, we can use reference. Instead of value, a reference to the original variable is passed to the called function. This is called calling function by reference. The advantage is that the called function can use actual variable and not its copy only. Likewise, we can also return values using reference. (Example- swapping values)

Manipulators
The manipulators are operators used with insertion operator “<<’ to format or manipulate the data display. ‘endl’ and ‘setw’ are most common manipulators.

endl manipulator causes a linefeed to be inserted into the output stream. i.e the cursor moves to next line. It is similar to ‘\n’ character.
Eg-
                        cout<<”Kathmandu”<<endl;
                        cout<<”Nepal”;
See output

setw manipulator specify a field width to a number or string that follows it and force them to be printed right justified. The field width is given as an argument to this manipulator.
Eg-
                        x = 456; y = 40;
                        cout<<setw(5)<<x<<setw(5)<<y;

The manipulator will specify a field 5 for printing the value of x. The value is right justified within the fields as shown below. For y, it will specify again space of width 5, right justifies and prints.