Lecture-02-Basic Elements of C++
Lecture-02-Basic Elements of C++
Using
March-2025
Chapter II
Basic Elements of C++
2
Chapter Contents
3
Introduction to C++
Programming Language
C++ is a general-purpose programming language that was developed as an
enhancement of the C language to include object-oriented paradigm.
It is an imperative and a compiled language.
Here are some key points to keep in mind while working with C++:
Object-Oriented Programming: C++ is an object-oriented programming
language, which means that it allows you to define classes and objects to
model real-world entities and their behavior.
Strong Type System: C++ has a strong type system, which means that
variables have a specific type and that type must be respected in all
operations performed on that variable.
Low-level Access: C++ provides low-level access to system resources,
which makes it a suitable choice for system programming and writing
efficient code.
Standard Template Library (STL): The STL provides a large set of pre-
written algorithms and data structures that can be used to simplify your code
and make it more efficient.
4
Cont…
Cross-platform Compatibility: C++ can be compiled and run
on multiple platforms, including Windows, MacOS, and Linux,
making it a versatile language for developing cross-platform
applications.
Performance: C++ is a compiled language, which means that
code is transformed into machine code before it is executed.
This can result in faster execution times and improved
performance compared to interpreted languages like Python.
Memory Management: C++ requires manual memory
management, which can lead to errors if not done correctly.
However, this also provides more control over the program’s
memory usage and can result in more efficient memory usage.
Syntax: C++ has a complex syntax that can be difficult to
learn, especially for beginners. However, with practice and
experience, it becomes easier to understand and work with. 5
Applications of C++:
C++ finds varied usage in applications such as:
Operating Systems & Systems Programming. e.g. Linux-based OS
(Ubuntu etc.)
Browsers (Chrome & Firefox)
Cloud/Distributed Systems
6
Advantages of C++:
Performance: C++ is a compiled language, which means that
its code is compiled into machine-readable code, making it one
of the fastest programming languages.
Object-Oriented Programming: C++ supports object-
oriented programming, which makes it easier to write and
maintain large, complex applications.
Standard Template Library (STL): The STL provides a wide
range of algorithms and data structures for working with data,
making it easier to write efficient and effective code.
Machine Independent: C++ is not tied to any hardware or
processor. If the compiler compiles the program in the system,
it will be able to run no matter what the hardware is.
Large Community: C++ has a large, active community of
developers and users, providing a wealth of resources and
support for learning and using the language. 7
Disadvantages of C++:
Steep Learning Curve: C++ can be challenging to learn,
especially for beginners, due to its complexity and the number
of concepts that need to be understood.
8
Some Interesting Facts about
C++:
The name of C++ signifies the evolutionary nature of the
changes from C. “++” is the C increment operator.
C++ is one of the predominant languages for the development
of all kind of technical and commercial software.
C++ introduces Object-Oriented Programming, not present in
C. Like other things, C++ supports the four primary features of
OOP: encapsulation, polymorphism, abstraction, and
inheritance.
C++ got the OOP features from Simula67 Programming
language.
10
Cont…
Let us understand every line and terminologies of the above
program.
1. // C++ program to display “Hello World”
This line is a comment line. A comment is used to display
additional information about the program. A comment does
not contain any programming logic. When a comment is
encountered by a compiler, the compiler simply skips that line
of code.
2. #include <iostream>
The #include is a preprocessor directive tells the compiler to
include the content of a file in the source code. For
example, #include<iostream> tells the compiler to include
the input-output library which contains all C++’s input/output
library functions.
11
Cont…
3. using namespace std
This is used to import the entity of the std namespace into the
current namespace of the program. It is basically the space
where all the inbuilt features of C++ are declared. For example,
std::cout.
4. int main() { }
The main() function is the entry point of every C++ program,
no matter where the function is located in the program. The
opening braces ‘{‘ indicates the beginning of the main function
and the closing braces ‘}’ indicates the ending of the main
function. 12
Cont…
5. cout<<“Hello World”;
The cout is a tool (object) that is used to display output on the
console screen. Everything followed by the character << in
double quotes ” ” is displayed on the output screen. The semi-
colon character at the end of the statement is used to
indicate that the statement is ending there.
6. return 0
This statement is used to return a value from a function and
indicates the finishing of a function. Here, it is used to sent the
signal of successful execution of the main function.
13
In C++ there are two types
of comments
Single Line Comment
Multi-Line Comment
14
Example
15
Why are Comments used in
C++?
Comments in C++ are used to summarize an algorithm,
identify a variable’s purpose, or clarify a code segment that
appears unclear. Comments are also used for:
17
Cont…
When you compile and execute this program, the following
four lines are displayed on the screen.
My first C++ program.
The sum of 2 and 3 = 5
7 + 8 = 15
Num = 6
These lines are displayed by the execution of the following four
statements.
cout << "My first C++ program." << endl;
cout << "The sum of 2 and 3 = " << 5 << endl;
cout << "7 + 8 = " << 7 + 8 << endl;
cout << "Num = " << num << endl; 18
Cont…
Let us consider the following statements:
For example, "My first C++ program." and "7 + 8 = " are
strings.
19
Cont…
Let us consider the following statement.
cout << "The sum of 2 and 3 = " << 5 << endl;
This output statement consists of two expressions.
The first expression (after the first <<) is “The sum of 2 and 3 =
” and the second expression (after the second <<) consists of
the number 5.
The expression "The sum of 2 and 3 = " is a string and evaluates
to itself.
The second expression, which consists of the number 5
evaluates to 5. Thus, the output of the preceding statement is:
The sum of 2 and 3 = 5
20
Keywords, Identifiers &
Operators
21
Keywords
Keywords are the reserved words that have special
meanings in the C++ language. They are the words that the
language uses for a specifying the components of the language,
such as void, int, public, etc. They can’t be used for a variable
name or function name or any other identifiers.
22
C++ Keywords
alignas
alignof and and_eq asm
27
Cont….
Output
The sum is: 12
28
Identifier Naming Conventions
Naming Conventions are not the rules enforced by C++
language but are suggestions for naming variables by the
programming community for easier understanding. Some of the
naming conventions are as follows:
For Variables:
Use camelCase.
For Classes:
Use PascalCase
30
Keywords vs Identifiers
Keywords Identifiers
Identifiers are the values used to
define different programming items
Keywords are predefined/reserved like a variable, integers, structures,
words and unions.
It defines the type of entity. It classifies the name of the entity.
an identifier can consist of
A keyword contains only alphabetical alphabetical characters, digits, and
characters, underscores.
It should be lowercase. It can be both upper and lowercase.
No special symbols or punctuations
are used in keywords and
No special symbols or punctuations identifiers. The only underscore can
are used in keywords and identifiers. be used in an identifier.
Example: Geeks_for_Geeks, GFG,
Example: int, char, while, do. Gfg1. 31
Operators in C++
In C++, an operator is a symbol that operates on a value to
perform specific mathematical or logical computations on given
values. They are the foundation of any programming language.
Table of Content
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Output
a + b = 11
a - b = 5
a * b = 24
a / b = 2
a % b = 2
++a = 9
--b = 2
34
Important Points: on
Arithmetic Operators
The Modulo operator (%) operator should only be used with
integers. Other operators can also be used with floating point
values.
++a and a++, both are increment operators, however, both
are slightly different. In ++a, the value of the variable is
incremented first and then It is used in the program. In a++,
the value of the variable is assigned first and then It is
incremented. Similarly happens for the decrement operator.
You may have noticed that some operator works on two
operands while other work on one. On the basis of this
operators are also classified as:
Unary: Works on single operand.
Binary: Works on two operands.
Ternary: Works on three operands.
35
2. Relational Operators
Relational operators are used for the comparison of the
values of two operands. For example, ‘>’ check right operand
is greater.
Name Symbol Description
Is Equal To == Checks both operands are equal
Checks first operand is greater than
Greater Than > the second operand
Greater Than Checks first operand is greater than
or Equal To >= equal to the second operand
Checks first operand is lesser than the
Less Than < second operand
Less Than or Checks first operand is lesser than
Equal To <= equal to the second operand
Not Equal To != Checks both operands are not equal 36
Example: Relational Operators
Output
a == b is 0
a > b is 1
a >= b is 1
a < b is 0
a <= b is 0
a != b is 1
Note: 0 denotes false
and 1 denotes true.
37
3. Logical Operators
Logical operators are used to combine two or more conditions
or constraints or to complement the evaluation of the original
condition in consideration. The result returns a Boolean value,
i.e., true or false.
39
4. Bitwise Operators
Bitwise Operations: are works on bit-level. So, compiler first
converted to bit-level and then the calculation is performed on
the operands.
Name Symbol Description
Copies a bit to the evaluated result if it
Binary AND & exists in both operands
Copies a bit to the evaluated result if it
Binary OR | exists in any of the operand
Copies the bit to the evaluated result if
it is present in either of the operands
Binary XOR ^ but not both
Shifts the value to left by the number
Left Shift << of bits specified by the right operand.
Shifts the value to right by the number
Right Shift >> of bits specified by the right operand.
40
One’s Complement ~ Changes binary digits 1 to 0 and 0 to 1
Example:
Note: Only char and int data types can be used with Bitwise
Operators.
Output
a & b is 4
a | b is 6
a ^ b is 2
a<<1 is 12
a>>1 is 3
~(a) is -7
41
5. Assignment Operators
Assignment Operators: are used to assign value to a variable.
We assign the value of right operand into left operand
according to which assignment operator we use.
42
Cont…
Name Symbol Description
Assigns the value on the right to the
Assignment = variable on the left.
First add right operand value into left
operand then assign that value into left
Add and Assignment += operand.
First subtract right operand value into
Subtract and left operand then assign that value into
Assignment -= left operand.
First multiply right operand value into
Multiply and left operand then assign that value into
Assignment *= left operand.
First divide right operand value into left
Divide and operand then assign that value into left
43
Assignment /= operand.
Example
Output
a = 6
a += b is 10
a -= b is 6
a *= b is 24
a /= b is 6
44
6. Ternary or Conditional
Operators
Ternary or conditional operator returns the value, based
on the condition.
Expression1 ? Expression2 : Expression3
The ternary operator ? determines the answer on the basis of
the evaluation of Expression1. If it is true,
then Expression2 gets evaluated and is used as the answer
for the expression. If Expression1 is false,
then Expression3 gets evaluated and is used as the answer
for the expression.
46
Miscellaneous Operators
1. sizeof Operator
sizeof operator is a unary operator used to compute the size
of its operand or variable in bytes. For example,
sizeof (char);
sizeof (var_name);
2. Comma Operator (,)
Comma operator is a binary operator that is used for
multiple purposes. It is used as a separator or used to evaluate
its first operand and discards the result; it then evaluates the
second operand and returns this value (and type).
int n = (m+1, m-2, m+5);
int a, b, c; 47
Cont…
3. Arrow Operator
Arrow operator is used to access the variables of classes or
structures through its pointer.
sptr -> member;
4. Casting Operators
Casting operators are used to convert the value of one data
type to another data type. For example, for an integer value x:
(float)x
static_cast<float>(x)
48
Cont…
5. Dot Operator(.)
Dot operator is used to access members of structure
variables or class objects using their object names.
obj . member;
50
C++ Variables
In C++, variable is a name given to a memory location. It is
the basic unit of storage in a program. The value stored in a
variable can be accessed or changed during program execution.
Creating a Variable
Giving it a name is called variable definition (sometimes
called variable declaration). The syntax of variable
definition is: type name;
where, type is the type of data that a variable can store,
and name is the name assigned to the variable. Multiple
variables of the same type can be defined as:
type name1, name2, name3 ....; The data type of a variable is
selected from the list of data types supported by C++. 51
Cont…
Example:
• To store number without decimal point, we use integer data
type.
int num;
• Here, int is the keyword used to tell the compiler that the
variable with name num will store integer values. The C++
Course covers the types of variables in C++ and how to use
them effectively in your programs.
52
Initializing a Variable
A variable that is just defined may not contain some valid
value. We have to initialize it to some valid initial value. It is
done by using an assignment operator = as shown: type
name;
name = value;
Definition and initialization can also be done in a single step as
shown: type name = value;
where the value should be of the same type as variable.
Example:
int num = 100; The integer variable num is initialized with the
value 100. Values are generally the literals of the same type. 53
Accessing a Variable
Output
a
54
Updating a Variable
55
Rules For Naming Variable
The names given to a variable are called identifiers. There are
some rules for creating these identifiers (names):
57
Cont…
Addition of two integers can be done in C++ using +
operator as shown:
Output
30
We can do the above operation using the variables that store
these two values.
Output
30
58
Constant Variables
In C++, a constant variable is one whose value cannot be
changed after it is initialized. This is done using
the const keyword.
59
Scope of Variables
Scope of Variable is the region inside the program where the
variable can be referred to by using its name. Basically, it is the
part of the program where the variable exists. Proper
understanding of this concept requires the understanding of
other concepts such as functions, blocks, etc.
61
C++ Data Types
Data types specify the type of data that a variable can store.
Whenever a variable is defined in C++, the compiler allocates
some memory for that variable based on the data type with
which it is declared as every data type requires a different
amount of memory.
62
Cont…
Output
10
Explanation: In the above code, we needed to store the value 10 in our program,
so we created a variable var. But before var, we have used the keyword ‘int‘. This
keyword is used to define the data types of integers.
63
Cont…
In C++, data types are classified into the following types:
S. No. Type Description Data Types
Syntax:
char name;
where name is the identifier assigned to the variable.
65
Cont…
Example
Output
A
66
Cont…
2. Integer Data Type (int)
Integer data type denotes that the given variable can store
the integer numbers. The keyword used to define integers
is int. Its size is 4-bytes (for 64-bit) systems and can store
numbers for binary, octal, decimal and hexadecimal base
systems in the range from -2,147,483,648 to
2,147,483,647.
Syntax
int name;
where, name is the identifier assigned to the variable.
67
Cont…
Example Output
25
21
68
Cont…
3. Boolean Data Type (bool)
The boolean data type is used to store logical
values: true(1) or false(0). The keyword used to define a
boolean variable is bool. Its size is 1 byte.
Syntax
bool name;
where name is the identifier assigned to the variable.
69
Cont…
Example
Output
1
70
Cont…
4. Floating Point Data Type (float)
Floating-point data type is used to store numbers with
decimal points. The keyword used to define floating-point
numbers is float. Its size is 4 bytes (on 64-bit systems) and
can store values in the range from 1.2E-38 to 3.4e+38.
Syntax
float name;
where, name is the identifier assigned to the variable.
71
Cont…
Example Output
36.5
72
Cont…
5. Double Data Type (double)
The double data type is used to store decimal numbers with
higher precision. The keyword used to define double-precision
floating-point numbers is double. Its size is 8 bytes (on 64-bit
systems) and can store the values in the range from 1.7e-308
to 1.7e+308
Syntax
double name;
where, name is the identifier assigned to the variable.
73
Cont…
Example
Output
3.14159
74
Cont…
6. Void Data Type (void)
The void data type represents the absence of value. We
cannot create a variable of void type. It is used for pointer and
functions that do not return any value using the keyword void.
Syntax
void functionName();
75
Cont…
Example
Output
Hello, World!
76
Size of Data Types in C++
We can find the size of the data type using sizeof operator.
77
Cont…
Example Output
Size of int: 4 bytes
Size of char: 1 byte
Size of float: 4 bytes
Size of double: 8 bytes
78
Data Type Modifiers
80
Cont…
Statements: In C++, a statement controls the sequence of
execution, evaluates an expression, or does nothing (the null
statement). All C++ statements end with a semicolon.
81
82