0% found this document useful (0 votes)
12 views51 pages

C-- Assigment

The document provides an overview of C++ programming concepts, including definitions of key terms such as source code, class, polymorphism, and data abstraction. It also covers true/false statements about C++ features, the basic structure of a C++ program, and comparisons between procedural and object-oriented programming. Additionally, it explains various data types, constants, comments, and input/output statements in C++.

Uploaded by

freemovies1218
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)
12 views51 pages

C-- Assigment

The document provides an overview of C++ programming concepts, including definitions of key terms such as source code, class, polymorphism, and data abstraction. It also covers true/false statements about C++ features, the basic structure of a C++ program, and comparisons between procedural and object-oriented programming. Additionally, it explains various data types, constants, comments, and input/output statements in C++.

Uploaded by

freemovies1218
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/ 51

Unit-1 (C++)

1.​ Collection of commands is called source code or code.


2.​ Collection of object is called class.
3.​ When one task is performed by different ways is known as polymorphism.
4.​ Data Abstraction refers to providing only essential information to the outside world and
hiding their background details. Abstraction is hiding internal details and showing functionality.
5.​ In C++ data types (variables) are called identifiers.
6.​ In C++ the functions are called methods.
7.​ Cout is an output statement.
8.​ >> is called extraction bitwise operator.
9.​ Floating point numbers stored in float variable are called single-precision numbers.
10.​ << is called insertion bitwise operator.
Q-2 True or False
1.​ Class is a blueprint or structure. True.
2.​ Hiding internal details and showing functionality is known as polymorphism. False.
Polymorphism refers to one task being performed in different ways. Hiding internal details and
showing functionality is known as abstraction.
3.​ Wrapping code and data together into a single unit is known as encapsulation. True.
4.​ Private members of the class cannot be accessed outside the class. True.
5.​ Dot operator is used to access the members of the class. True.
6.​ Cin is an output statement. False. Cin is an input statement. Cout is an output statement.
7.​ C++ is a low level language. False. C++ is a high level language. Fortran, COBOL and C are
high level programming languages.
8.​ POP program is difficult to relate with real world scenario. True.
9.​ Fortran, COBOL and C are called high level programming languages. True.
10.​ String literal is by default added with a special character \n null character which denotes the
end of the string. False. String literal is by default added with a special character \0 null
character which denotes the end of the string.
11.​ const is a keyword in c++ and which is used declare constant. True.
12.​ class is a keyword in c++ and which is used to define class. True.
13.​ #define PI 3.142 is an example definition section within structure of C++ program. False.
#define PI 3.142 is an example preprocessor directives within structure of C++
program.
14.​ Inheritance provides code reusability. True.
15.​ Object is an instance of a class. True.

Q-3 Put check mark on correct answer.

1.​ Class is a _____________________type of data type. User defined.


2.​ When global variables and local variables are having same name then to access global
varables in a scope of local variable's context __________ operator is used. Scope
Resolution. The scope resolution operator :: is used to access hidden names due to
variable scopes.
3.​ Class variables have ______________ access specifiers by default. Private.
4.​ what will be the output of sizeof(long long int) in C++? 8.
5.​ Which punctuation ends most lines of C++ code? ;
6.​ Which of the following is a valid class declaration? class B { }

Q-4 Give answer for following questions.

1.​ C++ was developed by Bjarne Stroustrup at Bell Labs in 1983.


2.​ Every program in C++ has one function, always named main, that is always called when your
program first executes.
3.​ Right shift bitwise >> is called extraction operator.
4.​ Left shift bitwise << is called insertion operator.
5.​ In C++ data types(variables) are called identifiers.
6.​ In C++ the functions are called methods.
7.​ Hexadecimal integer constant is preceded by 0x. (Note: This information is not directly
available in the provided sources, and may require independent verification.)
8.​ Octal integer constant is preceded by 0. (Note: This information is not directly available in the
provided sources, and may require independent verification.)
9.​ In POP Importance is given to the operation on data rather than the data.
10.​ Collection of commands is called source code or code.
11.​ Object is an instance of a class.
12.​ To give effect of carriage return /new line endl is used. (Note: \n can also be used to give the
effect of carriage return/new line. This information is not directly available in the provided
sources, and may require independent verification.).

Q-5 Answer the following questions:

Q-5 Answer the following questions:

1. What is Procedural Programming Language?

Based on the sources, here's a detailed explanation of Procedural Programming Language:

●​ Step-by-step Instructions: Procedural programming involves providing a list of instructions


to the computer, detailing what to do step by step.
●​ Traditional Approach: It is a standard approach used in traditional languages like Fortran,
COBOL, and C.
●​ Sequential Execution: In this paradigm, each instruction is executed in order, one after the
other.
●​ Variables and Functions: Variables and functions are stored in separate memory locations.
●​ Focus on Operations: Procedural programming places importance on the operation
performed on data rather than the data itself.

Disadvantages of Procedural Programming

●​ 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.

2. List and explain features of OOPs.

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

3. Explain the basic structure of C++ program.

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>

using namespace std;

