C++ Module 2 Notes
C++ Module 2 Notes
1. Identifiers
In C++, entities like variables, functions, classes, or structs must be given
unique names within the program so that they can be uniquely identified.
The unique names given to these entities are known as identifiers.
It is recommended to choose valid and relevant names of identifiers to
write readable and maintainable programs. Keywords cannot be used as
an identifier because they are reserved words to do specific tasks. In the
below example, “first_name’ is an identifier.
string first_name = "Raju";
2. Keywords
Keywords in C++ are the tokens that are the reserved words in
programming languages that have their specific meaning and
functionalities within a program. Keywords cannot be used as an identifier
to name any variables.
For example, a variable or function cannot be named as ‘int’ because it is
reserved for declaring integer data type.
There are 95 keywords reserved in C++. Some of the main Keywords
are:
continu
break try catch char Class const
e
Protecte publi
long new operator private return
d c
continu
break try catch char Class const
e
registe
mutable struct case Switch and or
r
namespac static_cas
goto not Xor bool do
e t
unsigne
double int void Virtual union while
d
3. Constants
Constants are the tokens in C++ that are used to define variables at the
time of initialization and the assigned value cannot be changed after that.
We can define the constants in C++ in two ways that are using the ‘const’
keyword and ‘#define’ preprocessor directive. Let’s see both methods one
by one.
1. Define Constants using the ‘const’ Keyword in C++
Constants are the values that do not change during the execution of the
program once defined. We can make constant any type of data such as
integer, float, string, and characters. A literal is a constant value assigned
to a constant variable.
Syntax
const data_type variable_name = value;
Initialize the string object with string within the double inverted commas
(“).
string variable_name = "This is string";
5. Special Symbols
Special symbols are the token characters having specific meanings within
the syntax of the programming language. These symbols are used in a
variety of functions, including ending the statements, defining control
statements, separating items, and more.
Below are the most common special symbols used in C++
programming:
· Semicolon (;): It is used to terminate the statement.
· Square brackets []: They are used to store array elements.
· Curly Braces {}: They are used to define blocks of code.
· Scope resolution (::): Scope resolution operator is used to
access members of namespaces, classes, etc.
· Dot (.): Dot operator also called member access operator used to
access class and struct members.
· Assignment operator ‘=’: This operator is used to assign values
to variables.
· Double-quote (“): It is used to enclose string literals.
· Single-quote (‘): It is used to enclose character literals.
6. Operators
C++ operators are special symbols that are used to perform operations on
operands such as variables, constants, or expressions. A wide range
of operators is available in C++ to perform a specific type of operations
which includes arithmetic operations, comparison operations, logical
operations, and more.
For example (A+B), in which ‘A’ and ‘B’ are operands, and ‘+’ is an
arithmetic operator which is used to add two operands.
Types of Operators
1. Unary Operators
2. Binary Operators
3. Ternary Operators
1. Unary Operators
Unary operators are used with single operands only. They perform the
operations on a single variable. For example, increment and decrement
operators.
· Increment operator ( ++ ): It is used to increment the value of
an operand by 1.
· Decrement operator ( — ): It is used to decrement the value of
an operand by 1.
2. Binary Operators
They are used with the two operands and they perform the operations
between the two variables. For example (A<B), less than (<) operator
compares A and B, returns true if A is less than B else returns false.
· Arithmetic Operators: These operators perform basic arithmetic
operations on operands. They include ‘+’, ‘-‘, ‘*’, ‘/’, and ‘%’
· Comparison Operators: These operators are used to compare
two operands and they include ‘==’, ‘!=’, ‘<‘, ‘>’, ‘<=’, and ‘>=’.
· Logical Operators: These operators perform logical operations
on boolean values. They include ‘&&’, ‘||’, and ‘!‘.
· Assignment Operators: These operators are used to assign
values to variables and they include ‘variables‘, ‘-=‘, ‘*=‘, ‘/=‘,
and ‘%=’.
· Bitwise Operators: These operators perform bitwise operations
on integers. They include‘&’, ‘|’, ‘^’, ‘~’, ‘<<‘, and ‘>>‘.
3. Ternary Operator
The ternary operator is the only operator that takes three operands. It is
also known as a conditional operator that is used for conditional
expressions.
Syntax:
Expression1 ? Expression2 : Expression3;
C++ Operators
Operators are symbols that perform operations on variables and values.
For example, + is an operator used for addition, while - is an operator used
for subtraction.
Operators in C++ can be classified into 6 types:
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Bitwise Operators
6. Other Operators
a + b;
Here, the + operator is used to add two variables a and b. Similarly there
are various other arithmetic operators in C++.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
int main() {
int a, b;
a = 7;
b = 2;
return 0;
}
Run Code
Output
a+b=9
a-b=5
a * b = 14
a/b=3
a%b=1
In C++,
7/2 is 3
7.0 / 2 is 3.5
7 / 2.0 is 3.5
% Modulo Operator
The modulo operator % computes the remainder. When a = 9 is divided by b
= 4, the remainder is 1.
int num = 5;
// increment operator
++num; // 6
Here, the code ++num; increases the value of num by 1.
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 100, result_a, result_b;
return 0;
}
Run Code
Output
result_a = 11
result_b = 99
// assign 5 to a
a = 5;
= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
int main() {
int a, b;
// 2 is assigned to a
a = 2;
// 7 is assigned to b
b = 7;
return 0;
}
Run Code
Output
a=2
b=7
After a += b;
a=9
int main() {
int a, b;
a = 3;
b = 5;
bool result;
return 0;
}
Run Code
Output
3 == 5 is 0
3 != 5 is 1
3 > 5 is 0
3 < 5 is 1
3 >= 5 is 0
3 <= 5 is 1
Logical AND.
&& expression1 && expression2
True only if all the operands are true.
Logical OR.
|| expression1 || expression2
True if at least one of the operands is true.
Logical NOT.
! !expression
True only if the operand is false.
Then,
int main() {
bool result;
return 0;
}
Run Code
Output
(3 != 5) && (3 < 5) is 1
(3 == 5) && (3 < 5) is 0
(3 == 5) && (3 > 5) is 0
(3 != 5) || (3 < 5) is 1
(3 != 5) || (3 > 5) is 1
(3 == 5) || (3 > 5) is 0
!(5 == 2) is 1
!(5 == 5) is 0
| Binary OR
^ Binary XOR
0 0 0
0 1 0
1 0 0
1 1 1
Note: The table above is known as the "Truth Table" for the bitwise
AND operator.
Let's take a look at the bitwise AND operation of two integers 12 and 25:
00001100
& 00011001
_________
int main() {
// declare variables
int a = 12, b = 25;
Output
a = 12
b = 25
a&b=8
In the above example, we have declared two variables a and b. Here, notice
the line,
0 0 0
0 1 1
1 0 1
1 1 1
Let us look at the bitwise OR operation of two integers 12 and 25:
00001100
| 00011001
_________
Example 2: Bitwise OR
#include <iostream>
int main() {
int a = 12, b = 25;
return 0;
}
Run Code
Output
a = 12
b = 25
a | b = 29
0 0 0
0 1 1
1 0 1
1 1 0
Let us look at the bitwise XOR operation of two integers 12 and 25:
00001100
^ 00011001
_________
int main() {
int a = 12, b = 25;
return 0;
}
Run Code
Output
a = 12
b = 25
a ^ b = 21
Bitwise Complement
It is important to note that the bitwise complement of any integer N is
equal to -(N + 1). For example,
Consider an integer 35. As per the rule, the bitwise complement
of 35 should be -(35 + 1) = -36. Now, let's see if we get the correct answer
or not.
~ 00100011
__________
11011100
As we can see from the image above, we have a 4-bit number. When we
perform a one-bit right shift operation on it, each individual bit is shifted to
the right by 1 bit.
As a result, the right-most bit is discarded, while the left-most bit remains
vacant. This vacancy is replaced by a 0.
As we can see from the image above, we have a 4-bit number. When we
perform a 1 bit left shift operation on it, each individual bit is shifted to the
left by 1 bit.
As a result, the left-most bit is discarded, while the right-most bit remains
vacant. This vacancy is replaced by a 0.
int main() {
// Using for loop for shifting num right from 0 bit to 3 bits
for (i = 0; i < 4; i++) {
cout << "212 >> " << i << " = " << (212 >> i) << endl;
}
return 0;
}
Run Code
Output
Shift Right:
212 >> 0 = 212
212 >> 1 = 106
212 >> 2 = 53
212 >> 3 = 26
Shift Left:
212 << 0 = 212
212 << 1 = 424
212 << 2 = 848
212 << 3 = 1696
For example, 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.
Output
1. #include <iostream>
2. using namespace std;
3. class Operate
4. {
5. public:
6. // declaration of the member function
7. void fun();
8. };
9. // define the member function outside the class.
10. void Operate::fun() /* return_type Class_Name::function_name */
11. {
12. cout << " It is the member function of the class. ";
13. }
14. int main ()
15. {
16. // create an object of the class Operate
17. Operate op;
18. op.fun();
19. return 0;
20. }
Output
1. #include <iostream>
2. int main ()
3. {
4. int num = 0;
5.
6. // use scope resolution operator with std namespace
7. std :: cout << " Enter the value of num: ";
8. std::cin >> num;
9. std:: cout << " The value of num is: " << num;
10. }
Output
1. #include <iostream>
2. using namespace std;
3. class Parent
4. {
5. static int n1;
6. public:
7. static int n2;
8. // The class member can be accessed using the scope resolution operator.
9. void fun1 ( int n1)
10. {
11. // n1 is accessed by the scope resolution operator (:: )
12. cout << " The value of the static integer n1: " << Parent::n1;
13. cout << " \n The value of the local variable n1: " << n1;
14. }
15. };
16. // define a static member explicitly using :: operator
17. int Parent::n1 = 5; // declare the value of the variable n1
18. int Parent::n2 = 10;
19. int main ()
20. {
21. Parent b;
22. int n1 = 15;
23. b.fun1 (n1);
24. cout << " \n The value of the Base::n2 = " << Parent::n2;
25. return 0;
26. }
Output
1. #include <iostream>
2. using namespace std;
3. class ABC
4. {
5. public:
6. // declare static member function
7. static int fun()
8. {
9. cout << " \n Use scope resolution operator to access the static member. ";
10. }
11. };
12. int main ()
13. {
14. // class_name :: function name
15. ABC :: fun ();
16. return 0;
17. }
Output
1. #include <iostream>
2. using namespace std;
3. class ABC
4. {
5. // declare access specifier
6. public:
7. void test ()
8. {
9. cout << " \n It is the test() function of the ABC class. ";
10. }
11. };
12. // derive the functionality or member function of the base class
13. class child : public ABC
14. {
15. public:
16. void test()
17. {
18. ABC::test();
19. cout << " \n It is the test() function of the child class. ";
20. }
21. };
22. int main ()
23. {
24. // create object of the derived class
25. child ch;
26. ch.test();
27. return 0;
28. }
Output
x = (2/5) * 4 (2/5) * 4
extern int y = 89 89
int z = 21 21
static int a = 60 60
int main() {
int a; // variable declaration.
a = (4 / 3) + 2; // constant expression
cout << "The value of a is: " << a; // displaying the value of a.
return 0;
}
Run Code >>
Output
The value of a is: 3
int main() {
int a; // variable declaration.
int b; // variable declaration
int c; // variable declaration
a=8;
b=9;
c = a + b;
cout << "\nValue of c is: " << c; // displaying the value of c.
return 0;
}
Run Code >>
Output
Value of c is:17
#include <iostream>
using namespace std;
int main() {
float a = 8.9; // variable initialization
float b = 5.6; // variable initialization
float c; // variable declaration
c = a + b;
cout << "The value of c is: " << c << endl; // displaying the value of c.
return 0;
}
Run Code >>
Output
The value of c is:14.5
#include <iostream>
using namespace std;
int main() {
int X[] = {1, 2, 3, 4, 5}; // array initialization
int *ptr; // pointer declaration
ptr = X; // assigning the base address of the array to the pointer ptr
ptr = ptr + 1; // incrementing the value of the pointer
cout << "Value of the second element of an array: " << *ptr << endl;
return 0;
}
Run Code >>
Output
value of the second element of an array: 2
#include <iostream>
using namespace std;
int main() {
int X = 45; // variable declaration
int Y = 78; // variable declaration
bool Z = X > Y; // relational expression
cout << "The value of Z is: " << Z << endl; // displaying the value of Z.
return 0;
}
Run Code >>
Output
The value of Z is : 0
int main()
{
int x = 2;
int y = 7;
int z = 4;
return 0;
}
Output
0
7.) Bitwise Expression in C++
Bitwise expressions are used to manipulate data at a bit level for shifting it to
bits.
#include <iostream>
using namespace std;
int main()
{
int A = 5; // variable declaration
cout << (A >> 1) << endl;
return 0;
}
Run Code >>
Output
2
Example-1
#include <iostream>
using namespace std;
int main()
{
int x; // variable declaration
int y; // variable declaration
x = y = 80; // chained assignment
cout << "Values of 'x' and 'y' are: " << x << "," << y << endl;
return 0;
}
Run Code >>
Output
Values of 'x' and 'y' are : 80,80
· Embedded assignment expressions- In this embedded assignment
expression one expression is enclosed within another assignment
expressions
Example-2
#include <iostream>
using namespace std;
int main()
{
int x; // variable declaration
int y; // variable declaration
x = 10 + (y = 90); // embedded assignment expression
cout << "Value of 'x' is " << x << endl;
return 0;
}
Run Code >>
Output
Values of 'x' is 100
int main()
{
int x = 10; // variable declaration
x += 10; // compound assignment
cout << "The value of x is: " << x << endl; // displaying the value of x.
return 0;
}
Run Code >>
Output
The value of x is: 20