Wednesday, January 4, 2017

Pass by reference using Pointer and Dynamic memory allocation


Pass by reference using Pointer :

#include<iostream>

using namespace std;

 void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
int main()
{
int x=2,y=3;
cout<<"Before swap: "<<endl; cout<<x<<" "<<y<<endl;
swap(&x,&y);
cout<<"After swap: "<<endl;
cout<<x<<" "<<y;
return 0;
}

Output:
 Before swap: 2 3
After swap:
3 2

Here, int * a= &x; it means that *a =x i.e. *a=2 and similarly *b=3. After swap *a=3 and *b =2 this means also x=3 and y=2.

Dynamic memory allocation using new and delete operator:

How does dynamic memory allocation work?

Your computer has memory (probably lots of it) that is available for applications to use. When you run an application, your operating system loads the application into some of that memory. This memory used by your application is divided into different areas, each of which serves a different purpose. One area contains your code. Another area is used for normal operations (keeping track of which functions were called, creating and destroying global and local variables, etc…). We’ll talk more about those later. However, much of the memory available just sits there, waiting to be handed out to programs that request it.
When you dynamically allocate memory, you’re asking the operating system to reserve some of that memory for your program’s use. If it can fulfill this request, it will return the address of that memory to your application. From that point forward, your application can use this memory as it wishes. When your application is done with the memory, it can return the memory back to the operating system to be given to another program.
Unlike static or automatic memory, the program itself is responsible for requesting and disposing of dynamically allocated memory.

#include <iostream>
 int main()
{
int *ptr = new int; // dynamically allocate an integer
*ptr = 7; // put a value in that memory location
delete ptr; // return the memory to the operating system. ptr is now a d angling pointer.

ptr =0; //ptr is now a nullptr
return 0;

}

Thursday, December 29, 2016

Function And Function Overloading

Functions:

 Function syntax:





#include<iostream>


using namespace std;


void  add();


int main()


{


 add();


 return 0;


}


void add()


{


 int a,b,c;


cout<<”Enter a” <<endl;


 cin>>a;


cout<<”Enter b”<<endl;


cin>>b;

c=a+b;
cout<<”c value “<<c <<endl;
}


1. Function declaration or prototype:

Function declaration tells compiler that same function with respective name and argument are somewhere in program. If declaration is not done at the beginning then the function must be defined before main () function.

2. Function call:

Function is call inside from the main () function.

3. Function definition:

All the statement which shows certain operation, is placed inside the function and is called, function is defined.

Syntax for function:

Data_type + function_name (arguments)

Advantages:

1.       Save memory space.
2.       Make program clear.
3.       Easy to debug.

 Function Overloading:

Function overloading occurs in the program when no of functions have same name but different arguments.

Advantages:
Having same name for all function reduces ambiguity because it is easy to remember the name of function.

Example:


#include<iostream>


 using namespace std;


 void m1(int i)


{


cout<<"Int-args:"<<endl;


}


void m1(float f)


{


 cout<<"Float-args:"<<endl;


}


int main()


{


m1(2);

m1(2.3f);
return 0;
}


Output:
Int-args:
Float-args:

Here, both functions have same name but different arguments. When integer is passed then “Int-
args:” is executed and when float is passed then “Float-args” is executed.

 Promotion Rules

Byte->short
int->long->float ->double-> double
Char

Example:



#include<iostream>


 using namespace std;


 void m1(char c)


{


cout<<"char-args:"<<endl;


}


void m1(int i)


{


cout<<"int-args:"<<endl;


}


void m1(int i,float f)

{
cout<<"int-float-args:"<<endl;
}
void m1(float f,int i)
{
cout<<"float-int-args:"<<endl;
}
int main()
{
m1('c');
m1(2);
m1(3,2.0);
 m1(2.0,3);
return 0;
}


Output:

char-args: int-args: int-float-args: float-int-args

