unit 1 C++ NOTES
unit 1 C++ NOTES
C++ history
C++ programming language was developed in 1980 by Bjarne Stroustrup
at bell laboratories of AT&T (American Telephone & Telegraph), located in
U.S.A.
Bjarne Stroustrup is known as the founder of C++ language.
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.
3) Portable
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
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.
The list of arguments of every function call is typed checked during compilation. If
there is a type mismatch between actual and formal arguments, implicit conversion
is applied if possible. A compile-time occurs if an implicit conversion is not
possible or if the number of arguments is incorrect.
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.
The programs written in C++ are well suited for real-world modeling problems as
close as possible to the user perspective.
21) Clarity
The keywords and library functions used in C++ resemble common English words.
C++ is multi-
C follows
paradigm. It supports
1) the procedural style
both procedural and
programming.
object oriented.
In C++, you can use
modifiers for class
Data is less secured in
2) members to make it
C.
inaccessible for
outside users.
C++ follows
C follows the top-
3) the bottom-up
down approach.
approach.
C programs are
C++ programs are
divided
9) divided into functions
into procedures and
and classes.
modules
C does not provide the C++ supports the
10)
feature of namespace. feature of namespace.
#include <iostream>
int main() {
int x = 10;
float y = 3.14;
return 0;
2.Keywords:
Keywords are reserved words in C++ that have a special meaning and cannot be
used as identifiers (e.g., variable names).
Examples include:
int, char, float, double, if, else, for, while, return, switch, etc.
3.Identifiers:
Example:
int main() {
int age = 25; // 'age' is an identifier
char grade = 'A'; // 'grade' is an identifier
}
#include <iostream>
using namespace std;
int main() {
int if = 10; // Error: 'if' is a keyword
cout << if << endl;
return 0;
}
Variables and Constants
Variables:
A variable is a named memory location used to store data that can change during
program execution.
Syntax:
data_type variable_name;
Example:
#include <iostream>
using namespace std;
int main() {
int number = 10;
char letter = 'A';
float price = 19.99;
cout << "Number: " << number << ", Letter: " << letter << ", Price: " << price
<< endl;
return 0;
}
Constants:
Constants are values that do not change during program execution. They are
defined using the const keyword. Example:
#include <iostream>
using namespace std;
int main() {
const int MAX_SIZE = 100;
cout << "Maximum size is: " << MAX_SIZE << endl;
// MAX_SIZE = 200; // Error: cannot modify a constant
return 0;
}
Data Types
A data type specifies the type of data that a variable can store such as integer,
floating, character etc.
#include <iostream>
int main() {
int integerVar = 5;
cout << "Integer: " << integerVar << ", Float: " << floatVar
<< ", Double: " << doubleVar << ", Char: " << charVar
return 0;
#include <iostream>
using namespace std;
int main() {
int arr[5] = {1, 2, 3, 4, 5};
cout << "Array elements: ";
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
cout << endl;
char str[] = "Hello";
cout << "String: " << str << endl;
return 0;
}
User-Defined Data Types:
#include <iostream>
struct Person {
string name;
int age;
};
int main() {
cout << "Name: " << p1.name << ", Age: " << p1.age << endl;
return 0;
Unions: A data structure that can store different data types in the same memory
location. Example:
union Data {
int i;
float f;
};
Enumerations: A user-defined data type consisting of a set of named integral
constants. Example:
Operators
Operators in C++ are symbols that perform operations on variables and values.
Some common operators:
Arithmetic Operators: +, -, *, /, %.
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 5;
cout << "Sum: " << (a + b) << endl;
cout << "Difference: " << (a - b) << endl;
cout << "Product: " << (a * b) << endl;
cout << "Division: " << (a / b) << endl;
cout << "Modulus: " << (a % b) << endl;
return 0;
}
#include <iostream>
int main() {
int a = 10, b = 5;
return 0;
#include <iostream>
int main() {
return 0;
#include <iostream>
int a = 5;
a += 3; // a = a + 3
a *= 2; // a = a * 2
return 0;
int a = 5;
int b = a++; // b = 5, a = 6 after
int a = 5;
int b = ++a; // b = 6, a = 6 after
int a = 5;
int b = a--; // b = 5, a = 4 after
o Prefix (--variable): Decrements the value first, then uses it.
int a = 5;
int b = --a; // b = 4, a = 4 after
Syntax:
Example:
int a = 5, b = 10;
int max = (a > b) ? a : b; // If a > b, max = a; else max = b
// Result: max = 10
In this example:
#include <iostream>
int main() {
int a = 5;
float b = 2.5;
return 0;
float f = 9.7;
cout << "Converted value: " << i << endl; // Output will be 9
return 0;
Examples:
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num; // Taking input from user
cout << "You entered: " << num << endl; // Displaying output
return 0;
}
Control Statements
if (condition) {
// code to execute if condition is true
}
Ex-
#include <iostream>
using namespace std;
int main() {
int a = 10;
if (a > 5) {
cout << "a is greater than 5" << endl;
}
return 0;
}
if-else Statement:
if-else statement: Executes one block of code if the condition is true and another
block if the condition is false.
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
#include <iostream>
using namespace std;
int main() {
int a = 3;
if (a > 5) {
cout << "a is greater than 5" << endl;
} else {
cout << "a is less than or equal to 5" << endl;
}
return 0;
}
else if Ladder:
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition2 is true
} else {
// code to execute if none of the conditions are true
}
#include <iostream>
using namespace std;
int main() {
int a = 7;
if (a > 10) {
cout << "a is greater than 10" << endl;
} else if (a == 7) {
cout << "a is 7" << endl;
} else {
cout << "a is less than 7" << endl;
}
return 0;
}
switch Statement:
Used to execute one of many blocks of code based on the value of an expression.
switch (expression) {
case value1:
// code for value1
break;
case value2:
// code for value2
break;
default:
// code if no match
}
#include <iostream>
using namespace std;
int main() {
int day = 3;
switch (day) {
case 1: cout << "Monday"; break;
case 2: cout << "Tuesday"; break;
case 3: cout << "Wednesday"; break;
case 4: cout << "Thursday"; break;
default: cout << "Invalid day"; break;
}
return 0;
}
Loops:
Loops are used to repeat a block of code multiple times. There are different types
of loops in programming, each with its own use case.
1. for,
2. while,
3. do-while
for Loop:
int main() {
for (int i = 1; i <= 5; i++) {
cout << "i = " << i << endl;
}
return 0;
}
while Loop:
Used when the number of iterations is unknown and the loop runs while a
condition is true.
int i = 0;
while (i < 5) {
// code to execute
i++;
}
Ex-#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 5) {
cout << "i = " << i << endl;
i++;
}
return 0;
}
do-while Loop:
int i = 0;
do {
// code to execute
i++;
} while (i < 5);
Ex-
#include <iostream>
using namespace std;
int main() {
int i = 1;
do {
cout << "i = " << i << endl;
i++;
} while (i <= 5);
return 0;
}
break and continue:
Ex-
#include <iostream>
int main() {
if (i == 3) {
if (i == 3) {
return 0;
goto Statement:
Used to jump to a specific label in the program (not recommended for structured
programming).
goto label;
label:
// code to execute
Ex- #include <iostream>
using namespace std;
int main() {
int i = 0;
end: // Label
cout << "Loop ended!" << endl;
return 0;
}
Simple Functions:
Declaration: Defines the function signature. Example:
int main() {
int result = add(5, 10); // Calling the function
cout << "Sum: " << result << endl;
return 0;
}
Passing Arguments:
How It Works:
When you pass a variable to a function by value, the function gets a copy of
the variable's value.
Changes made to the parameter inside the function will not affect the
original variable.
When you want the function to work with a copy of the data.
When you don’t need to modify the original variable or when the data being
passed is small (like an integer or a float).
Drawback:
If the data passed is large (e.g., large arrays or objects), copying the data can
be inefficient, so passing by reference might be preferred in such cases.
Syntax:
Example 1.
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 10;
cout << "Before Swap: a = " << a << ", b = " << b << endl;
cout << "After Swap (Outside function): a = " << a << ", b = " << b << endl;
return 0;
}
Example 2:
#include <iostream>
void updateValue(int x) {
x = 10;
int main() {
int a = 5;
updateValue(a);
cout << "Value of a: " << a << endl; // a will remain 5 (no change)
return 0;
Pass by Reference:
In Pass by Reference, the actual memory address of the variable is passed to the
function, allowing the function to directly modify the original variable. This means
that any changes made to the parameter inside the function will affect the original
variable outside the function.
How It Works:
When you pass a variable by reference, you're passing the memory address
(or reference) of the variable, not its value.
Any modifications inside the function will directly affect the original
variable because the function operates on the variable's address.
Syntax:
You can pass a parameter by reference using the & symbol in the function
declaration.
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 10;
cout << "Before Swap: a = " << a << ", b = " << b << endl;
cout << "After Swap: a = " << a << ", b = " << b << endl;
return 0;
}
Example2 :
#include <iostream>
int main() {
int a = 5;
updateValue(a);
return 0;
Return Statement:
When you declare a function as inline, the compiler attempts to replace the
function call with the actual code of the function at the point of the call. This can
reduce the function call overhead (e.g., saving the stack, jumping to another part of
the program), but it can also increase the size of the code if overused.
Example:
#include <iostream>
return x * x;
int main() {
int result = square(5); // Function call is replaced with the body of the
function
return 0;
1. Faster Execution:
o Since there's no overhead of function calls, inline functions can
execute faster, especially for small, frequently called functions.
2. Reduced Function Call Overhead:
o The compiler directly replaces the function call with the function
body, reducing the cost of setting up a function call (like saving the
return address, pushing arguments to the stack, etc.).
3. Efficiency for Small Functions:
o Inline functions are ideal for small functions that are called frequently,
such as accessor functions or simple mathematical operations.
1. Code Size:
o If an inline function is large or used extensively, it can increase the
size of the binary because the function code is inserted at every call
site. This could actually hurt performance due to code bloat.
2. Compiler's Discretion:
oThe inline keyword is a suggestion to the compiler, not a command.
The compiler can choose not to inline a function if it's too complex or
if inlining it doesn't provide a performance benefit.
3. Limited to Small Functions:
o Inline functions are only effective for small functions. Large functions
should not be inlined as they will increase the code size and reduce
performance.
Default Arguments:
#include <iostream>
void printValue(int x = 5) {
}
int main() {
return 0;
struct Point {
int x;
int y;
};
Point createPoint() {
Point p = {1, 2};
return p;
}
#include <iostream>
using namespace std;
struct Point {
int x, y;
};
Point createPoint() {
Point p = {1, 2};
return p;
}
int main() {
Point p1 = createPoint();
cout << "Point coordinates: (" << p1.x << ", " << p1.y << ")" << endl;
return 0;
}
Pointers in C++
A pointer is a variable that stores the memory address of another variable. Rather
than storing data directly, a pointer stores the location of where the data is kept.
Pointers are powerful tools in C++ for directly managing memory and interacting
with dynamically allocated memory, among other tasks.
Basic Concepts:
Pointer Syntax:
type: The type of data the pointer will point to (e.g., int, float, etc.)
*: Indicates that the variable is a pointer.
pointer_name: The name of the pointer variable.
#include <iostream>
using namespace std;
int main() {
int a = 10; // A normal integer variable
int *ptr = &a; // Pointer 'ptr' stores the address of 'a'
cout << "Value of a: " << a << endl; // Output: 10
cout << "Address of a: " << &a << endl; // Output: Memory address of 'a'
cout << "Pointer ptr points to address: " << ptr << endl; // Output: Same address
as &a
cout << "Value stored at the address ptr points to: " << *ptr << endl; // Output:
10
return 0;
}
Pointer Operations:
int a = 5;
int *ptr = &a; // 'ptr' now holds the address of 'a'
int a = 5;
int *ptr = &a;
cout << *ptr; // Output: 5
In C++, arrays and pointers are closely related. An array name is a pointer to the
first element of the array.
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr; // Pointer points to the first element of the array
return 0;
}
Explanation:
Pointer to Pointer:
A pointer can store the address of another pointer, known as a pointer to pointer.
#include <iostream>
using namespace std;
int main() {
int a = 10;
int *ptr = &a; // Pointer pointing to 'a'
int **ptr2 = &ptr; // Pointer to pointer
return 0;
}
Explanation:
ptr points to a.
ptr2 points to ptr, which points to a.
**ptr2 dereferences ptr2 (gives us ptr), and then *ptr gives us the value of a.
2. Dangling Pointer:
o A pointer that points to a memory location that has been deallocated
(i.e., freed) is a dangling pointer. Dereferencing a dangling pointer
can lead to crashes or unexpected behavior.