Ilovepdf Merged
Ilovepdf Merged
MANAGEMENT
WHY DO WE NEED
FILE HANDLING /FILE
MANAGEMENT?
TEXT FILES
7
BINARY FILES.
9
FILE OPERATIONS
10
11
OPENING A FILE - FOR
CREATION AND EDIT
Ex:fopen("E:\\cprogram\\newprogram.txt","w"
);
Open for both reading and writing If the file does not exist,
rb+
in binary mode. fopen( ) returns NULL.
Open for both reading and If the file does not exist, it
a+
appending. will be created.
Open for both reading and If the file does not exist, it
ab+
appending in binary mode. will be create
14
CLOSING A FILE
16
Function Description
17
WRITING TO A TEXT FILE
Function Description
#include <stdio.h>
printf("Enter num: ");
#include <stdlib.h>
scanf("%d",&num);
int main()
{
fprintf(fptr,"%d",num);
int num;
fclose(fptr);
FILE *fptr;
return 0;
// use appropriate location if
}
you are using MacOS or Linux
fptr =
fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
19
Example 2: Read from a text file
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
fscanf(fptr,"%d", &num);
FILE* demo;
int display;
demo = fopen("demo_file.txt", "r");
while (1) {
display = fgetc(demo);
if (feof(demo))
break;
printf("%c", display);
}
fclose(demo);
return 0;
} 21
Example 4: Read from a binary file
#include <stdio.h>
#include <stdlib.h> // else it will return a pointer
to the file.
struct threeNum { for (n = 1; n < 5; ++n) {
int n1, n2, n3; fread(&num,
}; sizeof(struct threeNum), 1,
int main() fptr);
{ printf("n1: %d\tn2:
int n; %d\tn3: %d\n", num.n1,
struct threeNum num; num.n2,
FILE* fptr; num.n3);
if ((fptr = }
fopen("C:\\program.bin", fclose(fptr);
"rb")) == NULL) {
printf("Error! opening return 0;
file"); }
// If file pointer will
return NULL Output
// Program will exit. n1: 1 n2: 5 n3: 6
exit(1); n1: 2 n2: 10 n3: 11
} n1: 3 n2: 15 n3: 16 22
n1: 4 n2: 20 n3: 21
FSEEK()
23
Example : use of fseek() in C
#include <stdio.h>
Syntax :
int main() int fseek(FILE *ptr, long int offset,
{ int pos);
FILE* fp;
fp = fopen("test.txt", "r");
return 0;
}
24
REWIND()
Syntax :
rewind (file_pointer);
25
Example: the use of rewind
#include <stdio.h>
int main()
{
FILE* fptr;
fptr = fopen("file.txt", "w+");
fprintf(fptr, "Geeks for Geeks\n");
// using rewind()
rewind(fptr);
printf("%s", buf);
return 0;
}
26
INTRODUCTION TO C++
HISTORY
• Origin:
C++ was created in the late 1970s at Bell Laboratories by
Bjarne Stroustup, initially called "C with Classes" with the
aim to enhance the capabilities of the C language by
incorporating object-oriented programming concepts.
• Evolution:
Over time, C++ has gone through several revisions and
standardizations, with the ISO C++ Standards Committee playing a
key role in maintaining compatibility across different
implementations.
5
KEY FEATURES OF C++
• Object-Oriented Programming:
C++ fully supports object-oriented paradigms like classes, objects, inheritance, polymorphism, and
encapsulation, enabling code reusability and modularity.
• Memory Management:
Allows for direct memory manipulation through pointers, providing fine-grained control over
memory allocation, which can be crucial for performance-critical applications.
• Generic Programming:
C++ supports templates, which enable writing generic code that can work with different data
types, promoting code flexibility.
• High Performance:
Due to its low-level control and efficient compilation, C++ is often preferred for applications where
speed is critical.
• Platform Independence:
C++ code can be compiled and run on various operating systems with minimal modifications,
making it portable.
6
APPLICATIONS OF C++
• Game Development:
C++ is widely used to create high-performance game engines due to its speed and control over graphics
rendering.
• System Programming:
Operating systems, device drivers, and embedded systems often utilize C++ because of its ability to
directly interact with hardware.
• Scientific Computing:
Numerical simulations and complex algorithms in fields like physics and engineering are frequently
implemented in C++ due to its computational efficiency.
• High-Frequency Trading:
C++ is often used for high-performance trading systems due to its ability to handle large volumes of
data quickly.
• Desktop Applications:
C++ can be used to develop complex graphical user interface applications across different platforms.
7
SETTING UP DEVELOPMENT
ENVIRONMENT (IDES, COMPILERS)
• https://www.youtube.com/watch?v=s6pXKE91_hE
• A basic C++ program structure includes a "main" function where the core logic resides,
utilizes data types to define variable types (like integers, floats, characters), uses variables to
store data, and interacts with the user through input (using "cin") and output (using "cout")
operations within the standard input/output stream.
• Key elements:
1. Header Inclusion:
#include <iostream>: This line includes the standard input/output library, allowing you to
use "cin" and "cout" for basic input and output.
2. Namespace Declaration:
using namespace std;: This line allows you to use standard library elements like "cin" and
"cout" without the "std::" prefix.
3. Main Function:
int main() { ... }: The "main" function is the entry point of your program, where the
execution starts.
9
DATA TYPES
10
11
EXAMPLE PROGRAM
#include <iostream>
using namespace std;
int main( )
{
string name;
int age;
cout << "Enter your name: ";
cin >> name;
cout << "Enter your age: ";
cin >> age;
cout << "Hello, " << name << "! You are " << age << " years old."
<< endl;
return 0;
}
12
Figure 1
13
CONTROL STRUCTURES IN C++
2. Selection Structure
Selection structure refers to the execution of instruction
according to the selected condition, which can be either
true or false. There are two ways to implement selection
structures, by “if-else statements” or by “switch case
statements”. An example diagram for selection structure
is shown in figure 2.
Figure
2
14
3. Loop Structure
Loop structure refers to the execution of an instruction in
a loop until the condition gets false. An example diagram
for loop structure is shown in figure 3.
Figure
3
15
IF ELSE STATEMENTS IN C++
16
As shown in figure 4, we declared a variable “age” and used “cin" function to gets its value from the user at run
time. At line 10 we have used "if” statement and give a condition “(age<18)” which means that if the age entered
by the user is smaller than "18” the output will be “you cannot come to my party” but if the age is not smaller
than “18” the compiler will move to the next condition.
At line 13 we have used “else if” statement and given another condition “age==18" which means that if the age
entered by the user is equal to "18” the output will be “you are a kid and you will get a kid pass to the party” but
if the age is not equal to the “18” the compiler will move to the next condition.
At line 16 we have used “else" condition which means that if none of the above condition is "true" the output will
be "you can come to the party”.
OUTPUT:
As can be seen in figure 5, that when we entered the age "81" which was greater
than 18, so it gives us the output "you can come to the party”. The main thing to 17
note here is that we can use as many “else if” statements as we want.
Figure
5
SWITCH CASE STATEMENTS IN C++
In switch-case statements, the value of the variable is tested with all the cases. An example program for
the switch case statement is shown in figure 6.
Figure 18
As shown in figure 4, we passed a variable “age” to the switch statement. The switch statement will compare the
value of variable “age" with all cases. For example, if the entered value for variable "age” is “18”, the case with
value “18” will be executed and prints “you are 18”. The keyword “break" will let the compiler skips all other
cases and goes out of the switch case statement. An output of the following program is shown in figure 6.
20
LOOPS IN C++
INFINITE LOOP
21
Procedural Vs Object Oriented
Programming
In procedural programming, the program is divided into In object-oriented programming, the program is divided
small parts called functions. into small parts called objects.
Adding new data and functions is not easy. Adding new data and function is easy.
Procedural programming does not have any proper way of Object-oriented programming provides data hiding so it is
hiding data so it is less secure. more secure.
In procedural programming, there is no concept of data In object-oriented programming, the concept of data hiding
hiding and inheritance. and inheritance is used.
In procedural programming, the function is more important In object-oriented programming, data is more important
than the data. than function.
Procedural programming is based on the unreal world. Object-oriented programming is based on the real world.
Procedural programming is used for designing Object-oriented programming is used for designing large
medium-sized programs. and complex programs.
Procedural programming uses the concept of procedure Object-oriented programming uses the concept of data
abstraction. abstraction.
Code reusability absent in procedural programming, Code reusability present in object-oriented programming.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
Introduction to Object-Oriented
Programming (OOP) concepts
OOPs Concepts:
● Class
● Objects
● Data Abstraction
● Encapsulation
● Inheritance
● Polymorphism
● Dynamic Binding
● Message Passing
4
Introduction to Object-Oriented
Programming (OOP) concepts
1. Class: A class is a user-defined data type. It consists of data members and member functions, which
can be accessed and used by creating an instance of that class. It represents the set of properties or
methods that are common to all objects of one type. A class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and brands but
all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage
range, etc. So here, Car is the class, and wheels, speed limits, mileage are their properties.
2. Object: It is a basic unit of Object-Oriented Programming and represents the real-life entities. An
Object is an instance of a Class. When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated. An object has an identity, state, and behavior.
Each object contains data and code to manipulate the data. Objects can interact without having to know
details of each other’s data or code, it is sufficient to know the type of message accepted and type of
response returned by the objects.
For example: “Dog” is a real-life Object, which has some characteristics like color, Breed, Bark, Sleep,
and Eats.
5
Introduction to Object-Oriented
Programming (OOP) concepts
3. Data Abstraction: Data abstraction is one of the most essential and important features of
object-oriented programming. Data abstraction refers to providing only essential information about the
data to the outside world, hiding the background details or implementation. Consider a real-life example
of a man driving a car. The man only knows that pressing the accelerators will increase the speed of the
car or applying brakes will stop the car, but he does not know about how on pressing the accelerator the
speed is increasing, he does not know about the inner mechanism of the car or the implementation of the
accelerator, brakes, etc in the car. This is what abstraction is.
4. Encapsulation: Encapsulation is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates. In Encapsulation, the variables or data
of a class are hidden from any other class and can be accessed only through any member function of
their class in which they are declared. As in encapsulation, the data in a class is hidden from other
classes, so it is also known as data-hiding.
Introduction to Object-Oriented
Programming (OOP) concepts
7
Introduction to Object-Oriented
Programming (OOP) concepts
6. Polymorphism: The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. For example, A person
at the same time can have different characteristics. Like a man at the same time is a father, a husband, an
employee. So the same person posses different behavior in different situations. This is called
polymorphism.
Introduction to Object-Oriented
Programming (OOP) concepts
7. Dynamic Binding: In dynamic binding, the code to be executed in response to the function call is
decided at runtime. Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run time. Dynamic Method Binding One of the main advantages of
inheritance is that some derived class D has all the members of its base class B. Once D is not hiding any
of the public members of B, then an object of D can represent B in any context where a B could be used.
This feature is known as subtype polymorphism.
8. Message Passing: It is a form of communication used in object-oriented programming as well as
parallel programming. Objects communicate with one another by sending and receiving information to
each other. 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 results. Message passing involves specifying
the name of the object, the name of the function, and the information to be sent.
9
Defining Class in C++
A class is defined in C++ using the keyword class followed by the name of the class. The
following is the syntax:
class ClassName {
access_specifier:
// Body of the class
};
Example
class ThisClass {
public:
int var; // data member
void print() { // member method
cout << "Hello";
}
10
};
We can create an object of the given class in the same way we declare the variables of
any other inbuilt data type.
ClassName ObjectName;
Example: MyClass obj;
In the above statement, the object of MyClass with name obj is created.
The data members and member functions of the class can be accessed using the dot(‘.’)
operator with the object. For example, if the name of the object is obj and you want to
access the member function with the name printName() then you will have to write:
obj.printName( );
11
// C++ program to illustrate how create a simple class and object
#include <iostream>
#include <string>
using namespace std;
Access Modifiers/Specifiers
In C++ classes, we can control the access to the members of the class using
Access Specifiers. Also known as access modifier, they are the keywords that
are specified in the class and all the members of the class under that access
specifier will have particular access level.
In C++, there are 3 access specifiers that are as follows:
1. Public: Members declared as public can be accessed from outside the
class.
2. Private: Members declared as private can only be accessed within the
class itself.
3. Protected: Members declared as protected can be accessed within the
class and by derived classes.
If we do not specify the access specifier, the private specifier is applied to every
member by default.
13
// C++ program to demonstrate accessing of data members
#include <bits/stdc++.h> // include all the standard libraries
using namespace std;
class Geeks {
private:
string geekname;
// Access specifier
public:
// Member Functions()
void setName(string name) { geekname = name; }
Till now, we have defined the member function inside the class, but we
can also define the member function outside the class. To define a
member function outside the class definition,
● We have to first declare the function prototype in the class
definition.
● Then we have to use the scope resolution:: operator along
with the class name and function name.
15
// C++ program to demonstrate member function definition outside class
#include <bits/stdc++.h>
using namespace std;
class Geeks {
public:
string geekname;
int id; Output
// printname is not defined inside class definition
Geekname is: xyz
void printname();
// printid is defined inside class definition Geek id is: 15
void printid() { cout << "Geek id is: " << id; }
};
Note that all the member functions defined
// Definition of printname using scope resolution operator :: inside the class definition are by default
void Geeks::printname() inline, but you can also make any
{
cout << "Geekname is: " << geekname; non-class function inline by using the
} keyword inline with them. Inline functions
int main() are actual functions, which are copied
{
Geeks obj1; everywhere during compilation, like
obj1.geekname = "xyz"; pre-processor macro, so the overhead of
obj1.id = 15; function calls is reduced.
// call printname()
obj1.printname(); Note: Declaring a friend function is a
cout << endl; way to give private access to a
// call printid()
obj1.printid(); non-member function.
return 0; 16
Constructors
Constructors are special class members which are called by the compiler every time
an object of that class is instantiated. Constructors have the same name as the class
and may be defined inside or outside the class definition.
There are 4 types of constructors in C++ classes:
● Default Constructors: The constructor that takes no argument is called default
constructor.
● Parameterized Constructors: This type of constructor takes the arguments to
initialize the data members.
● Copy Constructors: Copy constructor creates the object from an already
existing object by copying it.
● Move Constructor: The move constructor also creates the object from an
already existing object but by moving it.
17
// C++ program to demonstrate constructors
#include <bits/stdc++.h>
using namespace std;
class Geeks
{
public:
int id; Output
//Default Constructor Default Constructor called
Geeks()
{ Geek id is: -1
cout << "Default Constructor called" << endl; Parameterized Constructor called
id=-1;
} Geek id is: 21
//Parameterized Constructor
Geeks(int x)
{
cout <<"Parameterized Constructor called "<< endl;
id=x;
} Note: If the programmer does not define
}; the constructor, the compiler automatically
int main() {
creates the default, copy and move
// obj1 will call Default Constructor
Geeks obj1; constructor.
cout <<"Geek id is: "<<obj1.id << endl;
// obj2 will call Parameterized Constructor
Geeks obj2(21);
cout <<"Geek id is: " <<obj2.id << endl;
return 0; 18
Destructors
19
// C++ program to explain destructors
#include <bits/stdc++.h>
using namespace std;
class Geeks
{
public:
int id; Output
//Definition for Destructor Destructor called for id: 0
~Geeks() Destructor called for id: 1
{
cout << "Destructor called for id: " << id <<endl; Destructor called for id: 2
} Destructor called for id: 3
};
Destructor called for id: 4
int main() Destructor called for id: 7
{
Geeks obj1;
obj1.id=7;
int i = 0;
while ( i < 5 )
{
Geeks obj2;
obj2.id=i;
i++;
} // Scope for obj2 ends here
return 0;
} // Scope for obj1 ends here 20
Encapsulation
● Benefits of Encapsulation:
Improved code maintainability:
By hiding internal implementation details, changes to the class structure can be made
without affecting external code that interacts with it.
Data integrity:
Validation checks within mutators can prevent invalid data from being assigned to
variables, ensuring data consistency.
Modular design:
Encapsulation promotes the creation of well-defined, independent objects that can be
easily reused in different parts of the application.
22
Inheritance
• Types of Inheritance:
Single Inheritance:
A derived class inherits from only one base class, providing a simple "is-a" relationship.
Multiple Inheritance:
A derived class inherits from multiple base classes, allowing it to combine features from
various sources.
Multilevel Inheritance:
A class inherits from a derived class which itself inherits from another base class,
creating a chain of inheritance.
23
Encapsulation
● Access Control:
Public:
Members declared as public can be accessed from anywhere, including outside the class
and in derived classes.
Protected:
Members declared as protected can be accessed within the derived class and its
subclasses, but not from outside the class hierarchy.
Private:
Members declared as private can only be accessed within the class they are defined in, not
even by derived classes.
● Member Functions:
Inherited Member Functions:
When a class inherits from another, it automatically inherits all the member functions
(methods) of the base class.
Overriding Member Functions:
A derived class can redefine a member function inherited from the base class, allowing it
to provide a specialized implementation while maintaining the same function signature.
24
25
Polymorphism
Key points
3
Key points
Virtual Functions:
● A member function declared with the "virtual" keyword in a base class.
● When a pointer to a base class object points to a derived class object, calling a virtual
function on the pointer will invoke the derived class's overridden version.
Abstract Class:
● A class that cannot be directly instantiated and is meant to be used as a blueprint for
derived classes to implement.
class Animal {
public:
virtual void speak() { // Virtual function
cout << "Generic animal sound" << endl;
}
};
int main() {
Animal *ptr = new Dog(); // Pointer to base class pointing to a derived class object
ptr->speak();
} 5
Function and Operator Overloading
C++ allows you to specify more than one definition for a function name or an
operator in the same scope, which is called function overloading and operator
overloading respectively.
An overloaded declaration is a declaration that is declared with the same name as a
previously declared declaration in the same scope, except that both declarations
have different arguments and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the
most appropriate definition to use, by comparing the argument types you have used
to call the function or operator with the parameter types specified in the definitions.
The process of selecting the most appropriate overloaded function or operator is
called overload resolution.
#include <iostream>
using namespace std;
class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
Output:
int main(void) { Printing int: 5
printData pd; Printing float: 500.263
// Call print to print integer Printing character: Hello C++
pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
return 0;
} 7
Function Overloading in C++
You can have multiple definitions for the same function name in the same scope. The definition of the
function must differ from each other by the types and/or the number of arguments in the argument list.
You cannot overload function declarations that differ only by return type.
Overloaded operators are functions with special names: the keyword "operator" followed by the symbol
for the operator being defined. Like any other function, an overloaded operator has a return type and a
parameter list.
Box operator+(const Box&);
declares the addition operator that can be used to add two Box objects and returns final Box object. Most
overloaded operators may be defined as ordinary non-member functions or as class member functions. In
case we define above function as non-member function of a class then we would have to pass two
arguments for each operand as follows −
Box operator+(const Box&, const Box&);
#include <iostream>
using namespace std;
class Box {
public:
double getVolume(void) {
return length * breadth * height;
}
void setLength( double len ) {
length = len;
}
void setBreadth( double bre ) {
breadth = bre;
}
void setHeight( double hei ) {
height = hei;
}
// Overload + operator to add two Box objects.
Box operator+(const Box& b) {
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
9
};
// Main function for the program
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume(); Output:
cout << "Volume of Box1 : " << volume <<endl; Volume of Box1 : 210
// volume of box 2 Volume of Box2 : 1560
volume = Box2.getVolume(); Volume of Box3 : 5400
cout << "Volume of Box2 : " << volume <<endl;
// Add two object as follows:
Box3 = Box1 + Box2;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
} 10
Templates
11
Function Templates
12
#include <iostream>
using namespace std;
int main() {
// Example with integers
int x = 10, y = 20;
cout << "Before swap (int): x = " << x << ", y = " << y << endl;
swap(x, y);
cout << "After swap (int): x = " << x << ", y = " << y << endl;
return 0;
} 13
Class Templates
14
16
17
Exception handling
18
● Try block: This block encloses the code that might potentially
throw an exception.
● Throw statement: When an error occurs within the "try" block, the
"throw" keyword is used to signal the exception, often passing an
exception object containing details about the error.
● Catch block: This block is executed if an exception is thrown
within the "try" block, and it allows you to handle the exception
based on its type.
19
How it works?
20
● Purpose:
In C++, exception specifications are used to explicitly state which
types of exceptions a function may throw, enabling the compiler to
check if a function is potentially throwing exceptions that are not
handled by the calling code.
● Syntax:
A function can be declared with an exception specification using the
"throw()" keyword, followed by a list of exception types that the
function might throw.
21
Example
int main() {
try {
int result = divide(10, 0);
std::cout << result << std::endl; // This line will not be reached
} catch (const std::runtime_error& e) { // Catch the specific exception
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
22
23