DSC++ Unit - I
DSC++ Unit - I
Cout
This method is used to print variable / string / character. Syntax:
cout<< variable / charcter / string;
Functions in C++
A function is a block of code that performs a specific task. It has a name and
it is reusable i.e. it can be executed from as many different parts as required.
It also optionally returns a value to the calling function.
A complex problem may be decomposed into a small or easily manageable
parts or modules called functions. Functions are very useful to read, write,
debug and modify complex programs They can also be incorporated in the
main program. The main() itself is a function is invoking the other functions to
perfom various tasks.
return_type function_name(argument_list)
{ statement 1;
.
.
statements n; [return value];
}
In call by value, value being passed to the function is locally stored by the
function parameter in stack memory location. If you change the value of
function parameter, it is changed for the current function only. It will not
change the value of variable inside the caller method such as main(
#include <iostream> using namespace std; void change(int data); int main()
{
int data = 3; change(data);
cout << "Value of the data is: " << data<< endl; return 0;
}
void change(int data)
{
data = 5;
}
Call BY REFERENCE
In call by reference, original value is modified because we pass reference
(address).
Here, address of the value is passed in the function, so actual and formal
arguments share the same address space. Hence, value changed inside the
function, is reflected inside as well as outside the function.
Function Overloading
In C++, it is possible to make more than one function with same name, this
concept is known as function overloading. We can use same function name
for different purpose with different number and types of arguments.
In function overloading function names will be same but Types of arguments,
Order of arguments, Number of arguments must be different.
The C++ compiler selects the proper function by examining the number,
types and order of the arguments in the call. Function overloading is
commonly used to create several functions of the same name that perform
similar tasks but on different data types.
Eliminating the use of different function names for the same operations.
Helps to understand, debug and group easily.
Easy maintainability of the code.
Better understandability of the relationship b/w the program and the outside
world.
Function Templates
In C++, function templates are functions that serve as a pattern for
creating other similar functions. The basic idea behind function templates is
to create a function without having to specify the exact type(s) of some or all
of the variables. Instead, we define the function using placeholder types,
called template type parameters. Once we have created a function using
these placeholder types, we have effectively created a “function stencil”.
int main()
{
int i = max(3, 7); // returns 7 std::cout << i << '\n';
return 0;
}
C++ Arrays
Like other programming languages, array in C++ is a group of similar types
of elements that have contiguous memory location.
C++ Array Types
There are 2 types of arrays in C++ programming:
Single Dimensional Array
Multidimensional Array
C++ Pointers
The pointer in C++ language is a variable, it is also known as locator or
Advantage of pointer
Pointer reduces the code and improves the performance, it is used to retrieving
strings, trees etc. and used with arrays, structures and functions.
We can return multiple values from function using pointer.
It makes you able to access any memory location in the computer's memory.
Usage of pointer
There are many usage of pointers in C++ language.
Dynamic memory allocation
In c language, we can dynamically allocate memory using malloc() and
calloc() functions where pointer is used.
Arrays, Functions and Structures
delete Operator :
delete operator is used to Deallocates the dynamically allocated memory.
void main()
{
delete[] ptr;
//deallocating all the memory created by new operator
Object is an instance of a class. All the members of the class can be accessed
through object. Student s1; //creating an object of Student
C++ Class
In C++, object is a group of similar objects. It is a template from which
objects are created. It can have fields, methods, constructors etc.
class class_name
{
friend data_type function_name(argument/s); // syntax of friend function.
};
C++ Constructor
Default constructor
Parameterized constructor
Copy Constructor
C++ Default Constructor
A constructor which has no argument is known as default constructor. It is
invoked at the time of creating object.
C++ Destructor
A destructor works opposite to constructor; it destructs the objects of classes.
It can be defined only once in a class. Like constructors, it is invoked
automatically.
A destructor is defined like constructor. It must have same name as class. But
it is prefixed with a tilde sign (~).
int main () {
mypair <int> myobject (100, 75); cout << myobject.getmax(); return 0;
}
C++ Inheritance
In C++, inheritance is a process in which one object acquires all the
properties and behaviors of its parent object automatically. In such way, you
can reuse, extend or modify the attributes and behaviors which are defined in
other class.
Types Of Inheritance
C++ supports five types of inheritance:
Single inheritance
Multiple inheritance
Hierarchical inheritance
Multilevel inheritance
Hybrid inheritance
Derived Classes
A Derived class is defined as the class derived from the base clas
Single Inheritance
Single inheritance is defined as the inheritance in which a derived class is
inherited from the only one base class
Multilevel Inheritance
Multilevel inheritance is a process of deriving a class from another derived
class.
#include <iostream> using namespace std; class Animal {
public:
void eat() { cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){ cout<<"Barking..."<<endl;
}
};
class BabyDog: public Dog
{
public:
void weep() { cout<<"Weeping...";
}
};
int main(void) { BabyDog d1; d1.eat();
d1.bark();
d1.weep(); return 0;
}
Multiple Inheritance
Multiple inheritance is the process of deriving a new class that inherits the
attributes from two or more classes.
class B
{
protected:
int b; public:
void get_b(int n)
{
b = n;
}
};
class C : public A,public B
{
public:
void display()
{
std::cout << "The value of a is : " <<a<< std::endl; std::cout << "The value
of b is : " <<b<< std::endl; cout<<"Addition of a and b is : "<<a+b;
}
};
int main()
{
C c; c.get_a(10);
c.get_b(20);
c.display();
return 0;
}
Polymorphism
Polymorphism is an important and basic concept of OOPS. Polymorphism
specifies the ability to assume several forms. It allows routines to use
variables of different types at different times.
In C++, An operator or function can be given different meanings or
functions. Polymorphism refers to a single function or multi-functioning
operator performing in different ways.
Types of polymorphism
There are two types of polymorphism in C++
Static or Compile time polymorphism
Dynamic or Run time polymorphism
#include <iostream>
{
public:
virtual void display()
{
cout << "Base class is invoked"<<endl;
}
};
class B:public A
{
public:
void display()
{
cout << "Derived Class is invoked"<<endl;
}
};
int main()
{
A* a; //pointer of base class B b; //object of derived class a = &b;
a->display(); //Late Binding occurs
}
Algorithm:
An algorithm is a finite set of step by step instructions to solve a
problem. In normal language, algorithm is defined as a sequence of
statements which are used toperform a task.
In computer science, an algorithm can be defined as follows:
An algorithm is a sequence of unambiguous instructions used for solving
aproblem, which can be implemented (as a program) on a computer.
Properties
Every algorithm must satisfy the following properties:
Definiteness - Every step in an algorithm must be clear and unambiguous
Finiteness – Every algorithm must produce result within a finite number of steps.
Effectiveness - Every instruction must be executed in a finite amount of time.
Input & Output - Every algorithm must take zero or more number of inputs and
must produce at least one output as result.
Performance Analysis
In computer science there are multiple algorithms to solve a problem. When
we have more than one algorithm to solve a problem, we need to select the
best one.
Performance analysis helps us to select the best algorithm from multiple
algorithms to solve a problem.When there are multiple alternative algorithms
to solve a problem, we analyses them and pick the one which is best
suitable for our requirements. Generally, the performance of an algorithm
depends on the following elements...
Whether that algorithm is providing the exact solution for the problem?
Whether it is easy to understand?
Whether it is easy to implement?
How much space (memory) it requires to solve the problem?
How much time it takes to solve the problem? Etc.,
When we want to analyze an algorithm, we consider only the space and time
required by that particular algorithm and we ignore all remaining
elements.Performance analysis of an algorithm is performed by using the
following measures:
Space Complexity
Time Complexity
Space complexity
Total amount of computer memory required by an algorithm to complete
its execution is called as space complexity of that algorithm.Generally, when
a program is under execution it uses the computer memory for THREE
reasons. They are as follows...
Instruction Space: It is the amount of memory used to store compiled version of
instructions.
Environmental Stack: It is the amount of memory used to store information of
partially executed functions at the time of function call.
Data Space: It is the amount of memory used to store all the variables and
constants.
NOTE: When we want to perform analysis of an algorithm based on its Space
complexity, we consider only Data Space and ignore Instruction Space as well
as Environmental Stack. That means we calculate only the memory required
to store Variables, Constants, Structures, etc
Consider the following piece of code... int square(int a)
{
return a*a;
}
In above piece of code, it requires 2 bytes of memory to store variable 'a' and
another 2 bytes of memory is used for return value. That means, totally it
requires 4 bytes of memory to complete its execution.
Time complexity
The time complexity of an algorithm is the total amount of time
required by an algorithm to complete its execution. Generally, running time
of an algorithm depends upon the
following:
Whether it is running on Single processor machine or Multi processor machine.
Whether it is a 32 bit machine or 64 bit machine
Read and Write speed of the machine.
The time it takes to perform Arithmetic operations, logical operations, return
value and assignment operations etc.,
NOTE: When we calculate time complexity of an algorithm, we consider only
input data and ignore the remaining things, as they are machine dependent.
Asymptotic Notation
Asymptotic notation of an algorithm is a mathematical representation
of its complexity.
Majorly, we use THREE types of Asymptotic Notations and those are:
Big - Oh (O)
Omega (Ω)
Theta (Θ)
Big - Oh Notation (O)
Big - Oh notation is used to define the upper bound of an algorithm in terms of
Time Complexity.
Big - Oh notation always indicates the maximum time required by an algorithm
for all input values.
Big - Oh notation describes the worst case of an algorithm time complexity.
It is represented as O(T)
Example
Consider the following piece of code Algorithm Search (A, n,x)
{ // where A is an array, n is the size of an array and x is the item to be
searched. for i := 1 to n do
{
if(x=A[i]) then
{
write (item found at location i) return;
}
}
write (item not found)
}