C-- Assigment
C-- Assigment
● Data Insecurity: Data is exposed to the entire program, which means there's no security for
the data.
● Difficulty Relating to Real-World Objects: It's difficult to relate procedural programming
concepts to real-world objects.
Based on the sources, here are the key features of Object-Oriented Programming (OOP), explained in
detail:
● Objects: OOP is centered around the concept of objects, which are real-world entities with
characteristics and behaviours. An object is an identifiable entity with some characteristics
and behaviour. Objects are identified by a unique name and represent a particular instance of
a class.
● Classes: The building block of C++ that leads to Object-Oriented programming is a Class. A
class is like a blueprint for an object. It is a user-defined data type that holds its own data
members and member functions.
● Encapsulation: Wrapping code and data together into a single unit is known as
encapsulation. Both data and functions that operate on data are bundled as a unit called an
object.
● Abstraction: Abstraction refers to providing only essential information to the outside world
and hiding their background details. Hiding internal details and showing functionality is known
as abstraction.
● Polymorphism: When one task is performed in different ways, it is known as polymorphism.
In OOP, method overloading and method overriding are used to achieve polymorphism.
● Inheritance: When one object acquires all the properties and behaviours of a parent object, it
is known as inheritance. Inheritance provides code reusability. It involves forming a new
class (derived class) from an existing class (base class).
Based on the sources, here's an explanation of the basic structure of a C++ program:
● Collection of Commands: A C++ program comprises a collection of commands that instruct
the computer to perform specific tasks. This collection of commands is referred to as source
code or code.
● Functions and Keywords: These commands are typically either functions or keywords.
● Main Function: Every C++ program must have one function named main, which is the
starting point of execution. The main function is always called when the program first
executes.
Structure of C++ Program: The source provides #include <iostream> as the first line in
the example program. The iostream header file is used to define the cout, cin, and cerr
objects, which correspond to the standard output stream, standard input stream, and standard
error stream, respectively. Also the source provides an example of a basic C++ program:
#include <iostream>
int main(void) {
● Approach:
○ Procedural Programming: Uses a list of instructions to tell the computer what to
do step-by-step. It creates a step-by-step program that guides the application
through a sequence of instructions.
○ Object-Oriented Programming: Is a programming style associated with the concept
of Class, Objects, and other concepts revolving around these two, like Inheritance,
Polymorphism, Abstraction, Encapsulation etc. Everything is represented as an
object.
● Memory:
○ Procedural Programming: Variables and functions are stored in separate memory
locations.
○ Object-Oriented Programming: Variables and functions are stored in the same
memory location. Both data and function that operate on data are bundled as a unit
called an object.
● Importance:
○ Procedural Programming: Importance is given to the operation on data rather
than the data.
○ Object-Oriented Programming: Focuses on objects which have properties
(variables) and methods (functions).
● Real-world relation:
○ Procedural Programming: Difficult to relate with real-world objects.
○ Object-Oriented Programming: Designed to model programs using classes and
objects, making it easier to represent real-world entities.
● Data Security:
○ Procedural Programming: Data is exposed to the whole program, so there is no
security for data.
○ Object-Oriented Programming: Uses concepts like encapsulation and
abstraction to hide data and implementation details, providing data security.
5. Explain various data types available in C++.
C++ provides various data types, each represented differently within the computer’s memory. These
data types can be broadly classified into three categories: built-in data types, derived data types,
and user-defined data types.
● char: Used for storing single characters. The char keyword denotes this type. It typically
occupies 1 byte of memory, and its range is usually from -128 to 127. When a character is
assigned to a char variable, it stores the ASCII value of that character. There is also
unsigned char which also occupies 1 byte, but its range is 0 to 255.
● int: Used for storing numeric data without fractions. The size of an int variable varies from
computer to computer. On a 16-bit machine, it often occupies 2 bytes. Its range is typically
-32768 to 32767. int has modifiers like unsigned int, short int, and long int.
○ unsigned int: Also often occupies 2 bytes. It stores only positive values, with a
range from 0 to 65535.
○ short int: Typically occupies 2 bytes, same as int.
○ long int: Usually occupies 4 bytes, with a range from -2147483648 to
2147483647. Combinations like unsigned short int and unsigned long int
are possible, storing only positive values.
● float: Used to declare variables of real type, i.e., fractional numerical values. A float
variable occupies 4 bytes. Its range is approximately 3.4e-38 to 3.4e+38. It stores
floating-point numbers with 6 digits of precision. Floating-point numbers stored in a float
variable are called single-precision numbers. Modifiers of float include long float and
long double.
● double: A double variable requires 8 bytes of memory. Its range is about 1.7e-308 to
1.74e+308. It stores floating-point numbers with 14 digits of precision.
● long double: A long double variable needs 12 bytes of memory space. Its range is
approximately 3.4e-4932 to 1.1e+4932. It stores floating-point numbers with 14 digits of
precision and offers more accuracy.
● bool: The bool data type has two possible values: true or false. Booleans are used in
conditional statements and loops.
● void: The void keyword indicates an absence of data. It signifies "nothing" or "no value".
void cannot be used to declare simple variables.
6. Explain the concept of Keywords and Tokens.
Tokens:
Keywords:
● A keyword is a reserved word that cannot be used as a variable name or constant name.
● These words are used for special purposes or predefined tasks.
● Identifier names must differ in spelling and case from any keywords.
● You cannot use keywords as identifiers.
Constants are like normal variables, but their values cannot be modified by the program once they
are defined. Constants refer to fixed values and may belong to any data type.
The syntax for defining a constant is: const data_type variable_name; or const data_type
*variable_name;.
Types of Constants:
● Integer constants: These are fixed numerical values without any fractional part. For
example: 0, 1, 1218, 12482.
● Real or Floating-point constants: These are numerical values with a fractional part. For
example: 0.0, 1203.03, 30486.184.
● Octal & Hexadecimal constants:
○ Octal constants are represented with a base of 8. For example: (013 )8 =
(11)10.
○ Hexadecimal constants are represented with a base of 16. For example: (013)16 =
(19)10.
● Character constants: These are single characters enclosed in single quotes. For example:
'a', 'A', 'z'.
● String constants: These are sequences of characters enclosed in double quotes. For
example: "GLS University".
8. What is comment? Explain types of comments.
● Single-line comment: This type of comment starts with two forward slashes (//). Everything
after the slashes on the same line is considered a comment and is ignored by the compiler.
● Multi-line comment: This type of comment starts with /* and ends with */. Everything
between these delimiters, even across multiple lines, is considered a comment.
9. Explain Input/Output statements in C++.
C++ I/O operation uses the stream concept, where a stream is a sequence of bytes or flow of data,
making performance fast.
● Output Operation: If bytes flow from main memory to a device like a printer, display
screen, or a network connection, it's an output operation.
● Input Operation: Conversely, if bytes flow from a device to main memory, it's an input
operation.
● Header File: The <iostream> header file defines the cout, cin, and cerr objects,
corresponding to the standard output stream, standard input stream, and standard error
stream, respectively.
cin Statement:
● cin is a predefined variable that reads data from the keyboard using the extraction
operator (>>).
● It is a predefined object of the istream class.
● The syntax is: cin >> variable;. For example: int b; cin >> b; accepts a value for
the variable b.
● Multiple values can be accepted with a single cin statement. For example: cin >> a >>
b;.
cout Statement:
● The cout object, along with the << operator, is used to output values/print text.
● It is a predefined object of the ostream class.
● The syntax is: cout << variable;. For example: int b = 20; cout << b; displays
the value of variable b.
#include <iostream>
int main( )
int age;
cout << "Your age is: " << age << endl;
10. Explain the concept of variables and rules while defining variables.
Here's an explanation of the concept of variables and the rules for defining them in C++:
A variable is a name given to a memory location. It's the basic unit of storage in a program. The
value stored in a variable can be changed during program execution. A variable is just a name given
to a memory location, and all operations performed on the variable affect that memory location.
11. Write two or three names for each type of language (low, middle and high)
Here are some examples of programming languages classified into low-level, middle-level, and
high-level languages:
● Low-level languages: These languages are close to the machine's architecture and provide
little to no abstraction from the hardware.
○ Machine code
○ Assembly language
● Middle-level languages: These languages provide some abstraction but still allow for direct
manipulation of hardware.
○ C
● High-level languages: These languages are designed to be easier for humans to read and
write, providing significant abstraction from the hardware.
○ FORTRAN
○ COBOL
○ C++
12. List and explain disadvantages of Procedural Programming Language.
Here are the disadvantages of the Procedural Programming Language, according to the sources:
● Data Exposure: Data is exposed to the whole program, so there is no security for data.
● Difficulty relating to real-world objects: Procedural programming is difficult to relate to
real-world objects.
● Emphasis on operations rather than data: Importance is given to the operation on data
rather than the data itself.
● Class: A class is a user-defined data type that holds its own data members and member
functions. It serves as a blueprint for creating objects.
● Object: An object is an identifiable entity with some characteristics and behaviour and is an
instance of a class.
14. List derived data type names.
● Functions: In C++, functions are a set of statements that perform a specific task. Functions
are stored in separate memory locations in procedural programming, but in OOP, variables
and functions are stored in the same memory location.
● Arrays: The sources do not explicitly list arrays as derived data types. However, arrays are a
collection of elements of the same data type, so they are typically considered a derived data
type.
● Pointers: The sources do not explicitly list pointers as derived data types.
● References: From the sources, it is not clear whether references are derived data types.
15. List some new keywords available in C++.
● class: It is a keyword in C++ used to define a class. The building block of C++ that leads to
Object-Oriented programming is a Class. It is a user-defined data type.
● bool: The bool data type has one of two possible values: true or false. Booleans are
used in conditional statements and loops.
● const: const is a keyword in C++ used to declare a constant. Constants are like normal
variables, but their values cannot be modified by the program once they are defined.
● namespace: A namespace is designed to overcome difficulties and is used as additional
information to differentiate similar functions, classes, variables, etc., with the same name
available in different libraries.
● Purpose: It serves to get hidden names due to variable scopes so that you can still use them.
A namespace is designed to overcome this difficulty and is used as additional information to
differentiate similar functions, classes, variables etc. with the same name available in different
libraries.
● Unary Scope Operator: You can use the unary scope operator if a namespace scope or
global scope name is hidden by a particular declaration of an equivalent name during a block
or class. For example, if you have a global variable named my_var and a local variable
named my_var, you can access the global my_var using the scope resolution operator.
#include <iostream>
int my_var = 0;
int main(void) {
int my_var = 0;
return 0;
In C++, a reference variable is an alias for another variable. It provides a second name for the same
memory location [not from sources].
● Declaration: References are declared using the & symbol. For example: int x = 10;
int& ref = x; Here, ref is a reference to the variable x.
● Initialization: References must be initialised when they are declared. They cannot be
declared and then assigned later.
● Cannot be Null: A reference cannot be null. It must always refer to an object.
● Cannot be reassigned: Once a reference is bound to a variable, it cannot be reassigned to
refer to another variable.
● Use Cases: References are often used in function arguments to allow a function to modify
the original variable passed to it. This avoids the need to pass pointers and dereference them.
They are also used to avoid copying large objects when passing them to functions.
Here are the answers to Question 6 ("Match the following") from the "C++
Unit_1_Theory_Assignment.pdf" source:
● int: 2 or 4
● short int: 2
● long int: 4
● short: 2
● long: 4
● long long int: 8
● float: 4
● double: 8
● char: 1
● bool: 1
● long double: 10 or 12
3. Match the following lines with their corresponding access modifier names:
1. Class: A user-defined data type that holds its own data members and member functions. It
is a blueprint for creating objects.
2. Object: An identifiable entity with some characteristics and behaviour, and an instance of a
class.
3. Data Type: Determines the type and the operations that can be performed on the data.
4. Variable: A name given to a memory location. It is the basic unit of storage in a program,
and its value can be changed during program execution.
5. Keyword: A reserved word that cannot be used as a variable name or constant name.
8. Cout: A predefined object of the ostream class used for displaying outputs.
9. Cin: A predefined variable that reads data from the keyboard with the extraction operator
(>>). It is a predefined object of the istream class.
10. Inheritance: When one object acquires all the properties and behaviours of a parent
object. It provides code reusability.
12. Abstraction: Providing only essential information to the outside world and hiding
background details. Hiding internal details and showing functionality.
13. Encapsulation: Wrapping code and data together into a single unit.
17. Bool: A data type with one of two possible values: true or false. Booleans are used in
conditional statements and loops.
19. Const: A keyword in C++ used to declare a constant. Constants are like normal variables,
but their values cannot be modified once defined.
UNIT-2
2. do...while looping is executed at least once even though the condition is false. The do...while
loop checks its condition at the bottom of the loop. A do...while loop is similar to a while
loop, except that a do...while loop is guaranteed to execute at least one time.
4. A set of statements enclosed within a pair of opening and closing braces is called a
compound statement.
8. Switch structure/statement is an alternative to the else-if ladder which simplifies the code and
enhances readability.
9. If some operands are of integer type and some are of float type in an expression then it is
called a mixed mode expression.
10. The sizeof is a keyword and operator that determines the size, in bytes, of a variable or data
type. The sizeof is a compile-time operator that determines the size, in bytes, of a variable
or data type. The sizeof operator can be used to get the size of classes, structures, unions,
and other user-defined data types.
11. Ternary type of operators is defined with three operands. The conditional operator is a
ternary operator, taking three operands.
12. A conditional operator is also known as Ternary operator. The conditional operator (? :) is
a ternary operator (it takes three operands).
Q-2 True or False
1. goto: A goto statement provides an unconditional jump from the goto to a labeled
statement in the same function.
2. break: The source does not explicitly define the break keyword. However, it is implied that
break statement forces termination, and continue forces the next iteration of the loop to
take place, skipping any code in between.
3. continue: The continue statement forces the next iteration of the loop to take place,
skipping any code in between.
4. sizeof(): The sizeof is a keyword and compile-time operator that determines the size, in
bytes, of a variable or data type. The sizeof operator can be used to get the size of classes,
structures, unions, and any other user-defined data type. The syntax is sizeof (data
type).
5. stoi(): The sources do not contain a definition of the function stoi().
6. stod(): The sources do not contain a definition of the function stod().
7. else: When the if condition becomes false then else block gets executed. An if block can
have zero or one else block and it must come after else if blocks.
8. default: In a switch case, the default case is optional.
9. Nested if: It is always legal to nest if-else statements, which means you can use one if or
else if statement inside another if or else if statement(s).
1. Output: 11 (Due to the misplaced semicolon after the for loop, the loop runs without
executing the block, and i is incremented to 11 before printing.)
2. Compilation Error (% operator is not valid for float values.)
3. Compilation Error (void main() is incorrect; should be int main())
4. Output: z is:21
Output:
pgsql
CopyEdit
x is: 100
5.
6. Output: 170
7. Output: CHAR IS VOWEL: (Because 'A' is matched in case 'A':)
8. Output: 5 (if(a=5) assigns 5 to a, making the condition true.)
9. Compilation Error (Variables a, b, and c are used without declaration.)
10. Output: z is:19
○ Assignment Operator
○ Arithmetic Operator
○ Relational Operator
○ Logical Operators
○ Shorthand Arithmetic Assignment Operators
○ Increment/Decrement Operators
○ Conditional Operator
○ sizeof() Operator
○ Comma Operator
○ Ternary Operator
● Expressions and operands are not explicitly defined in the sources.
● Here's an example:
#include <iostream>
using namespace std;
int main () {
int a = 100;
int b = 200;
if( a == 100 ) {
if( b == 200 ) {
cout << "Value of a is 100 and b is 200" << endl;
}
}
cout << "Exact value of a is : " << a << endl;
cout << "Exact value of b is : " << b << endl;
return 0;
}
For Loop
Syntax:
for ( init; condition; increment ) {
statement(s);
●
○ init: The initialization step is executed first, and only once,
allowing you to declare and initialize any loop control
variables. It's not required, as long as a semicolon appears.
○ condition: Next, the condition is evaluated. If it is true, the
body of the loop is executed. If it is false, the body of the
loop does not execute, and control jumps to the next statement
after the for loop.
○ increment: After the body of the for loop executes, the flow of
control jumps back up to the increment statement, which updates
any loop control variables. This statement can be left blank,
as long as a semicolon appears after the condition.
For example:
Example:
#include <iostream>
using namespace std;
int main() {
int i = 1;
do {
cout << "Value of i: " << i << endl;
i++;
} while (i <= 5);
return 0;
}
● In this example, the code inside the do block will execute at least
once, printing the value of i. Then, the condition i <= 5 is checked.
If it's true, the loop continues; otherwise, it terminates.
9. What are binary operators? Explain with the help of an example.
The following points explain binary operators with examples:
10.explain the for loop with an example. The following points explain the
for loop:
Example:
#include <iostream>
int main() {
return 0;
13. explain the working of logical && and logical || operators. The
following explains the working of these logical operators:
● Logical AND (&&):
○ The logical AND operator && returns true (1) if both operands
are true (non-zero). If either operand is false (0), it returns
false (0).
Example:
#include <iostream>
int main() {
int a = 5;
int b = 10;
return 0;
Example:
#include <iostream>
int main() {
int a = -1;
int b = 10;
if (a > 0 || b < 20) {
return 0;
14. explain the concept of the goto statement. The following points explain
the goto statement:
Syntax:
goto label;
...
label: statement;
Example:
#include <iostream>
int main() {
goto notEligible;
notEligible:
return 0;
}
● In this example, if age is less than 18, the program jumps to the
notEligible label and prints "Not eligible to vote".
15. explain the comma operator with the help of an example. The following
points explain the comma operator:
Example:
#include <iostream>
int main() {
int i, j;
return 0;
Example:
#include <iostream>
using namespace std;
int main() {
int a = 10;
a += 5; // a = a + 5; a is now 15
a -= 3; // a = a - 3; a is now 12
a *= 2; // a = a * 2; a is now 24
a /= 4; // a = a / 4; a is now 6
a %= 5; // a = a % 5; a is now 1
return 0;
17. explain the Ternary operator with the help of an example. The following
explains the ternary operator:
Example:
#include <iostream>
int main() {
return 0;
UNIT-3
● Built-in Functions:
○ These are pre-defined functions available in the C++ library.
○ Example: cout is a built-in function used for displaying
output.
● User-defined Functions:
○ These are functions written by the user to solve specific
problems.
Example:
int add(int a, int b) {
return a + b;
● Function Header:
○ The function header consists of the return type, function name,
and parameter list (arguments).
○ Syntax: return_type function_name(parameter list).
○ Example: int max(int num1, int num2).
● Function Call:
○ A function call is when a program executes a function by
transferring control to it.
○ To call a function, use the function name followed by
parentheses containing any required parameters.
○ Example: int result = max(5, 3); calls the max function with
arguments 5 and 3.
● Calling Function:
○ A calling function is a function that invokes another function.
● Called Function:
○ A called function is the function that is invoked by another
function.
○ When a program calls a function, program control is transferred
to the called function.
Example:
int factorial(int n) {
if (n == 0) // Base case
return 1;
else
○
● Inline Function:
○ An inline function is a function for which the compiler
replaces the function call with the actual code of the function
at compile time.
○ The inline keyword is used to request the compiler to perform
this substitution.
○ Syntax: inline return-type function-name(parameters) { //
function code }.
● Significance:
○ Reduces function call overhead by inserting the function code
directly into the calling code.
○ Can improve efficiency, especially for small functions.
● Limitations:
○ The compiler may not perform inlining if the function contains
loops, static variables, recursion, or switch/goto statements.
8. Explain the concept of Function Overloading with an example.
● Function Overloading:
○ Function overloading allows multiple functions with the same
name but different parameter lists (different number or types
of arguments) within the same scope.
○ It enhances the readability of the program.
○ It is an example of polymorphism in C++.
○ Function overloading can be achieved by:
■ Changing the number of arguments.
■ Using different types of arguments.
Example:
int add(int a, int b) {
return a + b;
return a + b;
○
Example:
void display(int m) { // Function declaration
cout << "Student " << i + 1 << ": " << m[i] << endl;
int main() {
return 0;
○
Example:
int a = {
};
○
● Declaring an Array:
○ Specify the type of elements and the number of elements
required.
○ Syntax: type arrayName[arraySize].
○ Example: double balance.
● Initializing an Array:
○ Arrays can be initialized one by one or using a single
statement.
○ Example: double balance = {1000.0, 2.0, 3.4, 17.0, 50.0}.
○ If the size is omitted, the array is created just big enough to
hold the initialization values.
○ Example: double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0}.
Example:
void display(int n[]) { // Function declaration
cout << "num[" << i << "][" << j << "]: " << n[i][j] <<
endl;
}
int main() {
int num = {
{3, 4},
{9, 5},
{7, 1}
};
return 0;
○
● Default Argument:
○ A default argument is a value provided in a function
declaration that the compiler automatically assigns if the
caller does not provide a value for that argument.
○ If an argument is given a default value, all subsequent
arguments must also have default values.
○ Syntax: sum (int x, int y = 0);.
○ You can assign any value compatible with its data type as the
default value.
Example:
int sum(int x, int y = 0) {
return x + y;
UNIT-4
1.False. Nested data members are accessed using the dot operator (.) or
arrow operator (->) depending on whether you are accessing them
through an object or a pointer to an object.
2.False. In a class, members are private by default.
3.True. By default, the components/members of a structure are public.
4.False. Public members are accessible from the outside world.
5.False. Friend functions can be declared in either the private or
public part of a class.
6.True. The members of a class should be called with an object of the
class.
7.True. Each object of a class will have its own copy of its member
data.
8.False. Functions can return class objects.
9.True. The 'this' pointer is a constant pointer that holds the memory
address of the current object.
10.
True. A function becomes const when the const keyword is used in the
function’s declaration.
11.
True. Friend functions are not member functions.
12.
True. By creating a friend class, all the member functions of the
friend class also become friends of the other class.
13.
True. There is only one copy of the static member that has to be
created.
14.
True. All static data is initialized to zero when the first object is
created if no other initialization is present.
15.
True. A static function member is independent of any particular
object of the class.
16.
True. Member functions of a class can access static variables.
○ C++ does not directly support nested functions in the same way
as some other languages. However, similar behavior can be
achieved using lambda expressions or function objects
(functors).
For a detailed code example, please ask ChatGPT for the code
explanation.
5.Explain how to create an array of class objects with an example.
○ An array of objects is created when each element in the array
is an object of a class. The typical syntax involves specifying
the class name followed by the object array with a specified
size.
For a detailed code example, please ask ChatGPT for the code
explanation.
6.How to pass objects as a parameter, explain in detail with an
example.
Explain the significance of the this pointer.
● Characteristics:
● Constructor:
class Example {
public:
int x;
// Constructor
Example() {
x = 0;
};
●
● Destructor:
class Example {
public:
// Destructor
~Example() {
};
●
class Student {
public:
int id;
string name;
// Parameterized Constructor
Student(int i, string n) {
id = i;
name = n;
};
● Example:
class Point {
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }
// Copy constructor
};
int main() {
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY() << endl;
cout << "p2.x = " << p2.getX() << ", p2.y = " << p2.getY() << endl;
return 0;
Example:
class DynamicArray {
private:
int *arr;
int size;
public:
// Dynamic Constructor
DynamicArray(int s) {
size = s;
~DynamicArray() {
};