Unit-1 C++
Unit-1 C++
Predefined Functions: The system libraries already define these functions. To build
error-free code, a programmer will reuse the existing code in the system
libraries. charAt() is an example of a pre-defined function that searches for a character
position in a string.
Local Variable: In programming, a variable is used only within the routine or
function it is defined in. When the function is finished and control is returned to the part of
the program that called it, the local variables no longer exist.
Global Variable: A global variable is a variable that is declared in the global scope.
In other words, a variable is declared outside every other function defined in the code.
Modularity: When two different systems have two distinct jobs at hand but are
grouped to perform a bigger job first, this is referred to as modularity. Modularity is a
powerful tool for reducing the complexity of systems.
Parameter Passing: It‘s a mechanism to pass parameters to procedures, functions, or
routines. Parameter passing can be done through pass-by-value and pass-by-reference.
Inheritance:
Inheritance is the process by which objects of one class acquire the properties of
another class.
It supports the concept of hierarchical classification.
It helps to reduce the code size.
Inheritance is the process in which two classes have is-a relationship among each
other and objects of one class acquire properties and features of the other class.
The class which inherits the features is known as the child class, and the class whose
features it inherited is called the parent class.
For example, Class Vehicle is the parent class, and Class Bus, Car, and Bike are child
classes.
Dynamic Binding:
Binding refers to the linking of a procedure call to the code to be executed in
response to the call.
Dynamic binding also known as late binding means that the code associated with
a give procedure call is not known until the time of the function call at run time.
It is associated with polymorphism and inheritance.
Message Passing:
an object-oriented program consists of a set of objects that communicate
with each other.
The process of programming in object-oriented language involves the
following basic steps :
1. Creating classes that define objects and their behaviour.
2. Creating objects from class definitions and
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving
information much the same way as people pass messages to one
another. The concept of message passing makes it easier to talk about
building systems .
A message for an object is a request for execution of a procedure and
therefore will invoke a function in the receiving object that generates the
desired result. Message passing involves specifying the name of the
object, the name of the function – message and the information to be
sent. For example
Benefits of OOPs:
OOP offers several benefits to both the program designer and user.
Through inheritance, we can eliminate redundant code and extend the use of existing
classes.
The principle of data hiding helps the programmer to build secure programs that cannot
be invaded by code on other parts of the program.
It is possible to have multiple instances of on object to co-exist without any interference.
It is possible to map objects in the problem domain to those objects in the program.
It is easy to partition the work in a project based on objects.
Object-oriented systems can be easily upgraded from small to large systems.
Message passing techniques for communication between objects makes the interface
descriptions with external systems much simpler.
Software complexity can be easily managed.
Applications of OOP:
Applications of OOP are beginning to gain importance in many areas.
The most popular application of object-oriented programming, up to now, has been in the
area
of user interface design such as windows.
The other areas for application of OOP includes:
Real-time systems
Simulation and modelling
Object-oriented databases
Hypertext, hypermedia and expertext
AI and expert systems
Neural networks and parallel programming
Decision support and office automation systems
CIM/CAM/CAD systems.
What is C++?
C++ is an object-oriented programming language developed by Bjarne Stroustrup at
AT & T Bell Laboratories in New Jersey, USA, in 1980.
It is developed from Simula67 and C programming language.
The new fundamental is class in C++ programming language other than C so it was
given name ‗C with Classes‘ for C++.
But in 1983 from the increment operator (++) of C language the new name was given
C++.
In 1997 ANSI (American National Standard Institute) standardized C++.
C++ is super-set of C and it is similar to C language.
Most important facilities provided by C++ over C are: Class, Inheritance, function
overloading and Operator overloading.
C language uses top-down structure of programming while C++ uses bottom-up
structure.
Applications of C++
C++ is a versatile language for handling very large programs.
It is suitable for virtually any programming task including development
of editors, compilers, databases, communication systems and any complex
real-life application systems.
Those lists of applications are the following:
Google: We can say most of the components of Google are running with the
help of the C++ programming language. From the Chrome Browser to the
Google File system everywhere there is a use of C++ programming language.
Mozilla: Mozilla is another important organization that is using the C++
programming language as the driving force. The Firefox browser is running
with the help of the C++ programming language. Even the email & client
connection has been done with the C++ programming language.
Microsoft: We have already discussed the presence of C++ programming
language in the products of Microsoft. Even the Windows operating system has
some components which are running with the help of the C++ programming
language.
MongoDB: MongoDB is an open-source application that has a major
contribution to the database management system. The back end of the
MongoDB application uses the C++ programming language as the key element.
Scanner: All the scanner application is executed with the help of the C++
programming language. It might be scanning with the help of the mobile
camera also. But the presence of the C++ programming language is inevitable
when we will do some modifications to the scanned document.
Input Output Operators
Input operator:
C++ provides the operator >> to get input. It extracts the value through the keyboard
and assigns it to the variable on its right; hence, it is called as “Stream
extraction” or “get from” operator.
It is a binary operator i.e., it requires two operands. The first operand is the pre-
defined identifier cin (pronounced as C-In) that identifies keyboard as the input
device. The second operand must be a variable.
To receive or extract more than one value at a time, >> operator should be used for each
variable. This is called cascading of operator.
Example:
• cin >> num;
Pre-defined object cin extracts a value typed on keyboard and stores it in variable num.
• cin >>x >> y;
This is used to extract two values. cin reads thefirst value and immediately assigns
that to variable x; next, it reads the second value which is typed after a space and
assigns that to y. Space is used as a separator for each input.
Output Operator:
C++ provides << operator to perform output operation. The operator << is called
the “Stream insertion” or “put to” operator. It is used to send the strings or values
of the variables on its right to the object on its left. << is a binary operator.
The first operand is the pre-defined identifier cout (pronounced as C-Out) that
identifies monitor as the standard output object. The second operand may be a
constant, variable or an expression.
To send more than one value at a time, << operator should be used for each constant/
variable/expression. This is called cascading of operator.
Example:
• cout << ―Welcome‖;
Pre-defined object cout sends the given string ―Welcome‖ to screen.
• cout << ―The sum = ― << sum;
• cout <<―\n The Area: ― <<3.14*r*r;
\n – is a non graphical character constant to feed a new line.
• cout << a + b ;
Cascading of I/O operators
The multiple use of input and output operators such as >> and << in a single statement is
known as cascading of I/O operators.
Cascading cout:
int Num=20;
cout << ―A=‖ << Num;
Cascading cin - Example:
cout >> ―Enter two number: ‖;
cin >> a >> b;
Structure of C++ Program
. The structure of the program written in C++ language is as follows:
Include Files
Class Declaration
#include<iostream>
Namespaces:
A namespace permits grouping of various entities like classes, objects, functions, and
various C++ tokens, etc. under a single name.
Any user can create separate namespaces of its own and can use them in any other
program.
In the below snippets, namespace std contains declarations for cout, cin, endl, etc.
statements.
using namespace std;
Namespaces can be accessed in multiple ways:
o using namespace std;
o using std :: cout;
Class Declaration Section:
After the include section there is class declaration section.
In class declaration we are defining class, its member variable and declaration for the
member function.
This is also optional section.
You can create your C++ program without class but to use object oriented features,
class is necessary.
Namespace
Namespace is one of the new features in this language. It allows the grouping of
different entities such as classes, objects, functions and a variety of C++ tokens, etc.,
under a single name.
What is a Namespace?
Namespaces provide a method to avoid name conflicts in a project.
Namespaces in C++ are used as additional information to differentiate two or more
variables, functions, or classes having the same names.
Creation of Namespaces
Creating a namespace in C++ is similar to creating a class.
We use the keyword namespace followed by the name of the namespace to define a
namespace in C++.
Namespace MyNamespace
{
// Function, class, and variable declarations.
}
The C++ Standards Committee has rearranged the entities of the standard library under a
namespace known as std.
The entities of a namespace can be accessed in several ways which are as follows:
By specifying the using directive
using namespace std;
cout<<“Hello World”;
By specifying the full member name
std: :cout<<“Hello World”;
By specifying the using-declaration
using std:: cout;
cout<<“Hello World”;
As soon as the new-style header includes, its contents include in the std namespace.
Thus, all modern C++ compilers support these statements.
#include<iostream>
using namespace std;
But, some old compilers may not support these statements. In this scenario, these single
statements replace the statements.
#include<iostream.h>
C++ Data Types
All variables use data type during declaration to restrict the type of data to be stored.
Whenever a variable is defined in C++, the compiler allocates some memory for that
variable based on the data type with which it is declared.
Every data type requires a different amount of memory.
Data types specify the size and types of values to be stored.
C++ supports the following data types:
1. Primary or Built-in or Fundamental data type or Basic data type
2. Derived data types
3. User-defined data types
Array:
An array is a collection of items stored at continuous memory locations.
The idea of array is to represent many instances in one variable.
Syntax:
DataType ArrayName[size_of_array];
Pointers:
Pointers are symbolic representation of addresses.
They enable programs to simulate call-by-reference as well as to create and
manipulate dynamic data structures.
Syntax:
datatype *var_name;
Example:
int *ptr;
Reference:
When a variable is declared as reference, it becomes an alternative name for an
existing variable.
A variable can be declared as
reference by putting ‗&‘ in the
declaration.
Example:
Class:
The building block of C++ that leads to Object-Oriented programming is a Class.
It is a user-defined data type, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class.
A class is like a blueprint for an object.
Syntax:
Structure:
A structure is a user defined data type in C/C++.
A structure creates a data type that can be used to group items of possibly different
types into a single type.
Syntax:
struct structurename {
data member…
data memer function..
};
Union:
Like Structures, union is a user defined data type.
In union, all members share the same memory location.
For example in the following C program, both x and y share the same location. If we
change x, we can see the changes being reflected in y.
Enumeration:
Enumeration (or enum) is a user defined data type in C.
It is mainly used to assign names to integral constants, the names make a program
easy to read and maintain.
Syntax:
enum State {Working = 1, Failed = 0};
Typedef :
C++ allows you to define explicitly new data type names by using the keyword
typedef. Using typedef does not actually create a new data class, rather it defines a
name for an existing type.
This can increase the portability(the ability of a program to be used across different
types of machines; i.e., mini, mainframe, micro, etc; without much changes into the
code)of a program as only the typedef statements would have to be changed.
Using typedef one can also aid in self-documenting code by allowing descriptive
names for the standard data types.
Syntax:
typedef type name;
where type is any C++ data type and name is the new name for this data type.
Symbolic Constants
There are two ways of creating symbolic constants in C++.
Using the qualifier const and
Using a set of integer constants using enum keyword.
In both C and C++ any value declared as const can not be modified by the
program in any way.
However, there are some differences in implementation.
In C++, we can use const in a constant expression, such as
const int size = 10;
char name [size];
This would be illegal in C. const allows us to create typed constant instead
of having to use #define to create constants that have no type information.
if we use the const modifier alone it defaults to int. For example
const size = 10;
Means const int size = 10;
The named constants are just like variables except that their values cannot
be changed
C++ requires a const to be initialized.
ANSI C does not require an initialize.
Another method of naming integer constants is by enumeration as under;
enum { X. Y. Z};
This defines X, Y and Z as integer constants with values 0, 1, and 2 respectively.
This is equivalent to:
const x = 0; const y = 1; const z = 2;
We can also assign values to x, y, and z explicitly. Example: enum(x = 100, y = 50,
z= 200);
Such values can be any integer values.
Type Compatibility
C++ is very strict with regard to type compatibility as compared to
C.
For instance, C++ defines int, short int. and long int as three
different types.
They must be cast when their values are assigned to one another.
Similarly, unsigned char, char, and signed char are considered as
different types, although each of these has a size of one byte.
In C++, the types of values must be the same for complete
compatibility, or else, a cast must be applied.
These restrictions in C++ are necessary in order to support function
overloading where two functions with the same name are
distinguished using the type of function arguments.
Another notable difference is the way char constants are stored. In C,
they are stored as ints, and therefore,
sizeof (' x' )
is equivalent to
sizeof (int) in C.
In C++, however, char is not promoted to the size of int and therefore
sizeof( ' x ' )
equals
sizeof(char)
Type Casting
Type casting refers to the conversion of one data type to another in a program.
Typecasting can be done in two ways:
1. Implicit conversion or Implicit Type Casting
2. Explicit Type Conversion or Explicit Type Casting.
Implicit Type Casting or Implicit Type Conversion
o It is known as the automatic type casting.
o It automatically converted from one data type to another without any external
intervention such as programmer or user. It means the compiler automatically converts
one data type to another.
o All data type is automatically upgraded to the largest type without losing any
information.
o It can only apply in a program if both variables are compatible with each other.
char - short int -> int -> unsigned int -> long int -> float -> double -> long double, etc.
int num = 5;
float x;
x = num;
output : x = 5.0
Explicit Type Casting or Explicit Type Conversion
o It is also known as the manual type casting in a program.
o It is manually cast by the programmer or user to change from one data type to another
type in a program. It means a user can easily cast one data to another according to the
requirement in a program.
o It does not require checking the compatibility of the variables.
o In this casting, we can upgrade or downgrade the data type of one variable to another
in a program.
o It uses the cast () operator to change the type of a variable.
Syntax of the explicit type casting
1. (type) expression;
type: It represents the user-defined data that converts the given expression.
expression: It represents the constant value, variable, or an expression whose data type is
converted.
For example, we have a floating pointing number is 4.534, and to convert an integer value,
the statement as:
int num;
num = (int) 4.534; // cast into int data type
cout << num;
Declaration of Variables
We know that, in C, all variables must be declared before they are
used in executable statements.
C++ allows the declaration of a variable anywhere in the scope.
This means that a variable can be declared right at the place of its
first use.
This makes the program much easier to write and reduces the
errors that may be caused by having to scan back and forth.
It also makes the program easier to understand because the variables
are declared in the context of their use.
The example below illustrates this point.
int main()
{
float x;
float sum = 0;
for (i = 0; i <; i++)
{
cin >> x;
sum = sum + x;
}
float average;
average = sum/ ( i-1);
cout << average;
return 0;
}
The only disadvantage of this style of declaration is that we cannot see all the variables
used in scope.
Reference Variables
C++ introduces a new kind of variable known as the reference variable.
A reference variable provides an alias (alternative name) for a previously
defined variable.
For example, if we make the variable sum a reference to the variable
total, then sum and total can be used interchangeably to represent that
variable.
A reference variable is created as follows:
print the value 100. The statement total = total + 10; will
change the value of both total and sum to 110.
Operators in C + +
C++ has a rich set of
operators.
All C operators are valid in C++ also. In addition, C++ introduces some new
operators.
We have already seen two such operators, namely, the insertion operator << and
the extraction operator >>.
Other new operators are:
It automatically computes the size of the data object. We need not use the
operatorsizeof.
It automatically returns the correct pointer type, so that there is no need to
use a type cast
It is possible to initialize the object while creating the memory
space.
Like any other operator, new and delete can be overloaded.
Manipulators
Manipulators are operators that are used to format the data display.
The most commonly used manipulators are endl a nd setw.
The endl manipulators when used in an output statement, causes a linefeed
to be inserted.
It has the same effect as using the new line character "\n". For example,
the statement
cout << “m = “ << m << endl<< “n = “ << n << endl
<< “p = “ << p << endl;
would cause three line of output for each variable.
If we assume the values of the variables as 2597, 14 and 175 respectively,
the output will appear as follows.
m = 2597
n = 14
p = 175
Here, the numbers are right-justified.
This form of output is possible only if we can specify a common field
width for all the numbers and force them to be printed right-justified.
The setw manipulator does this job. It is used as follows:
cout « “sum = “;
cout « setw(5) « sum « endl ;
The manipulator setw(5) specifies a field width 5 for printing the value
of the variable sum.
This value is right -justified within the field as shown below:
sum = 345
Program illustrates the use of endl and setw.
Control Structure
Introduction:
C++ is a programming language from a high level that is widely used for creating
applications and software.
One of the most important concepts in C++ programming is Flow Control, which
refers to the ability to direct the flow of a program based on specific conditions.
This allows developers to control how their programs execute and can help to make
them more efficient and effective.
the following threecontrol structures:
Conditional Statements:
Conditional Statements are used in C++ to run a certain piece of program only if a
specific condition is met.
There are generally three types of conditional statements in C++: if, if-else,
and switch.
if Statement:
The if statement is the simplest of the three and is used to run a certain piece of code
only if a certain condition is true.
Syntax:
if (expression is true)
{
action1;
}
action2;
action3;
For example:
int x = 5;
if (x == 5) {
std::cout << "x is 5" << std::endl;
}
In this example, the block of code inside the curly braces will only be executed if the
condition inside the parentheses is true.
if-else Statement:
The if-else statement is used when we want to execute some code only if some
condition exists.
If the given condition is true then code will be executed otherwise else statement will
be used to run other part of the code.
Syntax:
if (expression is true)
{
action1;
}
else
{
action2;
}
action3;
For example:
int x = 5;
if (x == 5) {
std::cout << "x is 5" << std::endl;
} else {
std::cout << "x is not 5" << std::endl;
}
In this example, if the condition inside the parentheses is true, the first block of code
will be executed.
Otherwise, the second block of code will be executed.
switch Statement:
The switch statement is used to execute different blocks of code based on the value of a
variable.
Syntax:
switch (variable) {
case value1:
// code to execute if the variable is equal to value1
break;
case value2:
// code to execute if the variable is equal to value2
break;
// add more cases as needed
default:
// code to execute if the variable does not match any case
}
Example:
int x = 2;
switch (x) {
case 1:
std::cout << "x is 1" << std::endl;
break;
case 2:
std::cout << "x is 2" << std::endl;
break;
default:
std::cout << "x is not 1 or 2" << std::endl;
break;
}
In this example, the switch statement will execute the block of code associated with
the value of x.
If x is 1, the first block of code will be executed.
If x is 2, the second block of code will be executed.
If x is any other value, the default block of code will be executed.
Loops:
Loops are used in C++ to execute a block of code multiple times, either until a certain
condition is met or for a specific number of times.
There are generally three types of loops in C++: while, do-while, and for.
While Loop:
The while loop is used to execute when we want to run some code for until some
specific condition matches.
This is also a loop structure, but is an entry-controlled one.
Syntax:
while(condition is true)
{
actionl;
}
action2;
Example:
int x = 0;
while (x < 5) {
std::cout << x << std::endl;
x++; }
In this example, the while loop will continue to execute the block of code inside the
curly braces as long as x is less than 5.
Each time the loop executes, the value of x will be incremented by 1.
do-while Loop:
The do-while loop is the same as the while loop, but the condition is checked after
the first iteration of the loop.
The do-while is an exit-controlled loop.
Syntax:
do
{
actionl ;
}
while(condition is true);
action2;
Example:
AD
int x = 0;
do {
std::cout << x << std::endl;
x++;
} while (x < 5);
In this example, the do-while loop will execute the block of code inside the curly
brackets, and then it will check the condition.
So it will be executed a minimum of one time.
for Loop:
The for loop allows a program to execute a piece of program a fixed number of
times.
Syntax:
for (initialization; condition; increment/decrement)
{
// code to execute repeatedly
}
Here is an example that uses the for loop to print the numbers from 1 to 10:
for (int i = 1; i <= 10; i++)
{
cout << i << " ";
}