While resolving function overloading if exact matched function is not available then we won’t get any compile time error immediately. First it will promote argument to the next level and checked whether matched function is available or not. If matched function is available then it will be considered.
If matched method is not available then compiler promotes argument one again to the next level. This process will be continued until all possible promotions. Still if the matched function is not available then we will get compile time error.
So here in example, exact matched for char argument is not found so it promotes to next level int and hence finally it matched it and result is shown as “Int-args” for char argument also.

Conversion rules:



#include<iostream>

 using namespace std;

int main()

{

int a=2,b=3;

 float c;

c=a/b;

cout<<"The value of c:"<<c<<endl;
return 0;
}


Output :
The value of c: 0

Here, the output must be 0.666667 but it shows 0. Why?
Ans: (2/3)=(0.66667) but as default it takes only integer value and so 0 becomes output.





#include<iostream>


using namespace std;


int main()
{

int a=2,b=3;

float c;
c=(foat)a/b;
cout<<"The value of c:"<<c<<endl;
return 0;
}


Output
The value of c: 0.666667
Here, float is used as conversion where it takes the float value instead of int
value.

 Inline function:

Inline keyword used in function is just a request to compiler to copy the function definition in a place, from where it is called rather than to transfer the control from one memory location to another. It is feasible only when the function definition has small segment of code.

Advantages:

It increases execution time of function.

Example:



#include<iostream>


 using namespace std;


inline void add()


{
int a,b,c;
cout<<”Enter a” <<endl;
cin>>a;
cout<<”Enter b”<<endl;
cin>>b;
c=a+b;
cout<<”c value “<<c <<endl;
}
int main()
{
add();
cout <<”again call”<<endl;
add();
return 0;


}

Wednesday, December 28, 2016

General C++ Program Structure

General C++ Program Structure

#include<iostream>
using namespace std;
int main(){
cout<<”hello world”<<endl;
return 0;
}


1. #include<iostream>
This line is a pre-processing directive. All pre-processing directives within C++ source code begin with a # symbol. This one directs the pre-processor to add some predefined source code to our existing source code before the compiler begins to process it. This process is done automatically and is invisible to us.

2. Using namespace std
The two items our program needs to display a message on the screen, cout and endl, have longer names: std::cout and std::endl. This Using namespace std directive allows us to omit the std::prefix and use their shorter names. name std stands for “standard,” and the Using namespace std line indicates that some of the names we use in our program are part of the so-called “standard namespace.”

3. Int main()
This specifies the real beginning of our program. Here we are declaring a function named main.

Q. Why always main? Is it possible to use any other name besides main?

Ans: Compiler has instruction to search for keyword main. If compiler is instructed to search for other name as your choice besides main then the program must have you search name which you instruct to search for compiler. Return value 0 is also not necessary, you can return any integer value. But compiler does not care about any value you return. So it is considered better to return 0.
4. cout<<”hello world”<<endl;

The body of our main function contains only one statement. This statement directs the executing program to print the message hello world on the screen. A statement is the fundamental unit of execution in a C++ program. Functions contain statements that the compiler translates into executable machine language instructions. All statements in C++ end with a semicolon (;).

Monday, December 26, 2016

The Need of C++

The Need of C++:

1.       If you know C/C++ better, you can easily understand Java, JavaScript, and many other C-style languages.
2.       If you want to find out some implementation detail about operating system, Linux or minix would be the best choice, and they are both written in C/C++.
3.       There are tremendous excellent tools/libraries that are written in C/C++, which you can use to build the basic blocks of your project.
4.       If you want to write programs (Android apps, server side programs, etc.) they are secure and efficient, you should consider using C/C++.

Features of C++:

1.       Function overloading
2.       Inline function
3.       Operator overloading
4.       Easier way of memory management
5.       Run time polymorphism
6.       Stream class library for easier input/output
7.       Exception handling
8.       Run time information

History of C++:

During the late 1970s and early 1980s, C became the dominant computer programming language, and it is still widely used today. Since C is a successful and useful language, you might ask why a need for something else existed. The answer is complexity.  Throughout the history of programming, the increasing complexity of programs has driven the need for better ways to manage that complexity. C++ is response to that need. To better understand why managing program complexity is fundamental to the creation of C++, consider the following.

