February 2018

Inline function in C++ Programming

A inline function is a short-code function  written and placed before main function  and compiled as inline code. The prototyping is not required for inline function. It starts with keyword inline . In ordinary functions, when function is invoked the control is passed to the calling function and after executing the function the control is passed back to the calling program.
         But , when inline function is called, the inline code of the function is inserted at the place of call and compiled with the other source code together. That is the main  feature of inline function and different from the ordinary function.  So using inline function executing time is reduced because there is no transfer and return back to control. But if function has long code inline function is not suitable because it increases the length of source code due to inline compilation.

// Inline Function
//saves memory, the call to function cause the same code to be
//executed;the function need not be duplicated in memory
#include<iostream.h>
#include<conio.h>
inline float lbstokg(float pound)
{
return (0.453592*pound);
}
 void main()
{
float lbs1=50,lbs2=100; 
cout<<"Weinght in Kg:"<<lbstokg(lbs1) <<endl; 
cout<<"Weinght in Kg:" <<lbstokg(lbs2) <<endl; 
getch();
}


Function in C++ Programming

Default Arguments 

        When declaring a function we can specify a default value for each of the last parameters which are called default arguments. This value will be used if the corresponding argument is left blank when calling to the function. To do that, we simply have to use the assignment operator and a value for the arguments in the function declaration. If a value for that parameter is not passed when the function is called, the default value is used, but if a value is specified this default value is ignored and the passed value is used instead. 

For example:

// default values in functions

using namespace std;
int divide (int a, int b=2)
{
int r; r=a/b;
return (r);
}
int main ()
{
cout << divide (12);
cout << endl;
cout << divide (20,4);
return 0;
}

As we can see in the body of the program there are two calls to function divide. In the first one:

divide (12)

We have only specified one argument, but the function divide allows up to two. So the function divide has assumed that the second parameter is 2 since that is what we have specified to happen if this parameter was not passed (notice the function declaration, which finishes with int b=2, not just int b). Therefore the result of this function call is 6 (12/2).

In the second call: divide (20,4) There are two parameters, so the default value for b (int b=2) is ignored and b takes the value passed as argument, that is 4, making the result returned equal to 5 (20/4).


Inline Functions 

Function call is a costly operation. During the function call it’s execution our system takes overheads like: Saving the values of registers, Saving the return address, Pushing arguments in the stack, Jumping to the called function, Loading registers with new values, Returning to the calling function, and reloading the registers with previously stored values. For large functions this overhead is negligible but for small function taking such large overhead is not justifiable. To solve this problem concept of inline function is introduced in c++.

The functions which are expanded inline by the compiler each time it’s call is appeared instead of jumping to the called function as usual is called inline function. This does not change the behavior of a function itself, but is used to suggest to the compiler that the code generated by the function body is inserted at each point the function is called, instead of being inserted only once and perform a regular call to it, which generally involves some additional overhead in running time. Example: 

#include<isostream.h>    
#include<conio.h> 
inline void sum(int a int b) 

int s; 
s= a+b; 
cout<<”Sum=”<<s<<end1;
}
Void main() 

clrscr(); 
int x, y; 
cout<<”Enter two numbers”<
cin>>x>>y 
sum(x,y); 
getch(); 
}


Here at the time of function call instead of jumping to the called function, function call statement is replaced by the body of the function. So there is no function call overhead.



Overloaded functions 

In C++ two different functions can have the same name if their parameter types or number are different. That means that you can give the same name to more than one function if they have either a different number of parameters or different types in their parameters. This is called function overloading. For example:

// overloaded function
#include  
int mul (int a, int b)
{
return (a*b);
}
float mul (float a, float b)
{
return (a*b);
}
int main ()
{
 int x=5,y=2;
float n=5.0,m=2.0;
cout << mul (x,y);
cout << "\n";
cout << mul(n,m);
 cout << "\n";
 return 0;
}


