Programming using C++
Lovely Professional University
A training report
Submitted in partial fulfilment of the requirements for the award of
degree of
B. Tech.(CSE)
Submitted to
LOVELY PROFESSIONAL UNIVERSITY
PHAGWARA, PUNJAB
From 05/06/24 to 09/07/24
SUBMITTED BY :
Rohit Yadav
Registration Number: 12218514
DECLARATION
I hereby declare that I successfully completed my five-week summer training program
at the platform, which spanned from June 05, 2024, to July 09, 2024. During this
period, I engaged in comprehensive learning and practical applications across various
aspects of programming language, fundamentals, and related technologies.
The training provided me with valuable insights and hands-on experience,
significantly enhancing my technical knowledge and skills. I am confident that the
learning outcomes achieved during this training align perfectly with the academic and
professional requirements for the award of the Bachelor of Technology ([Link])
degree in Computer Science and Engineering (CSE) at Lovely Professional
University, Phagwara.
Date – 27 Sept. 2024 Name – Rohit Yadav
Registration no: 12218514
ACKNOWLEDGEMENT
I would like to express my deepest gratitude to LPU for providing an exceptional
learning experience through their comprehensive Programming using C++ program.
The quality of the content and the depth of the material have significantly contributed
to my understanding and skills in these fields.
I extend my sincere thanks to the instructors and contributors who designed and
delivered the course, making complex topics accessible and engaging. Their dedication
and expertise were invaluable in enhancing my learning journey.
I am also grateful to my university and my professors for their continuous support and
encouragement throughout my studies. Their guidance has been crucial in motivating
me to apply the knowledge gained from this program in real-world scenarios.
Lastly, I would like to thank my family and friends for their unwavering support and
encouragement, which kept me motivated throughout the duration of this program.
Summer Training Certificate By LPU
TABLE OF CONTENTS
Inner first page…………………………………………………………...………(i)
Declaration………………………………………………………………………(ii)
Acknowledgement……………………………………………..………………..(iii)
Certificate………………………………………………………..……………...(iv)
Table of Contents………………………………………………………………..(v)
1. Introduction
2. Data Types & Operators
3. Flow Of Control
4. Functions
5. Arrays
6. Recursion
7. Classes and Objects
8. Constructors and Destructors
9. Inheritance
10. Polymorphism
11. Encapsulation and Abstraction
12. Conclusion
13. References
INTRODUCTION
Overview of C++
C++ is a powerful, versatile programming language that has been widely used since its
development in the early 1980s by Bjarne Stroustrup. Building upon the foundational
concepts of the C language, C++ introduces object-oriented programming (OOP) features,
enabling developers to create complex and efficient software systems. Its ability to blend
low-level memory manipulation with high-level abstractions makes it particularly suitable for
systems programming, game development, real-time simulations, and performance-critical
applications.
Significance of C++
The importance of C++ in the programming landscape cannot be overstated. It has
significantly influenced many other programming languages and remains a key tool for many
software engineering disciplines. C++ provides a robust framework for managing resources
and executing code efficiently, making it a popular choice for applications where
performance and system-level access are critical. Its use in a variety of domains, including
finance, embedded systems, and high-performance computing, highlights its versatility and
enduring relevance.
Purpose of the Report
This report aims to explore various aspects of programming in C++, including
its core concepts, features, and practical applications. The report will cover:
1. Core Concepts: An overview of fundamental C++ features such as data
types, control structures, functions, and object-oriented programming
principles.
2. Advanced Topics: Insights into more advanced features including templates,
exception handling, and the Standard Template Library (STL).
3. Practical Applications: Examples demonstrating how C++ is used in real-
world scenarios, including case studies and sample code.
4. Best Practices: Guidelines and best practices for writing efficient and
maintainable C++ code.
Scope and Structure
The scope of this report includes both theoretical and practical elements of C++
programming. It is structured to provide a comprehensive understanding of the language,
starting with foundational concepts and progressively delving into more complex topics.
Each section is designed to build upon the previous one, ensuring a coherent learning
experience.
By the end of this report, readers will have a solid grasp of C++ programming, equipped with
the knowledge to develop and optimize their own C++ applications. This report is intended
for students, developers, and anyone interested in mastering C++ and leveraging its
capabilities for diverse programming challenges.
Role of C++ in Implementing Data Structures
C++ plays a pivotal role in the implementation of data structures due to its flexibility,
efficiency, and support for object-oriented programming. With features like pointers, dynamic
memory management, and rich libraries, C++ allows for precise control over data structures,
facilitating the creation of highly efficient and scalable software solutions. During my
summer training, I leveraged C++ to understand and implement various data structures,
solidifying my foundation in both theoretical and practical aspects of programming.
ARRAYS
Definition and Basic Concepts
An array is a collection of elements stored in contiguous memory locations. All elements in
an array are of the same data type, and each element can be accessed using its index, which
starts from 0.
Types of Arrays
One-dimensional Array: A linear array where elements are stored in a single row.
Multi-dimensional Array: Arrays with more than one dimension, such as a 2D array (a
matrix), where data is stored in rows and columns.
Operations on Arrays
Insertion: Adding an element at a specific position in the array.
Deletion: Removing an element from a specific position in the array.
Traversal: Accessing and processing each element of the array one by one.
Searching: Finding the position of a specific element in the array.
Problems
1. Find the Second Largest Element in an Array
CODE:
int findSecondLargest(int arr[], int n) {
int first = INT_MIN, second = INT_MIN;
for (int i = 0; i < n; i++) {
if (arr[i] > first) {
second = first;
first = arr[i];
} else if (arr[i] > second && arr[i] != first) {
second = arr[i];
}
}
return second;
}
Explanation: This function iterates through the array to find the largest and second-largest
elements. The first variable tracks the largest, and second tracks the second-largest element.
2. Merge Two Sorted Arrays into a Single Sorted Array
CODE:
void mergeArrays(int arr1[], int arr2[], int n1, int n2, int merged[]) {
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
if (arr1[i] <= arr2[j]) {
merged[k++] = arr1[i++];
} else {
merged[k++] = arr2[j++];
}
}
while (i < n1) {
merged[k++] = arr1[i++];
}
while (j < n2) {
merged[k++] = arr2[j++];
}
}
Explanation: This function merges two sorted arrays by comparing elements from both
arrays and placing the smaller one into the merged array. It continues until all elements from
both arrays are merged.
Data Types & Operators
Data Types & Their Description
[Link] Data Types
They are arithmetic types and are further classified into:
•Integer Type
•Floating type
2. Enumerated types
They are again arithmetic types and they are used to define variables that
can only assign certain discrete integer values throughout the program.
3. The Type Void
The type specifier void indicates that no value is available.
4. Derived Types
They include
•Pointer types
•Array types
•Structure types
•Union types
•Function types
Operators
1. Arithmatic Operator
2. Relational Operator
Flow Of Control
C++ Loop Types
There may be a situation, when you need to execute a block of code several
number of times. In general, statements are executed sequentially: The first
statement in a function is executed first, followed by the second, and so on.
A loop statement allows us to execute a statement or group of statements
multiple times and following is the general from of a loop statement in most
of the programming languages
Figure 3.1: Control Flow Diagram Of Loop
C++ programming language provides the following type of loops to han-
dle looping requirements.
C++ decision making statements
Following is the general form of a typical decision making structure found in
most of the programming languages
Certainly! Here’s a summary of C++ decision-making statements in point form,
without code:
• if Statement
o Executes a block of code if a condition is true.
• if-else Statement
o Executes one block of code if a condition is true, and a different block
if it is false.
• if-else if-else Ladder
o Tests multiple conditions in sequence and executes the block of code
corresponding to the first true condition.
• switch Statement
o Selects one of many code blocks to execute based on the value of an
expression.
• Conditional (Ternary) Operator
o Provides a shorthand way to choose between two values based on a
condition.
Functions
C++ Functions
A function is a group of statements that together perform a task. Every
C++ program has at least one function, which is main(), and all the most
trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up
your code among different functions is up to you, but logically the division
usually is such that each function performs a specific task.
A function declaration tells the compiler about a function’s name, return
type, and parameters. A function definition provides the actual body of the
function.
The general form of a C++ function definition is as follows
Here’s a concise summary of functions in C++:
Function Definition
- A function is a block of code designed to perform a specific task, defined by
a function name, return type, and parameters.
Function Declaration
- Also known as a function prototype; it specifies the function's name, return
type, and parameters, but does not include the body.
Function Definition
- Provides the actual body of the function, detailing the code to be executed.
Function Call
- Executes the function’s code by referring to the function’s name and passing
arguments if needed.
Return Type
- Specifies the type of value that the function returns; if no value is returned,
the type is `void`.
Parameters
- Variables passed into the function to provide input values; a function can
have none, one, or multiple parameters.
Function Overloading
- Allows multiple functions with the same name but different parameter lists to
exist.
Default Arguments
- Provides default values for some or all parameters, which can be overridden
when the function is called.
Recursive Functions
- Functions that call themselves to solve smaller instances of a problem.
Scope
- Local variables declared within a function are only accessible within that
function, while global variables are accessible throughout the program.
Classes and Objects
C++ Classes
The main purpose of C++ programming is to add object orientation to
the C programming language and classes are the central feature of C++
that supports object-oriented programming and are often called user-defined
types.
A class is used to specify the form of an object and it combines data rep-
resentation and methods for manipulating that data into one neat package.
The data and functions within a class are called members of the class.
C++ Class Definitions
When you define a class, you define a blueprint for a data type. This doesn’t
actually define any data, but it does define what the class name means, that
is, what an object of the class will consist of and what operations can be
performed on such an object.
A class definition starts with the keyword class followed by the class
name; and the class body, enclosed by a pair of curly braces. A class
definition must be followed either by a semicolon or a list of declarations
For example, we defined the Box data type using the keyword class as
follows
The keyword public determines the access attributes of the members of
the class that follows it. A public member can be accessed from outside the
class anywhere within the scope of the class object. You can also specify
the members of a class as private or protected which we will discuss in a
sub-section.
Define C++ Objects
A class provides the blueprints for objects, so basically an object is created
from a class. We declare objects of a class with exactly the same sort of
declaration that we declare variables of basic types. Following statements
declare two objects of class Box
Both of the objects Box1 and Box2 will have their own copy of data
members.
Constructors and Destructors
Constructors and destructors are special functions in C++ that are automatically invoked
when objects are created or destroyed. They help manage the lifecycle of objects, ensuring
they are properly initialized and cleaned up.
Constructors
Purpose
A constructor is called automatically when a new object is created. Its main role is to set up
the initial state of the object. This includes allocating any resources the object may need and
initializing its data.
Types:
Default Constructor : This type of constructor does not take any arguments and sets
up the object with default values. It is automatically provided if you do not define any
constructors yourself.
Parameterized Constructor : This constructor takes one or more arguments,
allowing you to initialize the object with specific values. This is useful when you want to
create an object with custom settings right from the start.
Copy Constructor : This constructor creates a new object as a copy of an existing one.
It ensures that when an object is copied, the new object gets a duplicate of the original
object's data.
- **Use Case**: Imagine you're creating an object to represent a car. When you
create this car object, you want to ensure it has all the necessary details like its
make and model. The constructor initializes these details, making sure that
every car object starts off correctly.
Destructors
- Purpose: A destructor is called automatically when an object is destroyed, either when it
goes out of scope or when it is explicitly deleted. Its main role is to clean up resources that
the object might have used, such as closing files or releasing memory.
- Use Case : Continuing with the car example, suppose your car object has allocated
memory or opened a file. When you're done with the car object, the destructor ensures that
these resources are properly released. This prevents resource leaks and keeps the system
resources managed efficiently.
Summary
Constructors are essential for setting up an object’s initial state, ensuring that it is properly
configured when created. Destructors on the other hand, handle the cleanup process when an
object is no longer needed, ensuring that any resources it used are properly released. Together,
constructors and destructors help manage the lifecycle of objects in C++, making your code more
reliable and resource-efficient.
Inheritance
Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a
new class to inherit characteristics (data and behaviors) from an existing class. This
mechanism promotes code reusability and helps organize and structure code efficiently.
Key Concepts:
- Base Class : This is the original class from which properties and behaviors are
inherited. It contains common features that can be shared by other classes.
- Derived Class : This is the new class that inherits features from the base class.
It can add new properties and behaviors or modify existing ones.
Purpose
- Reusability : By inheriting from a base class, the derived class can reuse the
code and functionality already defined, which avoids code duplication.
- Extensibility : Derived classes can extend or customize the functionality of
the base class. This means you can build more specialized classes based on
general ones.
- Hierarchy: Inheritance establishes a hierarchy among classes, making it
easier to model real-world relationships and organize code in a logical structure.
Summary
Inheritance allows a class to inherit properties and methods from another class,
facilitating code reuse and establishing a clear hierarchy. It helps in organizing
and managing code by allowing new classes to build upon existing ones,
extending or modifying their functionality as needed.
Polymorphism
Polymorphism is a key concept in Object-Oriented Programming (OOP) that allows objects
of different classes to be treated as objects of a common base class. It enables a single
function or method to operate in different ways depending on the type of object it is acting
upon.
Key Aspects:
- Function Overloading : This allows multiple functions with the same name but
different parameters to be defined. The appropriate function is called based on the number or
type of arguments passed. For example, a function named `display` could show different
outputs depending on whether it's given a string or an integer.
- Operator Overloading : This lets you define custom behaviors for operators (like `+`,
`-`, etc.) for user-defined classes. This means you can use standard operators in a way that
makes sense for your class types.
- Virtual Functions: These are functions in a base class that can be overridden in derived
classes. When a function is marked as virtual, the version of the function that is called is
determined at runtime based on the actual object type, not the type of the reference or pointer.
This allows for more flexible and dynamic method calls.
- Runtime Polymorphism : Achieved through virtual functions, it allows the program
to decide which method to call at runtime based on the object’s actual type.
Summary
Polymorphism allows different classes to be treated through a common
interface, with methods behaving differently based on the actual object type. It
includes function and operator overloading and virtual functions, enabling
flexible and dynamic method invocation and promoting code reuse and
adaptability.
Encapsulation and Abstraction
Encapsulation and abstraction are fundamental concepts in Object-Oriented Programming
(OOP) that help manage complexity by focusing on the essential aspects of an object and
hiding the details.
Encapsulation
- Definition : Encapsulation is the practice of bundling data (attributes) and methods
(functions) that operate on that data within a single unit or class. It restricts direct access to
some of an object's components and provides controlled access through public methods.
Purpose:
- Data Protection : By hiding the internal state of an object and only exposing necessary
methods, encapsulation prevents unauthorized or unintended interference.
- Code Organization : It groups related data and functions together, which helps in
managing and understanding code more easily.
- Access Control : Encapsulation uses access specifiers (public, protected, private) to
control how the data and methods of a class can be accessed from outside the class.
Abstraction
- Definition : Abstraction involves hiding the complex implementation details
of an object and exposing only the essential features to the user. It focuses on
what an object does rather than how it does it.
Purpose
- Simplified Interaction : By presenting a simplified interface to the user, abstraction
makes it easier to interact with complex systems or objects.
- Focus on Relevant Aspects: It allows users to work with high-level concepts and
functionalities without needing to understand the underlying complexities.
- Implementation : This is often achieved through abstract classes and interfaces, which
define the structure without specifying detailed implementations.
Summary
Encapsulation groups data and methods within a class while controlling access to them,
ensuring data protection and code organization. Abstraction simplifies interaction with
complex systems by hiding detailed implementation and focusing on essential features.
Together, they help in managing complexity and enhancing the design of software systems.
RECURSION
Definition and Basic Concepts
Recursion is a programming technique where a function calls itself to solve a smaller
instance of the same problem until it reaches a base case, which is a condition where the
problem can be solved without further recursion.
• Base Case: The condition under which the recursion stops. It prevents infinite loops.
• Recursive Case: The part of the function where the function calls itself with a smaller or
simpler input.
Types of Recursion
• Direct Recursion: A function directly calls itself.
• Indirect Recursion: A function calls another function, which eventually leads to the first
function being called again.
• Tail Recursion: The recursive call is the last statement in the function.
• Non-Tail Recursion: The recursive call is followed by additional operations.
Applications of Recursion
• Mathematical Computations: Factorials, Fibonacci numbers.
• Data Structure Operations: Traversal in trees (e.g., Inorder, Preorder).
• Problem Solving: Divide and conquer algorithms like Merge Sort, and Backtracking
problems like the N-Queens puzzle.
Problems
1. Calculate Factorial of a Number
CODE:
int factorial(int n) {
if (n <= 1) return 1; // Base case: factorial of 0 or 1 is 1
return n * factorial(n - 1); // Recursive case: n * (n-1)!
}
Explanation: This function multiplies the number n by the factorial of n-1, continuing
until n is 1 or 0, which stops the recursion.
1. Solve a Tower of Hanoi Problem
CODE:
void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) {
if (n == 1) {
cout << "Move disk 1 from " << from_rod << " to " << to_rod << endl;
return;
}
towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
cout << "Move disk " << n << " from " << from_rod << " to " << to_rod << endl;
towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);
}
Explanation: The function recursively moves n-1 disks from the source rod to the auxiliary
rod, moves the nth disk to the destination rod, and finally moves the n-1 disks from the
auxiliary rod to the destination rod.
CONCLUSION
Summary of Key Concepts
Throughout this report, we explored of programming using c++ like arrays, function,
recursion , inheritance , polymorphism . These structures are essential for efficiently storing,
organizing, and managing data in programming. We also discussed various operations and
problem-solving techniques associated with each data structure.
The Conclusion section of your report serves as the final summary and reflection on the
topics covered. It aims to encapsulate the key findings and insights gained from the report,
providing a clear wrap-up for readers. Here’s what it typically includes:
Final Thoughts
- Evaluation : Reflect on the overall learning experience, discussing how the study of C++
contributes to programming proficiency and understanding.
- Applications : Consider the practical relevance of C++ in various fields and how the
concepts learned can be applied to real-world problems.
Recommendations
- Further Learning : Suggest areas for continued exploration or advanced topics that readers
might pursue to deepen their understanding of C++.
- Best Practices : Offer any concluding advice or best practices for writing effective C++
code based on the findings of the report.
.
REFERENCES
Books:
• "Beginning C++ Through Game Programming" by Michael Dawson
• "The Design and Evolution of C++" by Bjarne Stroustrup
Online Resources:
• GeeksforGeeks ([Link])
• LeetCode ([Link])
• Coursera programming using c++ courses
Course Material:
• Lecture notes and assignments from the summer training course on "Programming using
C++"