0% found this document useful (0 votes)
79 views19 pages

Chapter 2 - Begins With C++ & Tokens, Expression and Ctrl. Structure

Uploaded by

basur00basur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views19 pages

Chapter 2 - Begins With C++ & Tokens, Expression and Ctrl. Structure

Uploaded by

basur00basur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

College of Business, Science &Technology (CBST), Mymensingh

Department of Computer Science and Engineering

Object Oriented Programming (OOP)

Tokens, Expressions and Control Structures

Prepared by
Md. Masum Billah
Lecturer, Dept. of CSE, CBSTMobile:
01793200796
Q. What is C++.

C++ is a cross-platform programming language that can be used to create high-performance


applications. It is as an extension to the C language. C++ gives programmers a high level of control
over system resourcesand memory.

C++ supports the object-oriented programming, the four major pillar of object-oriented
programming(OOPs) used in C++ are:

 Inheritance
 Polymorphism
 Encapsulation
 Abstraction

Q. Difference between C and C++.


C Language C++ Language
C is a structural or procedural programming C++ is a structural as well as an object-oriented
language. programming language.
C does not have any security features so it can be C++ is a secure language as it offers security
manipulated by outsider features such as data hiding and encapsulation.
C follows the top-down approach. C++ follows the bottom-up approach.
In C, scanf() and printf() are mainly used for C++ mainly uses stream cin and cout to perform
input/output. input and output operations.
C does not support reference variables. C++ supports reference variables.
C programs are divided into procedures and C++ programs are divided into functions and
modules classes.
C does not support the OOP features. C++ supports OOP features.

Q. Basic Structure of C++.

Basic structure of C++ is given below-


Q. Describe Various Sections of a C++ program.

A simple C++ program is given below-

#include <iostream.h>

using namespace std;

class Human{
int age=25;
char name[20]=”Rubel”;

public:
void display()
{
cout <<”Age is: ”<<age <<” Name is: ”<< name<< endl;
}

};

int main() {

Human h1; // Creation of object


h1.display( ); // Calling object function

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++.

class Human- declare class named as ‘Human’

int main() - The main function is the entry point of every program in C++ language. The void
keyword specifies that it returns no value.

Human h1 – Object of class Human is created..

cout - is used to print output to the standard output device (screen).

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.

Here are some examples of tokens in C++:

Keywords: int, double, if, else, for, while, return

Identifiers: x, y, sum, average, total_sales

Operators: +, -, *, /, %, ==, !=, >, <, &&, ||

Literals: 10, 3.14, "hello", 'a', true, false

Punctuators: ; , {, }, (, ), [, ], ,, ., ->

Special symbols: ::, >>, <<, #, ::

Tokens are the building blocks of C++ programs, and the compiler uses them to parse the code and
generate the corresponding machine code.

Q. Define keywords, Identifiers, Constants, Operators.

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

2. Identifiers: Identifier is a name given to a variable, function, class, or other user-defined


entityin a program. Identifiers in C++ can be composed of letters (both upper and lower case),
digits, and underscores (_). Identifiers in C++ are case-sensitive, which means that sum, Sum, and
SUM are all different identifiers.

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.

There are two types of constants in C++:


1. Literal constants. 2. Symbolic constants.
Literal constants are values that are directly specified in the code, and their value is determined
atcompile time. For example, 10, 3.14, „A‟, “hello” are all literal constants.

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.

Example: #define PI 3.14159265

const int MAX_ITEMS = 100;

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.

Q. Data Types in C++.


C++ supports the following data types:

 Primary or Built-in or Fundamental data type


 Derived data types
 User-defined data types

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

Q. Why type modifiers are used?

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.

Q. Application of void data type C++.

C++ doesn’t support void as variable type. Rather void data type can be used in some specific fact-

1. To specify return type of a function. Example-

void function()
{
}

2. To indicate empty parameter in parameter list. Example-

void function( void )


{
}

3. To declare generic pointer. Example-

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;

Q. Describe the uses of enumeration data type with example.

An enumeration is a user-defined data type that consists of integral constants. To define


anenumeration, keyword enum is used. Example-

enum season { spring, summer, autumn, winter };

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;
}

Q. Type cast in C++.

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++.

int num = 5;float


x;
x = float(num);

x = 5.0 // x is now 5.0

Type Casting is two types:

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

Q. What is the difference between 2 statements?


char * const p;
char const *p.

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.

char const *p:

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.

Q. What are the control flow statements in C/C++?


Control Statements Types Used in C/C++ Language-

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.

Q 2. Describe memory management operators in C++.


In C++, memory management operators allow us to allocate and deallocate memory dynamically.
The main memory management operators in C++ are:

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.

Syntax: pointer_variable = new data-type

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.

Syntax: delete pointer_variable;

Example: delete ptr; // Deallocates memory for a single int