Approaches to programming have changed dramatically since the invention of the computer. For example, when computers were first invented, programming was done by manually toggling in the binary machine instructions by use of the front panel. As long as programs were just a few hundred instructions long, this approach worked. As programs grew, assembly language was invented so that a programmer could deal with larger, increasingly complex programs by using symbolic representations of the machine instructions. As programs continued to grow, high-level languages were introduced that gave the programmer more tools with which to handle complexity.

The first widespread language was, of course, FORTRAN. While FORTRAN was an impressive first step, it is hardly a language that encourages clear and easy-to understand programs. The 1960s gave birth to structured programming. This is the method of programming championed by languages such as C.

The use of structured languages enabled programmers to write, for the first time, moderately complex programs fairly easily. However, even with structured programming methods, once a project reaches a certain size, its complexity exceeds what a programmer can manage. By the early 1980s, many projects were pushing the structured approach past its limits.

To solve this problem, a new way to program was invented, called object-oriented programming (OOP). Object-oriented programming is discussed in detail later in this book, but here is a brief definition: OOP is a programming methodology that helps organize complex programs through the use of inheritance, encapsulation, and polymorphism.

In the final analysis, although C is one of the world's great programming languages, there is a limit to its ability to handle complexity. Once a program exceeds somewhere between 25,000 and 100,000 lines of code, it becomes so complex that it is difficult to grasp as a totality. C++ allows this barrier to be broken, and helps the programmer comprehend and manage larger programs.

C++ was invented by Bjarne Stroustrup in 1979, while he was working at Bell Laboratories in Murray Hill, New Jersey. Stroustrup initially called the new language "C with Classes."

Use of C++

C++ is used by hundreds of thousands of programmers in essentially every application domain.
C++ is being highly used to write device drivers and other software that rely on direct manipulation of hardware under real-time constraints.
C++ is widely used for teaching and research because it is clean enough for successful teaching of basic concepts.

Anyone who has used either an Apple Macintosh or a PC running Windows has indirectly used C++ because the primary user interfaces of these systems are written in C++.

Click here to download pdf file

Saturday, December 24, 2016

Procedure Oriented Programming (POP) And Object Oriented Programming (OOP)

Procedure Oriented Programming (POP)

The programming language is said to be POP which focuses on procedure or function rather than data. In this programming language when a program is larger, it is then broken into smaller units called procedure or functions. High level programming languages like C, FORTAN, Pascal, etc are common procedure oriented programming languages.

Characteristics of POP:

1.       A large program is broken into small manageable procedures or functions.
2.       POP follows Top Down approach.
3.       POP does not have any access specifier.
4.       In POP, overloading is not possible.
5.       To add new data and functions in POP is not so easy.
6.       POP does not have any proper way for data hiding so it is less secure.
7.       Code reusability is still difficult.

Object Oriented Programming (OOP):

The programming language in which both objects and classes are used called OOP. This programming language focuses on data rather than procedures.OOP is a programming methodology that associates data structures with a set of operators which act upon it. Some common examples of OOP are C++, JAVA, VB.NET, C#.NET, etc.

Characteristics of OOP:

1.       OOP follows Bottom Up approach.
2.       Programs are divided into objects.
3.       OOP has access specifiers named public, private, protected, etc.
4.       In OOP, overloading is possible in the form of function overloading and Operator Overloading.
5.       OOP provides data hiding so it is more secure.
6.       OOP provides an easy way to add new data and function.
7.       Data structures are modeled as objects.
8.       Code reusability is easy in compare to POP.

Application Fields of OOP:

1.       Real time systems.
2.       Simulation and modeling.
3.       Object oriented databases.
4.        Neural network and parallel programming.
5.       Decision support and office automation systems.

Advantages of OOP:

1.       Through data hiding, security of information increases.
2.       Through abstraction, simplicity of system increases.
3.       Through encapsulation, customizing is easy.
4.       Through inheritance using code reuse, time complexity decreases.
5.       Through polymorphism, flexibility of program increases.
6.       Global data problem is reduced using class and object concept.

Disadvantages of OOP:

1.       Larger programming size.
2.       Slower programs.
3.       Steep learning curve.





Friday, December 23, 2016

Basic features of object oriented programming

 1. Class:
Class is an interface to create an object. Class has functions bind together. Function defines the behavior of an objects and attribute defines the property of an objects which it holds from single class any number of an object can be created.
Example:


class car{

  int height;

   int weight;

   string color;

   void start()

    {

cout<<"start"<<endl;   

    }

 void run()
   {
 cout<<"Run"<<endl;
   }
}


Here, class car has attributes as weight, height, color and function as start () and run().

2. Object:

Object is a run time entity. Function and attributes comes play only after creating an object. This refers that features are defined on class where access of these features asible only creating an object.
Example:
Car Lamborghini, ferai;
Here Lamborghini , ferai are only after real manufacturing of Lamborghini, ferari.
Note: for easy visualization, compare class with drawing of a car. By using single drawing many car can be manufactured which represents an object in c++.

3. Data hiding:

Data Hiding is the process of hiding information (data) from an unauthentic users information is provided only after the proper validation. If validation fails then information is not shown.
Example:

   a )  in ATM machine, people are able to access account information only after proper validation of pin number goes wrong at the time of validation then information is secure.
b) in facebook  ,gmail and others social sites, password and id entered must have to match with the previously stored password and id ,resides in database to view information.
Advantages:   it provides security.

4. Abstraction:

Abstraction says the detail mechanism is not necessary , just basic knowledge of using system's features is sufficient for proper utilization of system.
Example:

to use ATM machine people does  not  have to learn how ATM card is validated after entering into machine, which language is used to validate data, which databases either SQL or Oracle is implemented in bank to store data. Just basic knowledge of how to use ATM machine is sufficient to access account information. here   detail mechanism is hidden and only basic features is provided and it's called an abstraction.

Advantages:
it provides simplicity.

5. Encapsulation:

Encapsulation is just like capsule. It combines the features of both data hiding and abstraction in single unit.
Example:

In ATM system, GUI is integrated with the database through certain programming language. If GUI is needed to be update then without customizing  all the features of database and language ,it  can be updated.

Advantages:
It makes customization easy.

6. Inheritance:
class P{                                  class Q{                                  class R{
250 function ()                    250 function ()                        250 function ()
}                                                    }                                                   }
Suppose,3 class are there each having 250 number of functions. Let 200 numbers of functions are common among them. we concept yet do not know about the inheritance concept yet then the total number of functions to be written =750. Say, 750 functions take 90 hour of time code.

Inheritance concept say, if common functions are there among classes then place them in one class. After that use such policy, so other classes can easily access those common functions.


class common{

        200 functions()

};
class P: common{
        50 functions()
};
class Q: common{
        50 functions()
};
class R: common{
50 functions()
};

The total number of functions to be written = 350. Total time to write 350 function takes 42 hour of time.

Advantages:
It helps to refuse code and thus reduce time to code.

7. Polymorphism:

Polymorphism refers to many forms. This means under different situation same thing can behave differently. We human being is best example of polymorphism.
In University a person is a student, in home same person can be son/daughter of parent or husband/wife or father/mother of their child. According to location, relation changes for same person.
In OOP, same concept applies in polymorphism. Function overloading and Dynamic Binding is an example of polymorphism.
Example:

#include<iostream>

using namespace std;

void m1(int i)

{
 cout<<"int-args:"<<endl;
 }
void m1(float f)
{
    cout<<"float-args:"<<endl;
}
int main()
{
  m1(2);
  m1(2div>
  return 0;
}


Output:
    int-args:
 Float-args:
   Here, both functions have same name but depending upon type of argument it gives different output. If int argument is passes then it shows "int-args" as output. If float argument is passes then it shows "float-args" as output.

Advantages:
 It provides flexibility.