int main(void) {

Cout << “Hello World” << endl;

4. Differentiate Procedural Programming Language and Object-Oriented Programming.

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

Here's an explanation of the 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.

Built-in 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.

Here's an explanation of the concepts of Keywords and Tokens in C++:

Tokens:

●​ A token is the smallest element of a program that is meaningful to the compiler.


●​ Examples of tokens are:
○​ Keywords
○​ Identifiers
○​ Constants
○​ Strings
○​ Special Symbols
○​ Operators

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.

Solve question 7 for now.

7.​ Explain the types of Constants with example.

Here's an explanation of the types of Constants with examples in C++:

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.

Here's an explanation of comments and their types in C++:

In computer programming, a comment is a programmer-readable explanation or annotation in the


source code of a computer program. Comments are statements that are not executed by the
compiler and interpreter.

In C/C++, there are two 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++.

Here's an explanation of 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.

The << symbol is called the insertion operator.

The source provides the following example:

#include <iostream>

int main( )

int age;

cout << "Enter your age: ";

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

In C++, all variables must be declared before use.

Rules for defining variables (identifiers):


●​ Identifiers are used as the general terminology for the naming of variables, functions, and
arrays.
●​ Identifier names must differ in spelling and case from any keywords.
●​ You cannot use keywords as identifiers
●​ The first character of an identifier should be an alphabet or underscore. The rest can be
letters, digits, or underscores.
●​ Lower case and upper case letters are distinct.
●​ The maximum length of an identifier can be of 31 characters. However, the length varies from
one version of the compiler to another version.
●​ Some valid examples: sum, a1, a2, _1, _a, average, a_b, x123y.
●​ Some invalid examples: 1a, a-b, float.

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.

13.​ List user define data types names.

Here are some user-defined data types in C++:

●​ 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.

Here are some derived data types in C++:

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

Here are 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.

16.​ List advantages of Object Oriented Programming Language.

Here are some advantages of Object-Oriented Programming (OOP):

●​ Real-world connection: OOP is easier to relate to real-world objects. Everything is


represented as an object, which makes it a truly object-oriented programming language.
●​ Code reusability: Inheritance, a core concept in OOP, provides code reusability.
●​ Data security: Encapsulation, another key feature, wraps code and data together into a
single unit. Abstraction also helps in providing only essential information and hiding
background details.
17.​ Explain Scope Resolution Operator.

Here's an explanation of the Scope Resolution Operator (::) in C++:


The scope resolution operator :: is used to access hidden names due to variable scopes. It can be
used as both unary and binary.

●​ 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>

using namespace std;

int my_var = 0;

int main(void) {

int my_var = 0;

::my_var = 1; // set global my_var to 1

my_var = 2; // set local my_var to 2

cout << ::my_var << ", " << my_var;

return 0;

18. Explain Reference variable.

In C++, a reference variable is an alias for another variable. It provides a second name for the same
memory location [not from sources].

Key characteristics of references [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:

1. Match each data type with its size in memory:

●​ 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

2. Match the following lines with their corresponding features:


●​ One name many forms: Polymorphism
●​ Wrapping up data and functions in a single unit: Encapsulation
●​ Including only essential things: Abstraction
●​ Parent and Child class Relationships: Inheritance

3. Match the following lines with their corresponding access modifier names:

●​ only class: Private


●​ class plus extended class both can share: Protected
●​ outside class and anywhere in file: Public

Q-7 Define Following in one or two line.

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.

6.​ Preprocessor Directives: The sources do not define preprocessor directives.

7.​ endl: The sources do not define endl.

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.

11.​ Polymorphism: When one task is performed in different ways.

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.

14.​ Private: Only class can access private members.

15.​ Protected: Class plus extended class both can share.


16.​ Public: Outside class and anywhere in file.

17.​ Bool: A data type with one of two possible values: true or false. Booleans are used in
conditional statements and loops.

18.​ String: The sources do not define string.

19.​ Const: A keyword in C++ used to declare a constant. Constants are like normal variables,
but their values cannot be modified once defined.

20.​ Comments: Programmer-readable explanations or annotations in the source code of a


computer program, which are not executed by the compiler and interpreter.

UNIT-2

Q-1 Fill in the Blanks

1.​ Unary type of operator defined with a single operand.

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.

3.​ A relational expression is also called a Boolean expression or a Logical expression.

4.​ A set of statements enclosed within a pair of opening and closing braces is called a
compound statement.

5.​ A goto statement provides an unconditional jump. A goto statement provides an


unconditional jump from the goto to a labeled statement in the same function.

6.​ Binary type of operator is defined with two operands.

7.​ Looping is used when a block of code is to be executed n number of times.

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.​ In switch case default case is optional. True


2.​ The comma operator (,) is used to separate two or more expressions. True
3.​ Break statement forces the next iteration of the loop to take place, skipping any code in
between. False The continue statement forces the next iteration of the loop to take place,
skipping any code in between.
4.​ If block is always followed with the optional else block. False An if block is sometimes
followed with the optional else block.
5.​ While loop tests the condition at the end of the loop only. False Unlike for and while loops,
which test the loop condition at the top of the loop, the do...while loop checks its condition
at the bottom of the loop.
6.​ Looping is also called iteration. True
7.​ Do... while loop is followed by three fundamentals things to construct loop, initialisation and
test-expression. False
8.​ A while loop can be nested inside another loop. True
9.​ Remainder Operators (%) are not compatible with floating point numbers. True
10.​ The do-while loop is similar to the while loop, except that the test condition occurs at the end
of the loop. True A do...while loop is similar to a while loop, except that a do...while
loop is guaranteed to execute at least one time.

Q-3 Define following keywords/functions

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

Q-4 Find the Output:

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

address of x is: <some address>

size of x is: 16 (depends on the system, typically 16 for `long


double`)

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

Q-5 Answer the following questions:

1. What are Bitwise operators?explain with the help of an example.


Bitwise Operators in C++

1.​Definition: Perform operations at the bit level on integers.​

2.​Types of Bitwise Operators:​

○​ AND (&) → Sets bits to 1 if both corresponding bits are 1.


○​ OR (|) → Sets bits to 1 if at least one corresponding bit is 1.
○​ XOR (^) → Sets bits to 1 if only one corresponding bit is 1.
○​ NOT (~) → Inverts all bits (bitwise complement).
○​ Left Shift (<<) → Shifts bits left (multiplies by 2).
○​ Right Shift (>>) → Shifts bits right (divides by 2).

2: Explain the concept of operators. Explain term expressions and


operands.

●​ An operator is a symbol that tells the compiler to perform specific


mathematical or logical manipulations.​

●​ The sources give examples of operators:​

○​ 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.

3. Explain nested if else structure with an example.

●​ A nested if statement is an if or else if statement inside another if


or else if statement.
●​ Nested if...else statements allow for more complex conditional
checks. The syntax for a nested if statement is:
if( boolean_expression 1) {
// Executes when the boolean expression 1 is true
if(boolean_expression 2) {
// Executes when the boolean expression 2 is true
}
}

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

4. Explain for loop with its syntax.

For Loop

●​ A for loop is a repetition control structure that allows you to


efficiently write a loop that needs to execute a specific number of
times.

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.

6. What are Assignment operators? explain with the help of examples.


Assignment operators are used to assign values to variables. The basic
assignment operator is = which assigns the value on the right to the
variable on the left. C++ also provides shorthand arithmetic assignment
operators.

Examples of assignment operators:

●​ =: Simple assignment operator. Assigns the value of the right-side


operand to the left-side operand. For example, a = 5 assigns the
value 5 to the variable a.
●​ +=: Add and assign operator. It adds the right operand to the left
operand and assigns the result to the left operand. For example, a +=
5 is equivalent to a = a + 5.
●​ -=: Subtract and assign operator. It subtracts the right operand from
the left operand and assigns the result to the left operand. For
example, a -= 5 is equivalent to a = a - 5.
●​ *=: Multiply and assign operator. It multiplies the right operand
with the left operand and assigns the result to the left operand. For
example, a *= 5 is equivalent to a = a * 5.
●​ /=: Divide and assign operator. It divides the left operand by the
right operand and assigns the result to the left operand. For
example, a /= 5 is equivalent to a = a / 5.
●​ %=: Modulus and assign operator. It takes modulus using the left and
right operands and assigns the result to the left operand. For
example, a %= 5 is equivalent to a = a % 5.

8. What do you mean by term precedence and associativity? The following


points present an explanation of precedence and associativity:

●​ Precedence: Refers to the priority or order in which operators are


evaluated in an expression. Operators with higher precedence are
evaluated before operators with lower precedence. Parentheses can
override the default precedence.​

●​ Associativity: Determines the direction in which operators of the


same precedence are evaluated in an expression. Operators with the
same precedence are evaluated according to their associativity
(left-to-right or right-to-left).​

For example:

●​ int x = 5 - 17 * 6; Here, the multiplication operator * is of higher


precedence than the subtraction operator -. Hence, 17 * 6 is
evaluated first.
●​ int x = (5 - 17) * 6; Use of parentheses to evaluate 5 - 17 first.

9. explain a do-while loop with an example. The following points explain


the do-while loop:
●​ A do-while loop is a control flow statement that executes a block of
code at least once, and then repeatedly executes the block, or not,
depending on a condition at the end of the loop.​

●​ Syntax: do { statement(s); } while( condition );​

●​ Execution: The do-while loop checks its condition at the bottom of


the loop. The statement(s) in the loop execute once before the
condition is tested. If the condition is true, the flow of control
jumps back up to do, and the statement(s) in the loop execute again.
This process repeats until the given condition becomes false.​

●​ The key feature of a do-while loop is that it is guaranteed to


execute at least one time.​

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:

●​ A binary operator is an operator that requires two operands to


perform an operation. These operators perform various arithmetic,
logical, and bitwise operations.​

●​ Types of Binary Operators:​


○​ Arithmetic Operators: These operators perform mathematical
calculations such as addition, subtraction, multiplication, and
division. Examples: +, -, *, /, %.
○​ Relational Operators: These operators determine the
relationship between two operands, such as equality,
inequality, greater than, or less than. Examples: ==, !=, >, <,
>=, <=.
○​ Logical Operators: These operators perform logical operations
such as AND, OR, and NOT (though NOT is typically a unary
operator). Examples: && (logical AND), || (logical OR).
○​ Assignment Operators: Assign a value to a variable. Example: =.
○​ Bitwise Operators: Perform operations on the individual bits of
the operands.
●​ Example:​

#include <iostream>
●​ using namespace std;
●​
●​ int main() {
●​ int a = 10;
●​ int b = 5;
●​ int sum = a + b; // '+' is a binary operator
●​ int product = a * b; // '*' is a binary operator
●​
●​ cout << "Sum: " << sum << endl; //Output: Sum: 15
●​ cout << "Product: " << product << endl; //Output: Product: 50
●​
●​ if (a > b) { // '>' is a binary operator
●​ cout << "a is greater than b" << endl; //Output: a is
greater than b
●​ }
●​
●​ return 0;
●​ }
●​ In this example, +, *, and > are binary operators because they
operate on two operands (a and b). The + operator adds a and b, the *
operator multiplies a and b, and the > operator checks if a is
greater than b.

10.explain the for loop with an example. The following points explain the
for loop:

●​ A for loop is a repetition control structure that allows you to


efficiently write a loop that needs to execute a specific number of
times.
●​ Syntax: for ( init; condition; increment ) { statement(s); }
○​ init: The init step is executed first, and only once. This step
allows you to declare and initialise any loop control
variables. You are not required to put a statement here, 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 the flow of control jumps to the
next statement just after the for loop.
○​ increment: After the body of the for loop executes, the flow of
control jumps back up to the increment statement. This
statement allows you to update any loop control variables. This
statement can be left blank, as long as a semicolon appears
after the condition.

Example:​
#include <iostream>

using namespace std;

int main() {

for (int i = 1; i <= 5; i++) {

cout << "Value of i: " << i << endl;

return 0;

●​ In this example, the loop initialises i to 1, continues as long as i


is less than or equal to 5, and increments i after each iteration.

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>

using namespace std;

int main() {

int a = 5;

int b = 10;

if (a > 0 && b < 20) {

cout << "Both conditions are true" << endl;

return 0;

○​ In this example, the message "Both conditions are true" is


printed because both a > 0 and b < 20 are true.
●​ Logical OR (||):​

○​ The logical OR operator || returns true (1) if at least one of


the operands is true (non-zero). It returns false (0) only if
both operands are false (0).

Example:​
#include <iostream>

using namespace std;

int main() {

int a = -1;

int b = 10;
if (a > 0 || b < 20) {

cout << "At least one condition is true" << endl;

return 0;

○​ In this example, the message "At least one condition is true"


is printed because b < 20 is true, even though a > 0 is false.

14. explain the concept of the goto statement. The following points explain
the goto statement:

●​ A goto statement provides an unconditional jump from the goto to a


labelled statement in the same function.

Syntax:​
goto label;

...

label: statement;

●​ Where label is an identifier that identifies a labelled statement. A


labelled statement is any statement that is preceded by an identifier
followed by a colon (:).

Example:​
#include <iostream>

using namespace std;

int main() {

int age = 15;

if (age < 18) {

goto notEligible;

cout << "Eligible to vote" << endl;

notEligible:

cout << "Not eligible to vote" << endl;

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:

●​ The purpose of the comma operator is to string together several


expressions.
●​ The value of a comma-separated list of expressions is the value of
the right-most expression.
●​ Essentially, the comma's effect is to cause a sequence of operations
to be performed.

Example:​
#include <iostream>

using namespace std;

int main() {

int i, j;

i = (j = 10, j + 100, 999 + j);

cout << i << endl; // Output: 1009

return 0;

●​ In this example, j is first assigned 10, then j + 100 is evaluated,


and finally, 999 + j is evaluated, and its result (1009) is assigned
to i.

16. explain Shorthand Arithmetic Assignment Operators with examples. The


following explains shorthand arithmetic assignment operators:

●​ Shorthand arithmetic assignment operators provide a concise way to


perform an arithmetic operation and assign the result to a variable
in a single step.
●​ Common Shorthand Operators:
○​ += (Addition assignment): x += y is equivalent to x = x + y.
○​ -= (Subtraction assignment): x -= y is equivalent to x = x - y.
○​ *= (Multiplication assignment): x *= y is equivalent to x = x *
y.
○​ /= (Division assignment): x /= y is equivalent to x = x / y.
○​ %= (Modulus assignment): x %= y is equivalent to x = x % y.

Example:​
#include <iostream>
using namespace std;

int main() {

int a = 10;

a += 5; // a = a + 5; a is now 15

cout << "a += 5: " << a << endl;

a -= 3; // a = a - 3; a is now 12

cout << "a -= 3: " << a << endl;

a *= 2; // a = a * 2; a is now 24

cout << "a *= 2: " << a << endl;

a /= 4; // a = a / 4; a is now 6

cout << "a /= 4: " << a << endl;

a %= 5; // a = a % 5; a is now 1

cout << "a %= 5: " << a << endl;

return 0;

●​ These operators modify the variable on the left by performing the


specified arithmetic operation with the value on the right.

17. explain the Ternary operator with the help of an example. The following
explains the ternary operator:

●​ The conditional operator (? :) is a ternary operator, meaning it


takes three operands. It provides a concise way to express
conditional expressions.
●​ Syntax: condition ? expression1 : expression2;
○​ If the condition is true (non-zero), expression1 is evaluated
and its result is returned.
○​ If the condition is false (0), expression2 is evaluated and its
result is returned.

Example:​
#include <iostream>

using namespace std;

int main() {

int age = 20;

string status = (age >= 18) ? "Eligible to vote" : "Not eligible


to vote";

cout << status << endl; // Output: Eligible to vote

return 0;

●​ In this example, the ternary operator checks if age is greater than


or equal to 18. If it is, the variable status is assigned the string
"Eligible to vote"; otherwise, it is assigned "Not eligible to vote".

UNIT-3

Q-1 Fill in the Blanks

1.​Function header + Function body = Definition


2.​The first line consists of return type, function name, and arguments
declaration enclosed within a pair of parentheses is called Function
Header
3.​Compile-time polymorphism is also called early binding or Static
Binding
4.​A Reference variable is an alias to an existing variable.
5.​Scope resolution operator resolves disputes in local and global
variables with the same name.
6.​An Array is used to store a collection of data of the same type.
7.​An array with more than one script is known as a Multidimensional
array.
8.​Single/One Dimensional type of array has a single index value to
represent the arrays element.
9.​The array index always starts with 0.
10.​
The signature of a function is also known as Function Prototype.
11.​
To inline a function, place the keyword inline before the function
name and define the function before any calls are made to the
function.
12.​
C++ allows you to specify more than one definition for a function
name in the same scope, which is called Function Overloading.
13.​
There are two ways to overload the method in C++
○​ By changing Type of arguments or parameters
○​ By changing the Number
14.​
A Default argument is a value provided in a function declaration that
is automatically assigned by the compiler if the caller of the
function doesn’t provide a value for the argument with the default
value.
15.​
A function that calls itself is known as a recursive function, and
this technique is known as Recursion.
16.​
Void datatype is used to represent the absence of parameters.
17.​
The function declaration statement must end with a semicolon.
18.​
The inline function is used when the function is small. Note, this
answer is not directly stated in the sources, but it is the most
likely answer.
19.​
The default value for parameters is assigned in function declaration.

Q-2 True or False

1.​A function which invokes another function is called a calling


function. True
2.​A function returns a float value by default. False
3.​Function overloading is also termed function polymorphism. True
4.​All the elements of arrays consist of contiguous memory locations.
True
5.​One-dimensional arrays are used to store matrix data. False
6.​If a function is inline, the compiler places a copy of the code of
that function at each point where the function is called at compile
time. True
7.​The compiler can ignore the inline qualifier in case the defined
function is more than a line. True
8.​The compiler can ignore the request for inlining if a function is
recursive. True
9.​The compiler can ignore the request for inlining if a function
contains a switch or goto statement. True
10.​
The compiler can ignore the request for inlining if a function return
type is other than void, and the return statement doesn’t exist in
the function body. True
11.​
The compiler can ignore the request for inlining if a function
contains static variables. True
12.​
For an inline function, function call overhead doesn’t occur. True
13.​
An inline function also saves the overhead of push/pop variables on
the stack when the function is called. True
14.​
An overloaded declaration is a declaration that had been declared
with the same name as a previously declared declaration in the same
scope, except that both declarations have different arguments and
obviously different definition (implementation). True
15.​
State whether the following definitions are valid for function
overloading or not. int test() { } int test(int a) { } float
test(double a) { } int test(int a, double b) { }. True
16.​
For the default argument concept, only the last argument must be
given a default value. A default argument cannot be followed by a
non-default argument. True
17.​
State whether the following declarations for default argument are
valid or not. sum (int x,int y=0); sum (int x,int y=0,int z); sum
(int x,int y=10,int z=10); void sum (int, int=0); void add(int a, int
b = 3, int c, int d = 4); void add(int a, int b = 3, int c, int d);
add(int a, int b, int c, int d = 4). False
18.​
One can give any value a default value to argument, compatible with
its data type. True
19.​
When arguments in a function are declared without any identifier,
they are called placeholder arguments. True
20.​
State whether the following declarations for array are valid or not:
int x; int x1[]={1,2,3,4,5,6,7,8,9}; int
x2[]={{1,2,3},{4,5,6},{7,8,9}}; int x3={0};. False
21.​
Can Function return array. True
22.​
Following statement is valid or not: int[] add_array(int x[],int
y[]). False
23.​
Following statement is valid or not: void add_array(int[] x,int[] y).
False
24.​
Column size must be passed in function declaration when passing a
double dimension array as an argument. True
25.​
The idea behind a default argument is simple. If a function is called
by passing argument/s, those arguments are used by the function. But
if the argument/s are not passed while invoking a function then, the
default values are used. True

Q-3 Define follwing words in one line:


1.​Inline: Inline is a keyword placed before a function name to request
the compiler to insert the function's code directly at the calling
point, potentially improving performance.
2.​Default Argument: A default argument is a value provided in a
function declaration that the compiler automatically assigns if the
caller doesn't provide a value for that argument.
3.​Function Overloading: Function overloading is when multiple functions
in the same scope share the same name but have different parameters.
4.​Array: An array stores a fixed-size sequential collection of elements
of the same type.
5.​Index: An index is used to access a specific element within an array.
6.​Subscript: The source does not explicitly define "subscript," but
based on the context of arrays, a subscript is synonymous with an
index, used to access array elements.
7.​Multidimensional Array: A multidimensional array is an array with
more than one index to represent the array's elements.
8.​Recursion: Recursion is a technique where a function calls itself.
9.​Return Statement: The source does not explicitly define "return
statement," but based on general programming knowledge, a return
statement is a statement that ends the execution of a function and
returns a value to the caller.
10.​
Function: The source does not explicitly define "function," but based
on general programming knowledge, a function is a block of code
designed to perform a specific task, which can be called multiple
times from different parts of a program.

Q-4 Answer the following questions:

1. What is a Function? Explain the advantages of functions.

●​ A function is a group of statements that together perform a task.


Every C++ program has at least one function, which is main().
●​ Advantages of Functions:
○​ Functions promote code reusability, allowing the same function
to be run multiple times without rewriting the code.
○​ Functions aid in program modification. Changes can be made
within a function without altering the overall program
structure.
○​ Using functions saves memory space when the same code is used
multiple times.
○​ Functions organise the program by dividing it into subprograms
or modules that can be used separately when needed.
○​ Functions facilitate teamwork in larger projects by dividing
the project into modules among programmers.
○​ Functions make it easier to identify errors, simplifying
testing and debugging.

2. List and explain the classification of functions in detail.

●​ Functions can be categorised into two types:


○​ Built-in functions: These are part of the C++ library.
○​ User-defined functions: These are written by the user to solve
a problem, offering flexibility in code development.
●​ Functions can be classified into four categories:
○​ Function with no argument and no return value: This function
does not send or return any data to its calling point.
○​ Function with no argument but return value: This function does
not receive arguments but returns data to where it was called.
○​ Function with argument but no return value: This function
receives arguments but does not return any data.
○​ Function with argument and return value: This function sends
and returns data to its calling point.

3. Differentiate between a built-in function and a user-defined


function with an example.

●​ 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;

○​ This is a user-defined function that adds two integers.

4. What do you mean by function header and function call? Explain.

●​ 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.

5. Differentiate calling function and called function.

●​ 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.

6. Explain the concept of recursion with an example.


●​ Recursion:
○​ Recursion is a technique where a function calls itself to solve
a problem.
○​ Each recursive call breaks the problem into smaller subproblems
until a base case is reached, which stops the recursion.

Example:​
int factorial(int n) {

if (n == 0) // Base case

return 1;

else

return n * factorial(n - 1); // Recursive call

○​

7. What is an inline function? Explain its significance.

●​ 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;

double add(double a, double b) {

return a + b;

○​

9. Explain how to pass a Single Dimension array to functions with an


example.

●​ To pass a single-dimension array to a function:


○​ Declare the function with the array name as a parameter,
specifying the data type and optionally the size of the array.
○​ The function receives an integer pointer.
○​ Syntax: returnType functionName(dataType arrayName[arraySize]).

Example:​
void display(int m) { // Function declaration

cout << "Displaying marks: " << endl;


for (int i = 0; i < 5; ++i) {

cout << "Student " << i + 1 << ": " << m[i] << endl;

int main() {

int marks = {88, 76, 90, 61, 69};

display(marks); // Function call

return 0;

○​

10. Explain types of arrays with an example.

●​ Single / One-Dimensional Arrays:


○​ An array with a single index value to represent its elements.
○​ Syntax: type array_name[array_size].
○​ Example: int Age.
●​ Two / Multi-Dimensional Arrays:
○​ An array with multiple dimensions.
○​ Syntax: type name[size1][size2]...[sizeN].
○​ Example: int threedim.
○​ The simplest form is the two-dimensional array: type
arrayName[x][y].

Example:​
int a = {

{0, 1, 2, 3}, /* initializers for row indexed by 0 */

{4, 5, 6, 7}, /* initializers for row indexed by 1 */


{8, 9, 10, 11} /* initializers for row indexed by 2 */

};

○​

11. Explain the syntax of declaring and initializing an array.

●​ 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}.

12. Explain how to pass a Double Dimension array to functions with an


example.

●​ To pass a two-dimensional array to a function:


○​ The column size must be passed in the function declaration.

Example:​
void display(int n[]) { // Function declaration

cout << "Displaying Values: " << endl;

for (int i = 0; i < 3; ++i) {

for (int j = 0; j < 2; ++j) {

cout << "num[" << i << "][" << j << "]: " << n[i][j] <<
endl;

}
int main() {

int num = {

{3, 4},

{9, 5},

{7, 1}

};

display(num); // Function call

return 0;

○​

13. Explain the concept of a default argument in C++.

●​ 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

Below is the comprehensive solution to the C++ Unit 4 theory assignment


with all code examples removed. The original answers remain unchanged; for
learning the detailed code implementations, please ask ChatGPT for the code
explanation.
Q.1 Fill in the Blanks

1.​Variables of a class are called data members.


2.​Private members are class members that are hidden from the outside
world.
3.​The class written within another class is called the nested class.
4.​:: is known as the scope resolution operator.
5.​Object is an instance of a class.
6.​The function declared inside the class is known as a member function.
7.​The this pointer is an implicit parameter to all member functions.
8.​Friend functions do not have a this pointer because friends are not
members of a class.
9.​A friend function of a class is defined outside that class' scope but
it has the right to access all private and protected members of the
class.
10.​
A static member is shared by all objects of the class.
11.​
The static functions are accessed using only the class name and the
scope resolution operator (::).
12.​
Static member functions can only access static members.
13.​
The combination of inner and outer classes is known as a nested
class.
14.​
To declare a structure, the structure keyword is used.
15.​
The members of a class are accessed using the dot (.) operator.
16.​
A class is a blueprint for objects.
17.​
The static function can be invoked without the help of an object.
18.​
Constant member functions cannot change the value of a variable.
19.​
This pointer is a constant pointer.

Q.2 State Whether the Following Statements Are True or False

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.

Q.3 Questions and Answers

1.​What is a friend function? Give its characteristics.​

○​ A friend function is a non-member function that can access the


private and protected members of a class.​
Characteristics:
■​ It is not a member of the class.
■​ It is declared using the friend keyword inside the class.
■​ It can access private and protected members of the class.
■​ It is not in the scope of the class.
■​ It cannot be called using an object of the class.
■​ It can be invoked like a normal function without the help
of an object.
■​ It can have objects as arguments.
2.​What is a friend class? Explain with an example.​

○​ A friend class is a class that has access to the private and


protected members of another class. If class B is a friend of
class A, then class B can access the private and protected
members of class A. Note that friendship is not inherited, not
reciprocal, and not transitive.​
For a detailed code example, please ask ChatGPT for the code
explanation.
3.​Explain how to create a nested class with an example.​

○​ A nested class is a class declared inside another class. It is


useful for logically grouping classes that are closely related.
The nested class does not have direct access to the
private/protected members of the outer class unless declared as
a friend.​
For a detailed code example, please ask ChatGPT for the code
explanation.
4.​Explain how to create a nested function with an example.​

○​ 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.​

○​ Objects can be passed to functions either by value (which


creates a copy) or by reference (which allows the function to
modify the original object).​
For a detailed code example, please ask ChatGPT for the code
explanation.
7.​How to return an object from a function, explain in detail with an
example.​

○​ A function can return an object by simply using the return


statement to return an object of the class.​
For a detailed code example, please ask ChatGPT for the code
explanation.
8.​Explain the concept of a static member function with an example.​

○​ A static member function is independent of any particular


object of the class. It is called using the class name and can
only access static data members or other static member
functions.​
For a detailed code example, please ask ChatGPT for the code
explanation.
9.​What is an access specifier? List and explain the types of access
specifiers.​

○​ Access specifiers define the access level for class members


(variables and functions).
■​ Public: Members are accessible from anywhere outside the
class.
■​ Private: Members are accessible only within the class.
■​ Protected: Members are accessible within the class and
its derived classes.
10.​
Explain the Characteristics of Access Specifiers.​

○​ Public: Accessible from anywhere and provides the interface to


the class.
○​ Private: Accessible only within the class, ensuring data hiding
and encapsulation.
○​ Protected: Accessible within the class and its derived classes,
facilitating inheritance.


Explain the significance of the this pointer.​

○​ The this pointer is a constant pointer that holds the memory


address of the current object. It enables an object to refer to
itself, differentiate between member variables and local
variables with the same name, and access the object for which
the member function was called.
11.​
Explain the usage of the :: operator with an example.​

○​ The :: (scope resolution) operator is used to access


identifiers (variables, functions, classes) in different
scopes. It can be used to access a global variable when a local
variable with the same name exists, to access static members of
a class, or to define a member function outside the class
definition.​
For a detailed code example, please ask ChatGPT for the code
explanation.
12.​
What is a class? Explain the characteristics of a class.​
○​ A class is a user-defined data type that encapsulates its own
data members and member functions. It serves as a blueprint for
creating objects.​
Characteristics include:
■​ Data Abstraction: Hiding internal details and exposing
only essential features.
■​ Encapsulation: Bundling data and functions together.
■​ Inheritance: Ability to create new classes from existing
ones.
■​ Polymorphism: Ability of an object to take on many forms.
13.​
What is a Structure? Explain the limitations of structure.​

○​ A structure is a user-defined data type that can hold variables


of different data types.​
Limitations include:
■​ Lack of Data Hiding: Members are public by default,
providing less data security.
■​ Limited Encapsulation: Structures focus mainly on data
without strong encapsulation.
■​ No Inheritance: Structures do not support inheritance in
the same way as classes.
14.​
Explain the concept of a constant member function.​

○​ Constant member functions are functions that are not allowed to


modify any data members of the class. They are declared with
the const keyword after the function’s parameter list.
15.​
Explain the concept of a static data member with an example.​

○​ A static data member is shared among all objects of a class.


There is only one copy of the member regardless of the number
of objects, and it is typically initialized outside the class
definition using the scope resolution operator.​
For a detailed code example, please ask ChatGPT for the code
explanation.
For further clarification or to see full code examples for any of the above
topics, please ask ChatGPT for the code explanation.

Here's a detailed solution to the C++ Unit 5 Theory Assignment, based on


the provided sources:

Q.1 Fill in the Blanks:

●​ Dynamic allocation of memory is done by the new operator.


●​ A constructor that takes no argument is known as a default
constructor.
●​ Memory once allocated is released using the delete operator.
●​ The maximum number of arguments that can be passed to a destructor
function is zero.
●​ Copy constructor is used to make a copy of one class object from
another class object of the same class type.
●​ A constructor that accepts no parameters is called the default
constructor.
●​ A destructor has the same name as the constructor and it is preceded
by a tilde (~) sign.
●​ Constructors are used to initialise the objects of a class.
●​ A function with the same name as the class, but preceded with a tilde
character (~) is called the destructor of that class.

Q.2 State whether the following statements are True or False.

●​ Constructors can be overloaded. True.


●​ A destructor can have a return type. False.
●​ A constructor with no argument is called a parameterized constructor.
False. A constructor with no arguments is a default constructor.
●​ In dynamic allocation, memory is allocated at runtime. True.
●​ Dynamic allocation of memory is done by the new operator. True.
●​ Can a constructor return a value? False.
●​ Can we define a constructor outside of the class like a member
function? Yes.
●​ Can constructors be declared in the private section of the class?
Yes.
●​ Constructors and destructors should be public members. True.
●​ We can have multiple constructors in a class. True. This is
constructor overloading.
●​ Constructors are used to initialise objects while they are declared.
True.

Q.3 Questions and Answers:

1. How do you dynamically allocate memory in C++?

●​ In C++, dynamic memory allocation is done using the new operator.


●​ It involves allocating memory manually during runtime.
●​ Memory is allocated on the heap, which is managed by the programmer
using pointers.
●​ The new operator allocates the requested memory and returns a pointer
to the beginning of the allocated block.

2. How do you dynamically deallocate memory in C++? Explain with syntax.

●​ Dynamic memory deallocation is done using the delete operator.


●​ It releases the memory that was previously allocated dynamically.
●​ Syntax:
○​ For single objects: delete pointer_variable;
○​ For arrays: delete[] pointer_variable;
●​ It's crucial to deallocate memory to prevent memory leaks.

3. What is a constructor? Explain its characteristics.

●​ A constructor is a special member function of a class that is


automatically called when an object of that class is created.​

●​ It is used to initialise the objects of the class.​

●​ The constructor has the same name as the class.​


●​ If no constructor is explicitly defined, the compiler provides a
default constructor.​

●​ Characteristics:​

○​ Automatically called when an object is created.


○​ Has the same name as the class.
○​ No return type (not even void).
○​ Can be overloaded.
○​ Used to initialise data members of the object.
○​ If not defined explicitly, the compiler provides a default
constructor.

4. Explain with examples what are constructors and destructors.

●​ Constructor:​

○​ A special member function to initialise objects.


○​ Example:

class Example {

public:

int x;

// Constructor

Example() {

x = 0;

cout << "Constructor called" << endl;

};

●​
●​ Destructor:​

○​ A special member function to destroy objects.


○​ Called automatically when an object goes out of scope.
○​ Example:

class Example {

public:

// Destructor

~Example() {

cout << "Destructor called" << endl;

};

●​

5. List and explain the types of constructors

●​ Default Constructor: A constructor with no arguments.


●​ Parameterized Constructor: A constructor with arguments.
●​ Copy Constructor: A constructor that creates a new object as a copy
of an existing object.
●​ Dynamic Constructor: Used to allocate memory dynamically using new.
●​ Overloading Constructor: Having multiple constructors with different
parameters.

6. Explain the default constructor in detail.

●​ A default constructor is a constructor that takes no arguments.


●​ If no constructor is defined, the compiler automatically creates a
default constructor.
●​ It is used to initialise objects with default values.

7. What is a parameterized constructor, explain in detail with example


●​ A parameterized constructor is a constructor that accepts arguments.
●​ It allows initialising the object with specific values during
creation.
●​ Example:

class Student {

public:

int id;

string name;

// Parameterized Constructor

Student(int i, string n) {

id = i;

name = n;

};

8. Explain copy constructor in detail with example.

●​ A copy constructor is used to create a new object by copying the data


from an existing object of the same class.​

●​ Example:​

class Point {

private:

int x, y;

public:
Point(int x1, int y1) { x = x1; y = y1; }

// Copy constructor

Point(const Point &p) {x = p.x; y = p.y;}

int getX() { return x; }

int getY() { return y; }

};

int main() {

Point p1(10, 15); // Normal constructor

Point p2 = p1; // Copy constructor

cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY() << endl;

cout << "p2.x = " << p2.getX() << ", p2.y = " << p2.getY() << endl;

return 0;

10. Justify: When is the destructor called?

●​ The destructor is automatically called when an object is no longer


needed.
●​ This typically happens when:
○​ The object goes out of scope.
○​ The program ends.
○​ delete is used on a dynamically allocated object.

11. Define Dynamic Constructor with example.

●​ A dynamic constructor is used when memory allocation is done


dynamically using the new operator inside the constructor.
●​ It's used to dynamically initialise objects.

Example:

class DynamicArray {

private:

int *arr;

int size;

public:

// Dynamic Constructor

DynamicArray(int s) {

size = s;

arr = new int[size]; // Allocating memory dynamically

~DynamicArray() {

delete[] arr; // Freeing dynamically allocated memory

};

You might also like