In the first call to “mul” the two arguments passed are of type int, therefore, the function with the first prototype is called; This function returns the result of multiplying both parameters. While the second call passes two arguments of type float, so the function with the second prototype is called. Thus behavior of a call to mul depends on the type of the arguments passed because the function has been overloaded.

Notice that a function cannot be overloaded only by its return type. At least one of its parameters must have a different type.


Arguments passed by value and by reference 

In case of pass by value, Copies of the arguments are passed to the function not the variables themselves. For example, suppose that we called our function addition using the following code: // function example
#include  
int addition (int a, int b)
{
int r;  r=a+b;
 return (r);
}
int main ()
{
int z;
int x=5, y=3;
 z = addition (x,y);
cout << "The result is " << z;
return 0; }

What we did in this case was to call to function addition passing the values of x and y, i.e. 5 and 3 respectively, but not the variables x and y themselves.

When the function addition is called, the value of its local variables a and b become 5 and 3 respectively, but any modification to either a or b within the function addition will not have any effect in the values of x and y outside it, because variables x and y were not themselves passed to the function, but only copies of their values at the moment the function was called.

In case of pass by reference, Address of the variables (variable itself) not copies of the arguments are passed to the function. For example, suppose that we called our function addition using the following code: // function example
 
int addition (int &a, int &b)
{
int r;  r=a+b;
return (r);
}
int main ()
{
int z;
int x=5, y=3;
z = addition (x,y);
cout << "The result is " << z;
return 0;
}


What we did in this case was to call to function addition passing the variables x and y themselves (not values 5 and 3) respectively.

When the function addition is called, the value of its local variables a and b points to the same memory location respectively, therefore any modification to either a or b within the function addition will also have effect in the values of x and y outside it. 

Return by Reference 

If we return address (refrence) rather than value from a function then it is called return by reference. #include 

