Chapter 2 - Begins With C++ & Tokens, Expression and Ctrl. Structure
Chapter 2 - Begins With C++ & Tokens, Expression and Ctrl. Structure
Prepared by
Md. Masum Billah
Lecturer, Dept. of CSE, CBSTMobile:
01793200796
Q. What is C++.
C++ supports the object-oriented programming, the four major pillar of object-oriented
programming(OOPs) used in C++ are:
Inheritance
Polymorphism
Encapsulation
Abstraction
#include <iostream.h>
class Human{
int age=25;
char name[20]=”Rubel”;
public:
void display()
{
cout <<”Age is: ”<<age <<” Name is: ”<< name<< endl;
}
};
int main() {
return 0;
#include<iostream.h> includes the standard input output library functions. It provides cin and cout
methods for reading from input and writing to output respectively.
using namespace std - It is a directive that allows the programmer to use all the names defined in
thestd namespace without having to prefix them with std:: . The std namespace is the namespace that
contains all the standard library functions, classes, and objects in C++.
int main() - The main function is the entry point of every program in C++ language. The void
keyword specifies that it returns no value.
return 0 – this return value 0 to the operating system to signal the program has completed
successfully.
Q. What is Token in C++?
Token is the smallest element of a program that is meaningful to the compiler. Compiler reads the
program’s source code and divides it into a sequence of tokens. Which are then processed and
compiled into an executable program. Tokens canbe keywords, identifiers, operators, literals,
punctuators, or special symbols.
Punctuators: ; , {, }, (, ), [, ], ,, ., ->
Tokens are the building blocks of C++ programs, and the compiler uses them to parse the code and
generate the corresponding machine code.
1. Keyword: Keywords are reserved words that have a specific meaning and purpose in the
language.These keywords cannot be used as identifiers (such as variable or function names)
because they have a predefined meaning in the language. Here are some C++ keywords below:
asm, double, new, switch, auto, else, operator, template, break, enum, private, this, case, extern,
protected, throw, catch, float, public, try, char, for, typedef, class, return, union, const, short etc
Rules of Identifiers:
1. Only first 31 characters are significant.
2. First character must be a letter or underscore. Not Digits.
3. Must consist of letters, digits or underscore.
4. Cant’ use keywords.
5. Must not contain space.
3. Constants: A constant is a value that cannot be changed during program execution. Constants
canbe used to represent fixed values that are used throughout a program, such as pi (π)=3.1416.
constant can be various types like int, float, char, string.
Symbolic constants, also known as "named constants," are identifiers that represent a constant
value,and their value is determined at compile time. Symbolic constants are defined using the
const keyword or the preprocessor directive #define.
4. Operators: Operators are symbols or keywords that perform specific operations on one or
moreoperands, which are variables or values. C++ provides several types of operators, including
arithmetic, assignment, comparison, logical, bitwise, and conditional operators. Here's a brief
overview of each type:
Arithmetic operators.
Assignment operators.
Comparison operators.
Logical operators.
Bitwise operators.
Conditional operator.
Primitive Data Types: These data types are built-in or predefined data types and can be used
directlyby the user to declare variables. example: int, char, float, bool, etc. Primitive data types
available in C++ are:
1. Integer
2. Character
3. Boolean
4. Floating Point
5. Double Floating Point
6. Valueless or Void
7. Wide Character
Derived Data Types: Derived data types that are derived from the primitive or built-in datatypes
arereferred to as Derived Data Types. These can be of four types namely:
1. Function
2. Array
3. Pointer
4. Reference
(Functions, arrays, pointers, and references are called derived data types because they are constructed
using primitive data types and provide higher-level abstractions for organizing, accessing, and
manipulating data in programming languages.)
Abstract or User-Defined Data Types: Abstract or User-Defined data types are defined by the user
itself. Like, defining a class in C++ or a structure. C++ provides the following user-defined datatypes:
1. class
2. structure
3. union
4. enum
5. Typedef
Q. What is type modifier?
We can further modify some of the fundamental data types by using type modifiers. There are 4
typemodifiers in C++. They are:
1. signed
2. unsigned
3. short
4. long
We can modify the following data types with the above modifiers:
int
double // only support “long” modifier
char
Example: signed int , unsigned int, long int, short int, signed char, unsigned char, long double
Type Modifiers are special keywords defined in the programming language which are used to
modifythe default properties of the Built-in Data types. Type Modifiers are special keywords that
are used to modify the range of the data types and also the memory space allocated to the
variable.
C++ doesn’t support void as variable type. Rather void data type can be used in some specific fact-
void function()
{
}
void *p; //This generic pointer can hold address of any basic data type variable.
int a;
p=&a;
Q. Can we assign a void pointer to an int type pointer? If not, why? How can we
achieve this?
No, we cannot directly assign a void pointer to an int pointer in C++. This is because a void pointer
represents a generic pointer type that can be used to hold the address of any data type, but it lacks
typeinformation. On the other hand, C++ allows pointer assignments between same data types.
To achieve this, we need to use a type cast operator, to convert the void pointer to an int
pointer.Here's an example:
int a;
void *void_p=&a;
int *int_p; int_p=(int*)
void_p;
Here, the name of the enumeration is season. And, spring, summer and winter are values of
typeseason.
By default, spring is 0, summer is 1 and so on. We can change the default value of an enum
elementduring declaration (if necessary). Example-
enum season
{ spring = 0, summer
= 4,
autumn = 8, winter
= 12
};
Q. How does a constant defined by const differ from the constant defined by the
preprocessor #define?
1. CONSTs are handled by the compiler, whereas #DEFINEs are handled by the pre-processor.
2. The big advantage of const over #define is type checking. #defines can’t be type checked,
so this can cause problems when trying to determine the data type. If the variable is, a
constantthen we can grab the type of the data that is stored in that constant variable. Since
const are considered variables, we can use pointers on them. This means we can typecast,
move addresses, and everything else you’d be able to do with a regular variable besides
change the data itself, since the data assigned to that variable is constant.
3. #define should not be enclosed with a semicolon (;) but const should be enclosed with
asemicolon (;).
In general, const is a better option if we have a choice and it can successfully apply to the code.
Q. What is the application of scope resolution operator (::) C++?
Applications:
It is used to access the global variable which is same as local variable name.
It defines the member function outside of the class using the scope resolution.
It is used to access the static variable and static function of a class.
The scope resolution operator is used to override function in the Inheritance.
Demonstrate the standard namespace using the scope resolution (::) operator.
Example:
#include <iostream>using
namespace std;
char a = 'm'; // Global variablestatic
int b = 50;
int main() {
char a = 's'; // same as global variable name
cout << "The static variable : "<< ::b; // accessing static variable
cout << "\nThe local variable : " << a;
cout << "\nThe global variable : " << ::a; // accessing global variable
return 0;
}
Type casting/ Type Conversion refers to the conversion of one data type to another in a
program.Typecasting can be done in two ways:
Automatically by the compiler
Manually by the programmer or user.
Example: suppose we are given data which is an integer type, and we want to convert it into float
type. So, we need to manually cast int data to the float type, and this type of casting is called the
TypeCasting in C++.
1. Implicit Type Casting: In this casting compiler automatically converts one data type to
another. All data type is automatically upgraded to the largest type without losing any
information. Like below order-
char -> sort int -> int -> unsigned int -> long int -> float -> double -> long double
Example:
int num1 = 10;
double num2 = num1; // Implicit conversion from int to double
2. Explicit Type Casting: In this casting programmer or user manually change data type to
another type in a program. It uses the cast () operator to change the type of a variable.
Example:
double num1=4.56879;
int num2 = (int) num1; // Explicit conversion from double to int
char * const p:
This declaration defines a constant pointer p of char type. It means that p is a pointerthat cannot
be reassigned to point to a different memory location, but the value it points to can be modified.
This declaration defines a pointer p to a constant char type. It means that p is a pointerthat can be
reassigned to point to different memory locations, but the value it points to cannot be modified.
1. if Statements.
2. switch Statement.
3. conditional Operator Statement.
4. goto Statement.
5. loop Statements.
Q 1. Describe different types of operators used in C++ and state their purpose.
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provide the following types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
Arithmetic Operators: These operators are used to perform arithmetic or mathematical operations on
the operands. For example, ‘+’ is used for addition, ‘-‘ is used for subtraction ‘*’ is used for
multiplication, etc.
Relational Operators: These operators are used for the comparison of the values of two operands.
For example, ‘>’ checks if one operand is greater than the other operand or not, etc. The result returns
a Boolean value, i.e., true or false.
Logical Operator: These 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.
Bitwise Operator: These operators are used to perform bit-level operations on the operands. The
operators are first converted to bit-level and then the calculation is performed on the operands.
Mathematical operations such as addition, subtraction, multiplication, etc. can be performed at the bit
level for faster processing.
Assignment Operator: These operators are used to assign value to a variable. The left side operand
of the assignment operator is a variable and the right side operand of the assignment operator is a
value. The value on the right side must be of the same data type as the variable on the left side.
new: The new operator is used to allocate dynamic memory for objects, variable or arrays. It
dynamically creates an object or an array on the heap and returns a pointer to the allocated memory.
Example: int* ptr = new int(20); // Allocates memory and initialize for a single int
int* arr = new int[5]; // Allocates memory for an array of 5 int
delete: The delete operator is used to deallocate memory that was previously allocated with new. It
frees the memory occupied by objects or arrays.
In C++, basic data types include `int`, `float`, `char`, etc. An array takes one of these basic types and
creates a collection of multiple values of that type, all stored in a single structure. For example, an array
of integers (`int arr[5]`) is a group of 5 integers stored together, but it is based on the `int` data type.
So, arrays don't exist on their own—they are derived from other types like `int`, `float`, or `char`. That's
why we call them a derived data type!
This data type is commonly used in decision-making structures like `if` statements or loops, where we
need to evaluate whether a condition is met (true) or not (false).
Example:
#include <iostream>
int main() {
int userInput;
cout << "The dynamic variable is: " << dynamicVariable << endl;
return 0;
}
Q 6. What are the advantages of new operator over malloc() function?
Advantages of new over malloc() :
1. new does not need the sizeof() operator whereas malloc() needs to know the size
beforememory allocation.
3. new return specific type pointer whereas malloc() return NULL pointer.
4. new could initialize object while allocating memory to it whereas malloc () cannot.
1. new Operator: The new operator allocates memory for a single variable or object from the heap
(dynamic memory) and returns a pointer to the allocated memory.
Syntax:
2. new[ ] Operator: The new[ ] operator allocates memory for an array of elements (like multiple
integers or objects) dynamically.
Syntax:
int* arr = new int[5]; // Allocates memory for an array of 5 integers
3. delete Operator: The delete operator is used to deallocate memory that was previously allocated
with new. It frees up the allocated memory for a single variable or object.
Syntax:
delete ptr; // Frees the memory allocated for the single integer
4. delete[] Operator: The delete[ ] operator is used to deallocate memory for arrays that were allocated
using new[ ].
Syntax:
delete[ ] arr; // Frees the memory allocated for the array of 5 integers
Q 8. What is dynamic memory allocation?
Dynamic memory allocation is when a program requests memory from the computer while it’s running,
rather than before it starts. This is useful when you don’t know in advance how much memory we need.
For example, if we want to store a list of numbers, but we don’t know how many there will be until the
program runs, we can ask the computer to give you memory for exactly that many numbers using
dynamic memory allocation. In C++, we can do this with the new operator, and when we're done with
the memory, we use delete to free it.
Q 9. How can memory be allocated using new and release using delete?
In C++, memory allocation and deallocation can be managed using the new and delete operators. Here's
a simple explanation of how they work:
The new operator allocates memory on the heap for a single object or an array of objects. It returns a
pointer to the allocated memory.
Example:
int *ptr = new int; // Allocates memory for a single integer
*ptr = 10; // Assigns the value 10 to the allocated memory
Once the dynamically allocated memory is no longer needed, it should be freed using the delete
operator. For single objects, we use delete, and for arrays, we use delete[ ].
Example
Unary operators: These are the operators that use a single operand as their only input to create a new
value. The associativity of unary operators is from right to left, and they all have equal precedence. The
unary expression is created when we combine the unary operator with an operand.
An operator known as a binary operator manipulates two operands to get a result. Operators offer a
simple way to compare numerical values or character strings and are represented by special characters
or by keywords.
Ternary operators:
Some programming languages provide an operator called the ternary operator that uses three operands
instead of the usual one or two that most operators utilise. It offers a means of condensing a
straightforward if else block.
In C++, the scope resolution operator is :: , which It is used for the following purposes.
1) To access a global variable when there is a local variable with same name.
4) In case of multiple Inheritance: If the same variable name exists in two ancestor classes, we can
use scope resolution operator to distinguish.
5) For namespace: If a class having the same name exists inside two namespaces we can use the
namespace name with the scope resolution operator to refer that class without any conflicts
6) Refer to a class inside another class: If a class exists inside another class we can use the nesting
class to refer the nested class using the scope resolution operator
7) Refer to a member of the base class in the derived object: In the case of having the same
method in both the base and derived classes, we could refer to each by the scope resolution operator
as below.
#include <iostream>
using namespace std;
int main() {
int x = 5; // Local variable
cout << "Local x: " << x << endl; // Prints local x (5)
cout << "Global x: " << ::x << endl; // Accesses global x (10)
return 0;
}
Q 12. How does the following statement differ?
char *const p;
char const *p;
1. char *const p;
The pointer p cannot change to point to a different memory address after it is initialized.
However, the value at the address p points to can be modified.
Explanation:
Example:
char ch = 'A';
char *const p = &ch; // p is a constant pointer to 'ch'
*p = 'B'; // Valid: You can change the value at the address p points to.
p = &ch; // Error: You cannot change the pointer itself.
Explanation:
Example:
//*p = 'C'; // Error: Cannot change the value at the address p points to.
p = &ch2; // Valid: You can change the pointer to point to another location.
Q 13. Write a program to evaluate the following function to 0.0001% accuracy.
SUM= 1+ (1/2)2 + (1/3)3 + .…..(1/n)n
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double sum = 1.0; // Start with the first term, which is 1
double tolerance = 0.000001; // 0.0001% = 0.000001
double term = 0.0;
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double x, term, sum;
int n = 1; // Power starts with 1 for the first term (x)
double accuracy = 0.000001; // 0.0001% accuracy as a fraction
// Continue adding terms until the term is smaller than the accuracy limit
while (fabs(term) > accuracy) {
n += 2; // Increase power by 2 for the next term (i.e., from x^1 to x^3, x^5, etc.)
return 0;
}
Q 15. Write a program to evaluate the following function to 0.0001% accuracy.
Cos x= 1 - x2/2!+ x4/4! - x6/6! +…..
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double x, term, sum;
int n = 0; // Initialize the power at 0 for the first term (1)
double accuracy = 0.000001; // 0.0001% accuracy as a fraction
// Continue adding terms until the term is smaller than the accuracy limit
while (fabs(term) > accuracy) {
n += 2; // Increase power by 2 for the next term (i.e., x^2, x^4, etc.)
return 0;
}
Example:
#include <iostream>
using namespace std;
int main() {
int a = 8, b=7;
int& c = a, &d=b;
return 0;
}
1. Function arguments: In C++, references are often used as function parameters to pass arguments by
reference rather than by value. This allows the function to modify the original variable, rather than just a
copy of it.
2. Returning values from function: A function can also return a reference to a variable, allowing the
calling function to modify the original variable directly.
3. Object initialization: Reference variables can be used to initialize objects. A reference variable can
be used to initialize one object with the value of another object.
4. Alias for existing variable: reference variables can be used to create an alias for an existing variable,
allowing the original variable to be accessed by two different names.
5. Polymorphism: References are often used in C++ to implement polymorphism, where a single
interface can be implemented by multiple classes. By using references to base classes, a single function
can be called with object of various derived classes. Allowing for greater code re-usability and
flexibility.