delete[] arr; // Deallocates memory for the array of int
Q 3. Why array is called a derived data type.
An array is called a derived data type because it is built (or "derived") from a basic data type.

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!

Q 4. What is the bool data type.


The `bool` data type is a boolean data type that can hold one of two values: `true` or `false`. These
values represent the truth of a condition or statement.

- `true`: Represents a value of 1.


- `false`: Represents a value of 0.

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:

bool isEven = (5 % 2 == 0); // This will be false because 5 is odd

Q 5. What is the dynamic initialization of a variable? Give an example.


Dynamic initialization of a variable refers to the process of assigning an initial value to a variable
at runtime, rather than at compile time. It allows the value of the variable to be determined
dynamicallybased on program logic or user input.

Here's an example in C++:

#include <iostream>

using namespace std;

int main() {
int userInput;

cout << "Enter a number: ";


cin >> userInput;

int dynamicVariable = userInput * 2;

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.

2. Operator new can make a call to a constructor whereas malloc() cannot.

3. new return specific type pointer whereas malloc() return NULL pointer.

4. new could initialize object while allocating memory to it whereas malloc () cannot.

Q 7. Dynamic memory allocation and deallocation operators new, new [ ], delete,


delete[ ].
Dynamic memory allocation allows us to allocate memory during runtime, rather than at compile
time.C++ provides special operators for dynamic memory allocation and deallocation: new and delete.

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:

int* ptr = new int; // Allocates memory for a single integer

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:

1. Allocating Memory Using new

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

2. Deallocating Memory Using delete

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

delete ptr; // Frees the memory allocated for the integer

Q 10. Explain the use of Unary and Ternary operator.


Operators are symbols that tell the compiler or interpreter to perform specific mathematical, logical, or
relational operations. Based on the number of operands they work with, operators can be classified into
unary, binary, and ternary operators.

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.

Example: ++, - - etc are unary operators.


Binary operators:

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.

Example: +,-,*,/ are binary operators.

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.

Example: ( ? : ) is a ternary operator.

Q 11. Role of Scope resolution operator. Explain with example.

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.

2) To define a function outside a class.

3) To access a class’s static variables.

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.

Example: Accessing Global Variables

#include <iostream>
using namespace std;

int x = 10; // Global variable

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;

This declares a constant pointer to a char.

 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:

 *const means the pointer is constant.


 You can modify the value p points to, but you can't change the address stored in p.

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.

2. char const *p;

This declares a pointer to a constant char.

 The pointer p can change to point to a different address.


 However, the value at the address p points to cannot be modified.

Explanation:

 const * means the data pointed to is constant.


 You can change p to point to another memory location, but you cannot modify the value it points
to.

Example:

char ch1 = 'A';


char ch2 = 'B';
char const *p = &ch1; // p is a pointer to a constant char

//*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;

for (int n = 2;; n++) { // Infinite loop using for


term = pow(1.0 / n, n); // Calculate the nth term
sum += term;

// Break if the term is smaller than tolerance


if (term < tolerance) {
cout << "Sum evaluated to: " << sum << " using " << n << " terms" << endl;
break;
}
}
return 0;
}

Q 14. Write a program to evaluate the following function to 0.0001% accuracy.


Sin x= x - x3/3! + x5/5! - x7/7! +…..

#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

// Input the angle in radians


cout << "Enter the value of x (in radians): ";
cin >> x;

term = x; // The first term in the series is x


sum = x; // Initialize sum with the first term

// 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.)

// Calculate next term based on previous term


term = -term * (x * x) / (n * (n - 1)); // Efficient calculation of next term
sum += term; // Add the term to the sum
}

// Output the final result


cout << "Sin(" << x << ") = " << sum << endl;

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

// Input the angle in radians


cout << "Enter the value of x (in radians): ";
cin >> x;

term = 1; // The first term in the series is 1


sum = 1; // Initialize the sum with the first term

// 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.)

// Calculate next term based on the previous term


term = -term * (x * x) / (n * (n - 1)); // Efficient calculation of next term
sum += term; // Add the term to the sum
}

// Output the final result


cout << "Cos(" << x << ") = " << sum << endl;

return 0;
}

Q 16. What is a reference variable? What is it’s major uses?


Reference variable is an alternate name of already existing variable. It cannot be changed to
referanother variable and should be initialized at the time of declaration and cannot be NULL.
The operator ‘&’ is used to declare reference variable.

The following is the syntax of reference variable:

datatype & refer_var = variable_name; // reference variable

Example:

#include <iostream>
using namespace std;

int main() {
int a = 8, b=7;
int& c = a, &d=b;

cout << "The variable a : " << a;


cout << "\n The reference variable of a : " << c;
cout << "The variable b : " << b;
cout << "\n The reference variable of b : " << d;

return 0;
}

Major uses of reference variable:

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.

Q 17. Differentiate between the process of dynamic memory allocation used in C


and C++.
From text book

You might also like