Notes-All
Notes-All
What is C?
C is the basic programming language that can be used to develop from the operating
systems (like Windows) to complex programs like Oracle database, Git, Python
interpreter, and many more. C programming language can be called a god's
programming language as it forms the base for other programming languages. If we
know the C language, then we can easily learn other programming languages. C
language was developed by the great computer scientist Dennis Ritchie at the Bell
Laboratories. It contains some additional features that make it unique from other
programming languages.
What is C++?
C++ history
History of C++ language is interesting to know. Here we are going to discuss brief
history of C++ language.
C++ Features
1. Simple
2. Abstract Data types
3. Machine Independent or Portable
4. Mid-level programming language
5. Structured programming language
6. Rich Library
7. Memory Management
8. Quicker Compilation
9. Pointers
10. Recursion
11. Extensible
12. Object-Oriented
13. Compiler based
14. Reusability
15. National Standards
16. Errors are easily detected
17. Power and Flexibility
18. Strongly typed language
19. Redefine Existing Operators
20. Modeling Real-World Problems
21. Clarity
1) Simple
C++ is a simple language because it provides a structured approach (to break the
problem into parts), a rich set of library functions, data types, etc.
In C++, complex data types called Abstract Data Types (ADT) can be created using
classes.
C++ is a structured programming language. In this we can divide the program into
several parts using functions.
6) Rich Library
C++ provides a lot of inbuilt functions that make the development fast. Following are
the libraries used in C++ programming are:
o <iostream>
o <cmath>
o <cstdlib>
o <fstream>
7) Memory Management
8) Quicker Compilation
C++ programs tend to be compact and run quickly. Hence the compilation and
execution time of the C++ language is fast.
9) Pointer
C++ provides the feature of pointers. We can use pointers for memory, structures,
functions, array, etc. We can directly interact with the memory by using the pointers.
10) Recursion
In C++, we can call the function within the function. It provides code reusability for
every function.
11) Extensible
C++ programs can easily be extended as it is very easy to add new features into the
existing program.
12) Object-Oriented
In C++, object-oriented concepts like data hiding, encapsulation, and data abstraction
can easily be implemented using keyword class, private, public, and protected access
specifiers. Object-oriented makes development and maintenance easier.
14) Reusability
With the use of inheritance of functions programs written in C++ can be reused in any
other program of C++. You can save program parts into library files and invoke them
in your next programming projects simply by including the library files. New
programs can be developed in lesser time as the existing code can be reused. It is also
possible to define several functions with same name that perform different task. For
Example: abs () is used to calculate the absolute value of integer, float and long
integer.
It is easier to maintain a C++ programs as errors can be easily located and rectified. It
also provides a feature called exception handling to support error handling in your
program.
C++ is a powerful and flexible language because of most of the powerful flexible and
modern UNIX operating system is written in C++. Many compilers and interpreters
for other languages such as FORTRAN, PERL, Python, PASCAL, BASIC, LISP, etc.,
have been written in C++. C++ programs have been used for solving physics and
engineering problems and even for animated special effects for movies.
C++ allows the programmer to redefine the meaning of existing operators such as +, -
. For Example, The "+" operator can be used for adding two numbers and
concatenating two strings.
21) Clarity
The keywords and library functions used in C++ resemble common English words.
To write the first C++ program, open the C++ console and write the following code:
#include <iostream>
int main() {
std::cout << "hi";
return 0;
}
#include<iostream>
using namespace std;
int main()
{
Cout<<”hello”;
return 0;
};
main() The main() function is the entry point of every program in C++ language.
cout << "Welcome " is used to print the data "Welcome " on the console.
C++ I/O operation is using the stream concept. Stream is the sequence of bytes or
flow of data. It makes the performance fast.
If bytes flow from main memory to device like printer, display screen, or a network
connection, etc, this is called as output operation.
If bytes flow from device like printer, display screen, or a network connection, etc to
main memory, this is called as input operation.
The cout is a predefined object of ostream class. It is connected with the standard
output device, which is usually a display screen. The cout is used in conjunction with
stream insertion operator (<<) to display the output on a console
#include <iostream>
using namespace std;
int main( ) {
char ary[] = "cse";
cout << "Value of ary is: " << ary << endl;
}
The cin is a predefined object of istream class. It is connected with the standard input
device, which is usually a keyboard. The cin is used in conjunction with stream
extraction operator (>>) to read the input from a console.
#include <iostream>
using namespace std;
int main( )
{
int grade ;
cout << "Enter your grade";
cin >>grade ;
cout << "hgjfguvfmh bhj Your grade: " << grade << endl;
}
The endl is a predefined object of ostream class. It is used to insert a new line
characters and flushes the stream.
#include <iostream>
using namespace std;
int main( ) {
cout << ”hi"<<endl;
cout << " hello"<<endl;
cout << "welcome"<<endl;
}
C++ Variable
A variable is a name of memory location. It is used to store data. Its value can be
changed and it can be reused many times.
type variable_list;
int x;
float y;
char z;
A variable name can start with alphabet and underscore only. It can't start with digit.
1. int a;
2. int _ab;
3. int a30;
C++ Data Types
A data type specifies the type of data that a variable can store such as integer, floating,
character etc.
The basic data types are integer-based and floating-point based. C++ language
supports both signed and unsigned literals.
The memory size of basic data types may change according to 32 or 64 bit operating
system.
C++ Keywords
C++ Operators
An operator is simply a symbol that is used to perform operations. There can be many
types of operations like arithmetic, logical, bitwise etc.
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operator
o Unary operator
o Ternary or Conditional Operator
o Misc Operator
The precedence of operator species that which operator will be evaluated first and
next. The associativity specifies the operators direction to be evaluated, it may be left
to right or right to left.
int data=5+10*10;
The "data" variable will contain 105 because * (multiplicative operator) is evaluated
before + (additive operator).
C++ Identifiers
C++ identifiers in a program are used to refer to the name of the variables, functions,
arrays, or other user-defined data types created by the programmer. They are the basic
requirement of any language. Every language has its own rules for naming the
identifiers.
In short, we can say that the C++ identifiers represent the essential elements in a
program which are given below:
o Constants
o Variables
o Functions
o Labels
o Defined data types
Some naming rules are common in both C and C++. They are as follows:
For example, suppose we have two identifiers, named as 'FirstName', and 'Firstname'.
Both the identifiers will be different as the letter 'N' in the first case in uppercase
while lowercase in second. Therefore, it proves that identifiers are case-sensitive.
Valid Identifiers
Result
Test2
_sum
power
Invalid Identifiers
The following are the examples of invalid identifiers:
Examples:
Keywords are the reserved words that have a special meaning to the compiler. They
are reserved for a special purpose, which cannot be used as the identifiers. For
example, 'for', 'break', 'while', 'if', 'else', etc. are the predefined words where
predefined words are those words whose meaning is already known by the compiler.
Whereas, the identifiers are the names which are defined by the programmer to the
program elements such as variables, functions, arrays, objects, classes.
Identifiers are the names defined by the programmer to the Keywords are the reserved words whose meaning
basic elements of a program. is known by the compiler.
It is used to identify the name of the variable. It is used to specify the type of entity.
It can use both lowercase and uppercase letters. It uses only lowercase letters.
No special character can be used except the underscore. It cannot contain any special character.
The starting letter of identifiers can be lowercase, It can be started only with the lowercase letter.
uppercase or underscore.
Examples are test, result, sum, power, etc. Examples are 'for', 'if', 'else', 'break', etc.
C++ Comments
The C++ comments are statements that are not executed by the compiler. The
comments in C++ programming can be used to provide explanation of the code,
variable, method or class. By the help of comments, you can hide the program code
also.
The single line comment starts with // (double slash). Let's see an example of single
line comment in C++.
#include <iostream>
using namespace std;
int main()
{
int x = 11; // x is a variable
cout<<x;
Return 0;
}
The C++ multi line comment is used to comment multiple lines of code. It is
surrounded by slash and asterisk (/∗ ..... ∗/). Let's see an example of multi line
comment in C++.
#include <iostream>
using namespace std;
int main()
{
/* declare and
print variable in C++. */
int x = 35;
cout<<x;
return 0;
}
C++ Expression
C++ expression consists of operators, constants, and variables which are arranged
according to the rules of the language. It can also contain function calls which return
values. An expression can consist of one or more operands, zero or more operators to
compute a value. Every expression produces some value which is assigned to the
variable with the help of an assignment operator.
#include <iostream>
using namespace std;
int main()
{
int x; // variable declaration.
x=(3/2) + 2; // constant expression
cout<<"Value of x is : "<<x; // displaying the value of x.
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int x; // variable declaration.
int y; // variable declaration
int z; // variable declaration
cout<<"Enter the values of x and y";
cin>>x>>y;
z=x+y;
cout<<"Value of z is :"<<z;
Return 0;
}
Relational Expressions
A relational expression is an expression that produces a value of type bool, which can
be either true or false. It is also known as a boolean expression.
#include <iostream>
using namespace std;
int main()
{
int a=45; // variable declaration
int b=78; // variable declaration
bool y= a>b; // relational expression
cout<<"Value of y is :"<<y; // displaying the value of y.
return 0;
}
Value of y is :0
Logical Expressions
#include <iostream>
using namespace std;
int main()
{
int a=2;
int b=7;
int c=4;
cout<<!((a>b)&&(a<c));
return 0;
}
0
Bitwise Expressions
For example:
x=3
x>>3 // This statement means that we are shifting the three-bit position to the right.
In the above example, the value of 'x' is 3 and its binary value is 0011. We are shifting
the value of 'x' by three-bit position to the right. Let's understand through the
diagrammatic representation.
#include <iostream>
using namespace std;
int main()
{
int x=5; // variable declaration
cout << (x>>1) ;
return 0;
}
In the above code, we have declared a variable 'x'. After declaration, we applied the
bitwise operator, i.e., right shift operator to shift one-bit position to right.
2
}
#include <iostream>
using namespace std;
int main()
{
int x=1; // variable declaration
std::cout << (x<<1) << std::endl;
return 0;
}
Assignment operator
In the above code, we have declared a variable 'x'. After declaration, we applied the
left shift operator to variable 'x' to shift the three-bit position to the left.56
#include <iostream>
using namespace std;
int main()
{
int a; // variable declaration
int b; // variable declaration
a=b=c=80; // chained assignment
cout <<"Values of 'a' and 'b' are : " <<a<<","<<b<< ;
return 0;
}
In the above code, we have declared two variables, i.e., 'a' and 'b'. Then, we have
assigned the same value to both the variables using chained assignment expression.
#include <iostream>
using namespace std;
int main()
{
int a; // variable declaration
int b; // variable declaration
a=10+(b=90); // embedded assignment expression
cout <<"Values of 'a' is " <<a<<;
return 0;
}
o compound Assignment
For example,
1. a+=10;
#include <iostream>
using namespace std;
int main()
{
int a=10; // variable declaration
a-=10; // compound assignment
cout << "Value of a is :" <<a<<; // displaying the value of a.
return 0;
}
UNIT-2
C++ if-else
In C++ programming, if statement is used to test the condition. There are various
types of if statements in C++.
o if statement
o if-else statement
o if-else-if ladder
o switch statement
C++ IF Statement
#include <iostream>
int main () {
int num = 20;
if (num % 5 == 0)
{
cout<<"It is divisible by 5";
}
return 0;
}
The C++ if-else statement also tests the condition. It executes if block if condition is
true otherwise else block is executed.
if(condition){
//code if condition is true
}
Else
{
//code if condition is false
}
#include <iostream>
using namespace std;
int main () {
int num = 11;
if (num % 2 == 0)
{
cout<<"It is even number";
}
else
{
cout<<"It is odd number";
}
return 0;
}
#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a Number: ";
cin>>num;
if (num % 2 == 0)
{
cout<<"It is even number"<<endl;
}
else
{
cout<<"It is odd number"<<endl;
}
return 0;
}
The C++ if-else-if ladder statement executes one condition from multiple statements.
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
Else
{
//code to be executed if all the conditions are false
}
#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a number to check grade:";
cin>>num;
if (num <0 || num >100)
{
cout<<"wrong number";
}
else if(num >= 0 && num < 50){
cout<<"Fail";
}
else if (num >= 50 && num < 60)
{
cout<<"D Grade";
}
else if (num >= 60 && num < 70)
{
cout<<"C Grade";
}
else if (num >= 70 && num < 80)
{
cout<<"B Grade";
}
else if (num >= 80 && num < 90)
{
cout<<"A Grade";
}
else if (num >= 90 && num <= 100)
{
cout<<"A+ Grade";
}
}
Enter a number to check grade:66
C Grade
C++ switch
The C++ switch statement executes one statement from multiple conditions. It is like
if-else-if ladder statement in C++.
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
//code to be executed if all cases are not matched;
break;
}
#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a number to check grade:";
cin>>num; 3
switch (num)
{
case 1: cout<<"It is 10"; break;
case 2: cout<<"It is 20"; break;
case 3: cout<<"It is 30"; break;
The C++ for loop is used to iterate a part of the program several times. If the number
of iteration is fixed, it is recommended to use for loop than while or do-while loops.
The C++ for loop is same as C/C#. We can initialize variable, check condition and
increment/decrement value.
#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=10;i++)
{
cout<<i <<"\n";
}
}
1
2
1
2
3
4
5
6
7
8
9
10
5
6
#include <iostream>
using namespace std;
int main()
{
int rows;
cout << "Enter number of rows: ";
cin >> rows;
for(int i = 1; i <= rows; i++)
{
for(int j = 1; j <= i; j++)
{
cout << "* ";
}
cout << "\n";
}
return 0;
}
10Output:
**
In C++, while loop is used to iterate a part of the program several times. If the number
of iteration is not fixed, it is recommended to use while loop than for loop.
#include <iostream>
using namespace std;
int main()
{
int i=11;
while(i<=10)
{
cout<<i <<"\n";
i++;
}
return 0;
}
The C++ do-while loop is used to iterate a part of the program several times.
If the number of iteration is not fixed and you must have to execute the loop at least
once, it is recommended to use do-while loop.
The C++ do-while loop is executed at least once because condition is checked after
loop body.
Do
{
//code to be executed
}
while(condition);
#include <iostream>
using namespace std;
int main() {
int i = 1;
do
{
cout<<i<<"\n";
i++;
}
while (i >= 10) ;
return 0;
}
It breaks the current flow of the program at the given condition. In case of inner loop,
it breaks only inner loop.
jump-statement;
break;
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;
}
cout<<i<<"\n";
}
}
1
2
3
4
The C++ continue statement is used to continue loop. It continues the current flow of
the program and skips the remaining code at specified condition. In case of inner loop,
it continues only inner loop.
jump-statement;
continue;
#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=10;i++){
if(i==5){
continue;
}
cout<<i<<"\n";
}
}
1
2
3
4
6
7
8
9
10
C++ Goto Statement
The C++ goto statement is also known as jump statement. It is used to transfer control
to the other part of the program. It unconditionally jumps to the specified label.
It can be used to transfer control from deeply nested loop or switch case label.
Syntax :
Goto statement :
statement:
#include <iostream>
using namespace std;
int main()
{
ineligible: cout<<"You are not eligible to vote!\n";
cout<<"Enter your age:\n";
int age;
cin>>age; 15
if (age < 18)
{
goto ineligible;
}
else
{
cout<<"You are eligible to vote!";
}
}
UNIT-3
C++ Functions
The function in C++ language is also known as
procedure or subroutine in other programming languages.
Advantage of functions in C
1) Code Reusability
2) Code optimization
Types of Functions
Syntax :
Function defintion
cout<<”hello”<<endl;
}
int main()
{
func();
func();
func();
cout<<”the program has ended”;
}
Call by value and call by reference in C++
There are two ways to pass value or data to function in C
language: call by value and call by reference. Original
value is not modified in call by value but it is modified
in call by reference.
#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;
}
Value of the data is: 3
#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
int swap;
swap=*x;
*x=*y;
*y=swap;
}
int main()
{
int x=500, y=100;
swap(&x, &y); // passing value to function
cout<<"Value of x is: "<<x<<endl;
cout<<"Value of y is: "<<y<<endl;
return 0;
}
C++ Recursion
#include<iostream>
using namespace std;
int main()
{
int factorial(int);
int fact,value;
cout<<"Enter any number: ";
cin>>value;
fact=factorial(value);
cout<<"Factorial of a number is: "<<fact<<endl;
return 0;
}
int factorial(int n)
{
if(n<0)
return(-1); /*Wrong value*/
if(n==0)
return(1); /*Terminating condition*/
else
{
return(n*factorial(n-1));
}
}
When the inline function is encountered, then the definition of the function is copied
to it. In this case, there is no control transfer which saves a lot of time and also
decreases the overhead.
#include<iostream>
using namespace std;
Class cal
{
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
Cal c;
cout<<"Addition of 'a' and 'b' is:"<<c.add(2,3);
return 0;
}
#include <iostream>
using namespace std;
class Cal {
public:
int add(int a,int b){
return a + b;
}
int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
30
55
Arrays
Like other programming languages, array in C++ is a
group of similar types of elements that have contiguous
memory location.
#include <iostream>
using namespace std;
int main()
{
int a[5]={10, 0, 20, 0, 30};
for (int i = 0; i < 5; i++)
{
cout<<a[i]<<"\n";
}
}
#include <iostream>
using namespace std;
int main()
{
int test[3][3]={{1,2,3},{4,5,6},{7,8,9}}; //declaration of 2D array
//traversal
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
cout<< test[i][j]<<" ";
}
cout<<"\n"; //new line at each row
}
return 0;
}
5 10 0
0 15 20
30 0 10
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Class
Inheritance
Polymorphism
Abstraction
Hiding internal details and showing functionality is
known as abstraction. For example: phone call, we don't
know the internal processing.
Encapsulation
Object
Object is an instance of a class. All the members of the class can be accessed through
object.
Let's see an example to create object of student class using s1 as the reference
variable.
In this example, Student is the type and s1 is the reference variable that refers to the
instance of Student class.
Class
class Student
{
public:
int id; //field or data member
float salary; //field or data member
String name;//field or data member
}
Class classname
Memberfunctions;----accessspecifiers returntype
functionname(parameters)
body
}
};
#include <iostream>
using namespace std;
class Student
{
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
};
int main() {
Student s1; //creating an object of Student
s1.id = 1;
s1.name = "a";
cout<<s1.id<<endl;
cout<<s1.name<<endl;
return 0;
}
1
a
#include <iostream>
using namespace std;
class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
void insert(int i, string n)
{
id = i;
name = n;
}
void display()
{
cout<<id<<" "<<name<<endl;
}
};
int main( ) {
Student s1; //creating an object of Student
Student s2; //creating an object of Student
s1.insert(1, "alekhya");
s2.insert(2, "alli");
s1.display();
s2.display();
return 0;
}
1 alekhya
2 alli
#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
void insert(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main() {
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
e1.insert(1, "alekhya”,2000);
e2.insert(2, "ali", 3000);
e1.display();
e2.display();
return 0;
}
alekhya 2000
ali 3000
Constructor
o Default constructor
o Parameterized constructor
o Copy constructor
Default Constructor
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main()
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}
Default Constructor Invoked
Default Constructor Invoked
Parameterized Constructor
#include <iostream>
class Employee {
public:
float salary;
id = i;
name = n;
salary = s;
void display()
};
int main(void) {
e1.display();
return 0;
Copy Constructor
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1)
{
x = x1;
y = y1;
}
// Copy constructor
Point(const Point &temp)
{
x = temp.x;
y = temp.y;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor of p2 is called here
// Let us access values assigned by constructors
cout<< "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout<< "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
}
Destructor
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main()
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
C++ Friend function
class class_name
{
friend data_type function_name(argument/s); // syntax of f
riend function.
};
#include <iostream>
using namespace std;
class A
{
int x =5;
friend class B; // friend class.
};
class B
{
public:
void display(A &a)
{
cout<<"value of x is : "<<a.x;
}
};
int main()
{
A a;
B b;
b.display(a);
return 0;
}
value of x is : 5
when the global and local variable or function has the same name in a program, and
when we call the variable, by default it only accesses the inner or local variable
without calling the global variable. In this way, it hides the global variable or function.
To overcome this situation, we use the scope resolution operator to fetch a program's
hidden variable or function.
Program to access the hidden value using the scope resolution (::) operator
#include <iostream>
using namespace std;
// declare global variable
int num = 50;
int main ()
{
// declare local variable
int num = 100;
Program to define the member function outside of the class using the scope resolution
(::) operator
#include <iostream>
using namespace std;
class Operate
{
public:
// declaration of the member function
void fun();
};
// define the member function outside the class.
void Operate::fun() /* return_type Class_Name::function_name */
{
cout << " It is the member function of the class. ";
}
int main ()
{
// create an object of the class Operate
Operate op;
op.fun();
return 0;
}
It is the member function of the class.
Program to demonstrate the standard namespace using the scope resolution (::)
operator
#include <iostream>
int main ()
{
int num = 0;
Strings
#include <iostream>
using namespace std;
int main( ) {
string s1 = "Hello";
char ch[] = { 'C', '+', '+'};
string s2 = string(ch);
cout<<s1<<endl;
cout<<s2<<endl;
}
Hello
C++
#include <iostream>
#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
char a[] = "mango";
char b[50];
do {
cout<<"What is my favourite fruit? ";
cin>>b;
} while (strcmp (a,b) != 0);
cout<<"Answer is correct!!"<<endl;
return 0;
}
What is my favourite fruit? apple
What is my favourite fruit? banana
What is my favourite fruit? mango
Answer is correct!!
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char a[25], b[25];
cout << "Enter the first string: ";
cin>>a;
cout << "Enter the second string: ";
cin>>b;
strcat(a, b);
cout << "a = " << a << endl;
cout << "b = " << b<<endl;
return 0;
}
Enter the key string: Welcome to
Enter the buffer string: C++ Programming.
Key = Welcome to C++ Programming.
Buffer = C++ Programming.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char a[25], b[25];
cout << "Enter the string: ";
cin>>a;
strcpy(b, a);
cout << "string = "<< a << endl;
cout << "copy string = "<< b<<endl;
return 0;
}
Enter the string: ISBAT
String= ISBAT
copy string = ISBAT
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char ary[] = "Welcome to C++ Programming";
cout << "Length of String = " << strlen(ary)<<endl;
return 0;
}
Length of String = 26
UNIT-4
Inheritance
In C++, inheritance is a process in which one object
acquires all the properties and behaviors of its parent
object automatically.
Types Of Inheritance
C++ supports five types of inheritance:
o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
o Hybrid inheritance
Derived Classes
A Derived class is defined as the class derived from the
base class.
Single Inheritance
Single inheritance is defined as the inheritance in which
a derived class is inherited from the only one base class.
Where 'A' is the base class, and 'B' is the derived class.
#include <iostream>
using namespace std;
class Account {
public:
float salary = 60000;
};
class Programmer: public Account {
public:
float bonus = 5000;
};
int main(void) {
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}
Salary: 60000
Bonus: 5000
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking...";
}
};
int main(void) {
Dog d1;
d1.eat();
d1.bark();
return 0;
}
Eating...
Barking...
Multilevel Inheritance
Multilevel inheritance is a process of deriving a class
from another derived class.
Multi Level Inheritance Example
When one class inherits another class which is further
inherited by another class, it is known as multi level
inheritance in C++. Inheritance is transitive so the last
derived class acquires all the members of all its base
classes.
#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;
}
Eating...
Barking...
Weeping...
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;
}
The value of a is : 10
The value of b is : 20
Addition of a and b is : 30
Hybrid Inheritance
Hybrid inheritance is a combination of more than one
type of inheritance.
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a()
{
std::cout << "Enter the value of 'a' : " << std::endl;
cin>>a;
}
};
class B : public A
{
protected:
int b;
public:
void get_b()
{
std::cout << "Enter the value of 'b' : " << std::endl;
cin>>b;
}
};
class C
{
protected:
int c;
public:
void get_c()
{
std::cout << "Enter the value of c is : " << std::endl;
cin>>c;
}
};
class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
#include <iostream>
using namespace std;
class Shape // Declaration of base class.
{
public:
int a;
int b;
void get_data(int n,int m)
{
a= n;
b = m;
}
};
class Rectangle : public Shape // inheriting Shape class
{
public:
int rect_area()
{
int result = a*b;
return result;
}
};
class Triangle : public Shape // inheriting Shape class
{
public:
int triangle_area()
{
float result = 0.5*a*b;
return result;
}
};
int main()
{
Rectangle r;
Triangle t;
int length,breadth,base,height;
std::cout << "Enter the length and breadth of a rectangle: " << std::endl;
cin>>length>>breadth;
r.get_data(length,breadth);
int m = r.rect_area();
std::cout << "Area of the rectangle is : " <<m<< std::endl;
std::cout << "Enter the base and height of the triangle: " << std::endl;
cin>>base>>height;
t.get_data(base,height);
float n = t.triangle_area();
std::cout <<"Area of the triangle is : " << n<<std::endl;
return 0;
}
Enter the length and breadth of a rectangle:
23
20
Area of the rectangle is : 460
Enter the base and height of the triangle:
2
5
Area of the triangle is : 5
UNIT-5
Polymorphism
The term "Polymorphism" is the combination of "poly"
+ "morphs" which means many forms. It is a greek word.
In object-oriented programming, we use 3 main concepts:
inheritance, encapsulation, and polymorphism.
Operator overloading
Method Overloading
Function Overloading is defined as the process of
having two or more function with the same name,
but different in parameters is known as function
overloading in C++. In function overloading, the
function is redefined by using either different types
of arguments or a different number of arguments. It
is only through these differences compiler can
differentiate between the functions.
#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
Output:
30
55
Operator Overloading
Where the return type is the type of value returned by the function.
#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++() {
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}
The Count is: 10
Method Overriding
If derived class defines same function as defined in
its base class, it is known as function overriding in
C++. It is used to achieve runtime polymorphism. It
enables you to provide specific implementation of
the function which is already provided by its base
class.
#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
};
int main(void) {
Dog d = Dog();
d.eat();
return 0;
}
Output:
Eating bread...
#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{ cout<<"Eating bread...";
}
};
int main() {
Dog d = Dog();
d.eat();
return 0;
}
Output:
Eating bread...
Run time Polymorphism Example: By
using two derived class (an example with virtual
keyword.)
#include <iostream>
using namespace std;
class Shape { // base class
public:
virtual void draw(){ // virtual function
cout<<"drawing..."<<endl;
}
};
class Rectangle: public Shape // inheriting Shape class.
{
public:
void draw()
{
cout<<"drawing rectangle..."<<endl;
}
};
class Circle: public Shape // inheriting Shape class.
{
public:
void draw()
{
cout<<"drawing circle..."<<endl;
}
};
int main() {
Shape *s; // base class pointer.
Shape sh; // base class object.
Rectangle rec;
Circle cir;
s=&sh;
s->draw();
s=&rec;
s->draw();
s=○
s->draw();
}
drawing...
drawing rectangle...
drawing circle...
o When the function has no definition, such function is known as "do-nothing" function.
o The "do-nothing" function is known as a pure virtual function. A pure virtual function is a
function declared in the base class that has no definition relative to the base class.
#include <iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
class Derived : public Base
{
public:
void show()
{
cout << "Derived class is derived from the base class." << std::endl;
}
};
int main()
{
Base *bptr;
//Base b;
Derived d;
bptr = &d;
bptr->show();
return 0;
}
Exception Handling
Exception Handling in C++ is a process to handle runtime errors. We
perform exception handling so the normal flow of the application can
be maintained even after runtime errors.
Try
Catch
throw
The try statement allows you to define a block of code to be tested for errors while it is
being executed.
The throw keyword throws an exception when a problem is detected, which lets us create
a custom error.
The catch statement allows you to define a block of code to be executed, if an error occurs
in the try block.
try
{
// Block of code to try
throw exception; // Throw an exception when a problem
arise
}
catch () {
// Block of code to handle errors
}
o try
o catch, and
o throw
#include <iostream>
using namespace std;
float division(int x, int y)
{
if( y == 0 )
{
throw "Attempted to divide by zero!";
}
return (x/y);
}
int main () {
int i = 25;
int j = 0;
float k = 0;
try {
k = division(i, j);
cout << k << endl;
}
catch (const char* e) {
cerr << e << endl;
}
return 0;
}
Output:
Attempted to divide by zero!
#include <iostream>
using namespace std;
int main() {
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
return 0;
}
#include <iostream>
int main()
try {
try{
throw 20;
catch (int n) {
throw;//Re-throwing an exception
catch (int n) {
return 0;
To read and write from a file we are using the standard C++ library
called fstream. Let us see the data types define in fstream library is:
Data Type Description
fstream It is used to create files, write information to files, and read information from files.
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream filestream("a.txt");
if (filestream.is_open())
{
filestream << "Welcome \n";
filestream << "C++ \n";
filestream.close();
}
else cout <<"File opening is fail.";
return 0;
}