int& min(int &x, int &y)
{
if(x}
void main()
{
clrscr();
int a,b,r;
cout<<”Enter two numbers”<>a>>b; 
min(a,b)=0; cout<<”a=”<

getch();

Here min function return the reference of the variable which is smaller between a and b and the statement “min(a.b)=0” makes the value of the variable zero which is smaller.

Structured Programming in C++ Programming

Structured programming (sometimes known as modular programming) is a subset of procedural programming that enforces a top-down design model, in which developers map out the overall program structure into separate subsections to make programs more efficient and easier to understand and modify similar functions is coded in a separate module or sub-module, which means that code can be loaded into memory more efficiently and that modules can be reused in other programs. In this technique, program flow follows a simple hierarchical model that employs three types of control flows: sequential, selection, and iteration.


Almost any language can use structured programming techniques to avoid common pitfalls of unstructured languages. Most modern procedural languages include features that encourage structured programming. Object-oriented programming (OOP) can be thought of as a type of structured programming, uses structured programming techniques for program flow, and adds more structure for data to the model. Some of the better known structured programming languages are Pascal, C, PL/I, and Ada.


Object-oriented Programming 

The fundamental idea behind object-oriented programming is to combine or encapsulate both data (or instance variables) and functions (or methods) that operate on that data into a single unit. This unit is called an object. The data is hidden, so it is safe from accidental alteration. An object’s functions typically provide the only way to access its data. In order to access the data in an object, we should know exactly what functions interact with it. No other functions can access the data. Hence OOP focuses on data portion rather than the process of solving the problem.

An object-oriented program typically consists of a number of objects, which communicate with each other by calling one another’s functions. This is called sending a message to the object. This kind of relation is provided with the help of communication between two objects and this communication is done through information called message. In addition, object-oriented programming supports encapsulation, abstraction, inheritance, and polymorphism to write programs efficiently. Examples of object-oriented languages include Simula, Smalltalk, C++, Python, C#, Visual Basic .NET and Java etc.


Object-Oriented Concepts 

The basic concepts underlying OOP are: Class, Object, abstraction, encapsulation, inheritance, and polymorphism.

 Abstraction:
             Abstraction is the essence of OOP. Abstraction means the representation of the essential features without providing the internal details and complexities. In OOP, abstraction is achieved by the help of class, where data and methods are combined to extract the essential features only. Encapsulation: Encapsulation is the process of combining the data (called fields or attributes) and functions (called methods or behaviors) into a single framework called class. Encapsulation helps preventing the modification of data from outside the class by properly assigning the access privilege to the data inside the class. So the term data hiding is possible due to the concept of encapsulation, since the data are hidden from the outside world.

 Inheritance: 

              Inheritance is the process of acquiring certain attributes and behaviors from parents. For examples, cars, trucks, buses, and motorcycles inherit all characteristics of vehicles. Object-oriented programming allows classes to inherit commonly used data and functions from other classes. If we derive a class (called derived class) from another class (called base class), some of the data and functions can be inherited so that we can reuse the already written and tested code in our program, simplifying our program.

 Polymorphism: 

              Polymorphism means the quality of having more than one form. The representation of different behaviors using the same name is called polymorphism. However the behavior depends upon the attribute the name holds at particular moment.

Advantages of Object-oriented Programming 

Some of the advantages are: 

 Elimination of redundant code due to inheritance, that is, we can use the same code in a base class by deriving a new class from it.
 Modularize the programs. Modular programs are easy to develop and can be distributed independently among different programmers.
 Data hiding is achieved with the help of encapsulation.
 Data centered approach rather than process centered approach.
 Program complexity is low due to distinction of individual objects and their related data and functions.
 Clear, more reliable, and more easily maintained programs can be created.

Object-based Programming 

The fundamental idea behind object-based programming is the concept of objects (the idea of encapsulating data and operations) where one or more of the following restrictions apply:
1. There is no implicit inheritance
2. There is no polymorphism
3. Only a very reduced subset of the available values are objects (typically the GUI components)

Object-based languages need not support inheritance or sub-typing, but those that do are also said to be object-oriented. An example of a language that is object-based but not object-oriented is Visual Basic (VB). VB supports both objects and classes, but not inheritance, so it does not qualify as object-oriented. Sometimes the term object based is applied to prototype-based languages, true object-oriented languages that do not have classes, but in which objects instead inherit their code and data directly from other template objects. An example of a commonly used prototype-based language is JavaScript.


Output Using cout 

The keyword cout (pronounced as ‘C out’) is a predefined stream object that represents the standard output stream (i.e monitor) in C++. A stream is an abstraction that refers to a flow of data.

The << operator is called insertion or put to operator and directs (inserts or sends) the contents of the variable on its right to the object on its left. For example, in the statement cout<<"Enter first value:"; the << operator directs the string constant “Enter first value” to cout, which sends it for the display to the monitor.


 Input with cin 

The keyword cin (pronounced ‘C in’) is also a stream object, predefined in C++ to correspond to the standard input stream (i.e keyword). This stream represents data coming from the keyboard.

The operator >> is known as extraction or get from operator and extracts (takes) the value from the stream object cin its left and places it in the variable on its right. For example, in the statement cin>>first;, the >> operator extracts the value from cin object that is entered from the keyboard and assigns it to the variable first.

Cascading of I/O operators 

We can use insertion operator (<<) in a cout statement repeatedly to direct a series of output streams to the cout object. The streams are directed from left to right. For example, in the statement cout<<Sum=”<
Similarly, we can use extraction operator (>>) in a cin statement repeatedly to extract a series of input streams from the keyboard and to assign these streams to the variables, allowing the user to enter a series of values. The values are assigned from left to right. For example, in the statement cin>>x>>y;, the first value entered will be assigned to the variable x and the second value entered will be assigned to variable y.

Manipulators 

Manipulators are the operators used with the insertion operator (<<) to modify or manipulate the way data is displayed. The most commonly used manipulators are endl, setw, and setprecision.
The end l Manipulator 
           This manipulator causes a linefeed to be inserted into the output stream. It has the same effect as using the newline character ‘\n’. for example, the statement
cout<<First value =”<will cause two lines of output.

The setw Manipulator 
           This manipulator causes the output stream that follows it to be printed within a field of n characters wide, where n is the argument to setw(n). The output is right justified within the field. For example,
cout<Output:   
John
is
boy
The setprecision Manipulator 
           This manipulator sets the n digits of precision to the right of the decimal point to the floating point output, where n is the argument to setprecision(n). For example,
float a = 42.3658945, b = 35.24569, c = 58.3214789, d = 49.321489; cout

Output:
42.365894
35.246
58.321
49.32
Note: The header file for setw and setprecision manipulators is iomanip.h.


Reference Variable 

Reference variable is an alias (another name) given to the already existing variables of constants. When we declare a reference variable memory is not located for it rather it points to the memory of another variable.
Consider the case of normal variables
Structured Programming



Structured Programming

Type Conversion 

There are two types of type conversion: automatic conversion and type casting.
Automatic Conversion (Implicit Type Conversion) 
When two operands of different types are encountered in the same expression, the lower type variable is converted to the type of the higher type variable by the compiler automatically. This is also called type promotion. The order of types is given below:
Structured Programming



Type Casting 

Sometimes, a programmer needs to convert a value from one type to another in a situation where the compiler will not do it automatically. For this C++ permits explicit type conversion of variables or expressions as follows:
(type-name) expression //C notation
type-name (expression) //C++ notation
For example, 
int a = 10000;
int b = long(a) * 5 / 2; //correct
int b = a * 5/2; //incorrect (can you think how?) 

C Program For Matrix Multiplication

#include<stdio.h>
#include <conio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10],multiply[10][10];
printf("Enter number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
printf("Enter elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);
if (n != p)
printf("The matrices can't be multiplied with each other.\n");
else
{
printf("Enter elements of second matrix\n");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
for (c = 0; c < m; c++){
for (d = 0; d < q; d++)
{
for (k = 0; k < p; k++)
{
sum = sum + first[c][k]*second[k][d];}
multiply[c][d] = sum;
sum = 0;
}
}
printf("Product of the matrices:\n");
for (c = 0; c < m; c++)
{
for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);
printf("\n");
}
}
return 0;
}

OUTPUT

C Program For Matrix Multiplication | C Programming


Matrix Chain Multiplication

  • Matrix chain multiplication (or Matrix Chain Ordering Problem, MCOP) is an optimization problem that can be solved using dynamic programming.
  • Given a sequence of matrices, the goal is to find the most efficient way to multiply these matrices.
  • The problem is not actually to perform the multiplications, but merely to decide the sequence of the matrix multiplications involved.
  • Here are many options because matrix multiplication is associative. In other words, no matter how the product is parenthesized, the result obtained will remain the same. For example, for four matrices A, B, C, and D, we would have:

((AB)C)D = ((A(BC))D) = (AB)(CD) = A((BC)D) = A(B(CD))
Matrix Chain Multiplication

Example of Matrix Chain Multiplication


Example:
Sequence {4, 10, 3, 12, 20, and 7}. The matrices have size 4 x 10, 10 x 3, 3 x 12, 12 x 20, 20 x 7. We need to compute M [i,j], 0 ≤ i, j≤ 5.
We know M [i, i] = 0 for all i.
Matrix Chain Multiplication
Matrix Chain Multiplication

Here P0 to P5 are Position and M1 to M5 are matrix of size (pi to pi-1
On the basis of sequence, we make a formula
Matrix Chain Multiplication

In Dynamic Programming, initialization of every method done by '0'.So we initialize it by '0'.It will sort out diagonally.
We have to sort out all the combination but the minimum output combination is taken into consideration.
Matrix Chain Multiplication
Matrix Chain Multiplication

Pseudo code

Matrix Chain Multiplication


Union In C Programming  

Unions in c is like structure contain members whose individual data types may differ from one another. However, the members that compose a union all share the same storage area within the computer's memory whereas each member within a structure is assigned its own unique storage area.  Thus unions are used to observe memory.  They are useful for application involving multiple members, where values need not be assigned to all the members at any one time. Like structures union can be declared using the keyword union as follows:           

union item
         
{                 
int m;               
 float p;                 
char c;         
}         
code;
     
This declares a variable code of type union item. The union contains three members each with    a different data type. However, we can use only one of them at a time. This is because if only    one location is allocated for union variable irrespective of size. The compiler allocates a piece    of storage that is large enough to access a union member we can use the same syntax that we    use to access structure members. That is
            
code.m       
 code.p         
code.c
     
are all valid member variables? During accessing we should make sure that we are accessing    the member whose value is currently stored.   
For example, a statement such as
            
code.m=456;           
code.p=456.78;           
printf(“%d”,code.m);     



  More on Structure  

  typedef Keyword      

There is an easier way to define structs or you could "alias" types you create. For example:   
typedef struct
 
{       
char firstName[20];
 char lastName[20];       
char SSN[10];       
float gpa;       
}
 student; 

Now you can use student directly to define variables of student type without using struct keyword. Following is the example:
          
student student_a;   
You can use typedef for non-structs:     
typedef long int *pint32;             
pint32 x, y, z;                 
 x, y and z are all pointers to long ints

Structure In C Programming 

  Arrays are used to store large set of data and manipulate them but the disadvantage is that all the elements stored in an array are to be of the same data type. If we need to use a collection of different data type items it is not possible using an array. When we require using a collection of different data items of different data types we can use a structure.  Structure is a method of grouping data of different types.  A structure is a convenient method of handling a group of related data items of different data types.  



Structure declaration: 

General format:   
struct tag_name{          
data type member1;   
data type member2;   
…   
};
 Example:      
struct lib_books       
{ char title[20];   
char author[15];             
int pages;            
float price;         
};   
   
the keyword struct declares a structure to holds the details of four fields namely title, author pages and price. These are members of the structures. Each member may belong to different or same data type. The tag name can be used to define objects that have the tag names structure. The structure we just declared is not a variable by itself but a template for the structure. We can declare structure variables using the tag name anywhere in the program. For example the statement,                   
  
struct lib_books book1, book2, book3;    
 declares book1, book2, book3 as variables of type struct lib_books each declaration has four  elements of the structure lib_books. The complete structure declaration might look like this                     struct lib_books                   
{                           
char title[20];                           
char author[15];                         
int pages;                        
 float price;                   
};   
                  struct lib_books, book1, book2, book3;     

structures do not occupy any memory until it is associated with the structure variable such as book1. The template is terminated with a semicolon. While the entire declaration is considered as a statement, each member is declared independently for its name and type in a separate statement inside the template. The tag name such as lib_books can be used to declare structure variables of its data type later in the program. We can also combine both template declaration and variables declaration in one statement, the declaration             
struct lib_books           
{                   
char title[20];                   
char author[15];                   
int pages;                   
float price;             
} book1, book2, book3;       
is valid. The use of tag name is optional for example             
struct           
{                   
…                  
 …                   
…             
} book1, book2, book3;      

declares book1, book2, book3 as structure variables representing 3 books but does not include a    tag name for use in the declaration.       

A structure is usually defining before main along with macro definitions. In such cases the    structure assumes global status and all the functions can access the structure.     


  Giving values to members       

As mentioned earlier the members themselves are not variables they should be linked to    structure variables in order to make them meaningful members. The link between a member    and a variable is established using the member operator „. ‟ which is known as dot operator or    period operator.       For example:                    
 Book1.price       

Is the variable representing the price of book1 and can be treated like any other ordinary   variable. We can use scanf statement to assign values like                 
          scanf(“%s”,book1.file);   
          scanf(“%d”,& book1.pages);      

 Or we can assign variables to the members of book1                 

strcpy(book1.title,”basic”);                 
strcpy(book1.author,”Balagurusamy”);              
 book1.pages=250;               
book1.price=28.50;    

Assignment to Students      

Explain how to access array elements and to display those elements under two topics: (i)    Accessing array elements (ii) displaying array elements.  

Functions and structures       

We can pass structures as arguments to functions. Unlike array names however, which always    point to the start of the array, structure names are not pointers. As a result, when we change    structure parameter inside a function, we don‟t affects its corresponding argument.   


Passing structure to elements to functions     

A structure may be passed into a function as individual member or a separate variable.     A program example to display the contents of a structure passing the individual elements to a    function is shown below.              
 #include            
#include          
void fun(float,int);         
 void main()          
{                 
 struct student                  
{                        
float marks;                        
int id;            
};                  
struct student s1={67.5,14};                    
fun(s1.marks,s1.id);                  
getch();          }          
void fun(float marks,int id)          
{                     
printf("\nMarks:%f",marks);                    
printf("\nID:%d",id);          
}      

It can be realized that to pass individual elements would become more tedious as the number of structure elements go on increasing a better way would be to pass the entire structure variable    at a time.     


Passing entire structure to functions       

In case of structures having to having numerous structure elements passing these individual    elements would be a tedious task. In such cases we may pass whole structure to a function as    shown below:              
 # include stdio.h>           
{                   
int emp_id;                   
char name[25];                   
char department[10];                  
 float salary;           
};           
void main()           
{                   
static struct employee emp1= { 12, “sadanand”, “computer”, 7500.00 };                    
 /*sending entire employee structure*/                   
display(emp1);           
}               
/*function to pass entire structure variable*/             
display(empf)           
struct employee empf           
{                     
printf(“%d%s,%s,%f”, empf.empid,empf.name,empf.department,empf.salary);           
}     

  Arrays of structure      

It is possible to define an array of structures for example if we are maintaining information of all the students in the college and if 100 students are studying in the college. We need to use an array than single variables. We can define an array of structures as shown in the following example:             structure information           
{                   
int id_no;                   
char name[20];
 char address[20];                   
char combination[3]; 
int age;           
}            
 student[100];       

An array of structures can be assigned initial values just as any other array can. Remember that    each element is a structure that must be assigned corresponding initial values as illustrated  
  below.   
           
 #include< stdio.h >           
void main()          
{                   
struct info                   
{                        
 int id_no;                         
char name[20];                         
char address[20];                        
 char combination[3];                        
 int age;                   
};                  
struct info std[100];                   
int i,n;                     
printf(“Enter the number of students”);                   
scanf(“%d”,&n);                   
for(i=0;i < n;i++)                   
{                         
 printf(“ Enter Id_no,name address combination age\m”);                                scanf("%d%s%s%s%d”,&std[I].id_no,std[I].name,std[I].address,std[I].                           combination,&std[I].age);                  
}                   
printf(“\n Student information”);                   
for (I=0;I< n;I++)                   
{                         
 printf(“%d%s%s%s%d\n”,                              std[I].id_no,std[I].name,std[I].address,std[I].combination,std[I].age);                  
}          
}     

Structure within a structure       

A structure may be defined as a member of another structure. In such structures, the declaration of the embedded structure must appear before the declarations of other structures.        struct date  int id_no;     
{  
char name[20];     
int day;  
char address[20];     
int month;  
char combination[3];     
int year;  int age;     
};  
structure date def;     
struct student  structure date doa;     
{  }oldstudent, newstudent;        

the structure student contains another structure date as its one of its members.