Xii Computer Sci Notes
Xii Computer Sci Notes
ANUM NISA 1
COMPUTER SCIENCE (XII)
Mac has better integration with other Apple products, such as iPhones and iPads. Mac
is known for its powerful hardware and fast speed.
Disadvantages:
Mac is usually more expensive than Windows computers.
There is less software and games for Mac, because Windows is the most used operating
system.
8. Write any three advantages of using Linux/Unix OS.
Multi-User, Multi-Tasking: Unix supports simultaneous access for multiple users and allows
multiple processes to run simultaneously, enhancing system efficiency.
Robust Security: Unix features robust security measures like file permissions and encryption,
providing protection against unauthorized access and malware.
Reliability: Unix is known for its stability and reliability, minimizing system crashes and
ensuring continuous operation, particularly in high-performance computing environments
requirement.
9. Describe one key feature of the Windows operating system that distinguishes it from
other operating systems.
One key feature of the Windows operating system is its support for a wide range of hardware
devices and peripherals. Windows provides built-in drivers and compatibility support for a
variety of hardware components, making it easy for users to install and use new devices with
their computer system.
10. Why window is known as GUI interface?
Windows is known as a GUI (Graphical User Interface) interface because it provides users with
visual elements such as windows, icons, menus, and pointers (WIMP) to interact with the
operating system and applications. Instead of relying solely on text-based commands, users
can perform tasks by clicking icons, selecting options from menus, and dragging objects using
a mouse or other pointing device.
11. Differentiate between DOS and Windows Operating System.
ANUM NISA 2
COMPUTER SCIENCE (XII)
12. How does batch operating system differ from other interactive operating systems? A
batch operating system processes jobs in batches without user interaction. It collects similar
tasks or jobs, executes them sequentially, and requires minimal user involvement. In contrast,
interactive operating systems allow users to interact with the system in real-time, providing
immediate feedback and response to user input.
13. What are the advantages and disadvantages of batch processing in operating systems?
Advantages of batch processing includes:
• improved resource utilization
• reduced system idle time
• simplified management of repetitive tasks. Dis Advantages of batch processing
includes:
Enhanced System Efficiency: These systems optimize resource usage, minimizing idle time
and improving overall system performance through simultaneous execution of multiple
programs.
ANUM NISA 3
COMPUTER SCIENCE (XII)
ANUM NISA 4
COMPUTER SCIENCE (XII)
Increased reliability: Multiprocessor systems can continue to operate even if one processor
fails, as the remaining processors can continue to execute tasks.
Better scalability: Multiprocessor systems can be scaled more easily than single-processor
systems, as additional processors can be added to the system to handle increased workloads.
20. Write disadvantages of multiprocessing operating system.
Increased complexity: Multi processing systems are more complex than single-processor
systems, and they require additional hardware, software, and management resources.
Higher power consumption: It require more power to operate than single- single-processor
systems, which can increase the cost of operating and maintaining the system.
Difficult programming: Developing software that can effectively utilize multiple processors
can be challenging, and it requires specialized programming skills.
Definition Designed for use by a single user at a Designed to support multiple users
time. accessing the system simultaneously.
User Interaction Typically provides a single user Provides multiple user interfaces,
interface for interaction with the allowing multiple users to log in and
system. work concurrently.
Resource Resources are dedicated to a single Resources are shared among multiple
Management user so management is easy. users, with the operating system
managing access and allocation.
ANUM NISA 5
COMPUTER SCIENCE (XII)
ANUM NISA 6
COMPUTER SCIENCE (XII)
ANUM NISA 7
COMPUTER SCIENCE (XII)
New:
The process is being created but has not yet been admitted to the system. This state occurs
when the process is initiated by the user or another process.
Ready:
The process is ready to execute and is waiting for CPU time. It has been loaded into main
memory and is waiting in the ready queue to be dispatched by the CPU scheduler.
ANUM NISA 8
COMPUTER SCIENCE (XII)
Running:
The process is currently being executed by the CPU. It is actively performing its tasks, and its
instructions are being executed.
Waiting (Blocked):
The process is waiting for some event to occur, such as an I/O operation to complete, a signal
from another process, or a resource to become available. It is temporarily blocked and not
ready to execute.
Terminated (Exit):
The process has completed its execution or has been terminated by the operating system or
another process. It is removed from memory, and its resources are deallocated.
35. Differentiate between process and thread along with one example of each.
Process Thread
ANUM NISA 9
COMPUTER SCIENCE (XII)
Chapter#2 SDLC
1. Write the importance/purpose of the system development life cycle.
The basic purpose of SDLC is to develop a system in systematic way in the perfect
manner.
• SDLC ensures quality assurance through clear requirements, design specifications,
and testing procedures.
• It facilitates risk management by identifying potential challenges early.
• Effective resource management is achieved by allocating personnel, time, and
budget efficiently.
• Communication and collaboration among stakeholders are promoted throughout the
development process.
ANUM NISA 1
0
COMPUTER SCIENCE (XII)
ANUM NISA 1
1
COMPUTER SCIENCE (XII)
The purpose of the Design Phase is to transform the requirements into detailed system
design specifications. The developers create the high-level design/ logical structure of
overall project that can be implemented in programming language. This phase also defines
the ways through which user can interact with the system.
Flowchart:
ROLE OF TESTING/ VERIFICATION PHASE (at least any three valid points)
• Testing/ verification phase in SDLC examines the system for functionality and quality
by
• discovering problems and errors.
• It evaluates the capabilities of code/programs.
• It helps to verify proper integration and interaction of each component in the system.
• It helps in reviewing of requirements, design, and code.
• It helps in identifying defects and ensuring they are addressed before system
deployment.
• It also plays important role in lowering the maintenance cost of the system.
7. Which phase of SDLC is used to find the strength and weaknesses of system being
developed?
A feasibility study is used to find the strength and weaknesses of system.
It is conducted in order to objectively uncover the strengths and weaknesses (SWOT
Analysis). A SWOT analysis is used to study the internal and external environments of a
company and is part of a company’s strategic planning process. It can help to identify and
assess the opportunities and threats present in the natural environment, the resources
required for the project, and the prospects for success.
It is conducted in order to find answers to the following questions:
Does the company possess the required resources and technology?
Will the company receive a sufficiently high return on its investment?
A feasibility report should include the following sections:
• Description of the Product/Service
• Technology Considerations
• Product/ Service
• Marketplace
• Identification of the Specific Market
• Marketing Strategy
• Organizational Structure
ANUM NISA 1
2
COMPUTER SCIENCE (XII)
• Schedule
• Financial Projections
8. What is the purpose of requirement engineering? Differentiate between the two main
types of requirements.
The purpose of requirement engineering is to systematically gather, analyze, document,
and validate the requirements of a software system to ensure that it meets the needs of
stakeholders and delivers the desired functionality and quality.
ANUM NISA 1
3
COMPUTER SCIENCE (XII)
ANUM NISA 1
4
COMPUTER SCIENCE (XII)
ANUM NISA 1
5
COMPUTER SCIENCE (XII)
Its main purpose is to provide a flexible and powerful tool for software development, combining
the efficiency of the C programming language with additional features for object-oriented
programming (OOP). C++ allows developers to write code that is both procedural and
objectoriented, enabling them to create modular, reusable software components while
maintaining control over system resources and performance.
2. Define computer program. Also differentiate between source code and object code. A
computer program is a set of instructions written in a programming language that directs a
computer to perform specific tasks or operations.
Header files in C++ are the files that contain information about definitions or declarations of
functions, classes, variables, constants, and other entities used in a program. These
declarations provide the interface or blueprint for these entities, allowing other parts of the
program to use them without needing to know their implementation details.
Each header file contains information about specific entity, e.g. <math.h> contains information
or code for performing mathematical functions such as finding square root of a number.
Header files typically have a ".h" extension and are included in source files using the #include
preprocessor directive.
4. Write the purpose of using preprocessor directives.
The preprocessor directive is used to include a header file at the beginning of program. A
preprocessor directive is not a normal program instruction to be executed by the CPU. It is a
code for the compiler to include a header file.
Normally two preprocessor directives (#inculde & #define) are used in C++.
The syntax of preprocessor directive to include a header file in a program is:
# include <name of header file>
It begins with a # sign, followed by the word include and then the name of header file is written
within angled brackets.
ANUM NISA 1
6
COMPUTER SCIENCE (XII)
The #define preprocessor directive creates symbolic constants. The symbolic constant is
called a macro and the general form of the directive is – #define macro-name replacement-
text
#define PI 3.14159
5. Differentiate between header file and preprocessor directives.
Ambiguity and Confusion: Using reserved words as variable names creates ambiguity and
confusion in code due to their predefined meanings in the language syntax, making it unclear if
they are intended as variables or have reserved significance.
Syntax Conflicts: The use of reserved terms as variable names may cause syntax issues.
The compiler may perceive the reserved word as part of the language syntax rather than a
variable name, resulting in compilation issues or unexpected behavior.
ANUM NISA 1
7
COMPUTER SCIENCE (XII)
Readability and Convention: Variable names should reflect the goal or meaning of the data
they represent, which improves code readability. Using reserved words as variable names is
against this standard and may make the code more difficult to understand.
7. Explain the basic structure of C++ program with the help of an example.
preprocessor directives void
main()
{
body of main() function
}
A C++ program starts with preprocessor directives, followed by the line void main function and
then the body of the main () function is written within curly brackets { }. Body of main() function
consists of executable statements. These statements perform a specific task when the
program is executed by the CPU. There is no restriction on the number of statements that can
be written in the body of the main () function.
To understand the structure of program, consider the following program.
# include <iostream.h> void
main()
{
cout<<"Information Technology";
}
Explanation:
#include<iostream.h> a preprocessor directive. This program prints a message on the
screen. Therefore, iostream.h header file is included which contains the code for performing
input/output operations.
void main ()
This line identifies the main function of the C++ program. All C++ programs must have main()
function. If a program consists of more than one function, the location of main() does not
matter. In C++ program the main () function is always executed first.
cout<<"Information Technology";
This is a C++ statement. The meaning of this statement is to print the message "Information
Technology" on the screen. This statement is written within the curly brackets and is called
body of the main () function.
8. Write the purpose of using statement terminators.
The "statement terminator" in C++ is a symbol that marks the end of a statement. In C++, the
semicolon “;” serves as the statement terminator. It is placed at the end of most statements to
indicate to the compiler that the current statement has ended. cout<<"Information
Technology";
The statement ends with a semicolon to marks its end. If “;” is missing the compiler will give
syntax error number and also the message that “;” is missing. The error number and message
may vary depending on the compiler used.
ANUM NISA 1
8
COMPUTER SCIENCE (XII)
9. Why is it important to write Comments in a program? Also differentiate its two types.
Comments are notes/ explanatory remarks used to document sections of a program. They are
intended for people who may be reading the source code. The readers can easily understand
the logic of the program by documented code.
1. Single-line comments
2. Multi-line comments
ANUM NISA 1
9
COMPUTER SCIENCE (XII)
In C++, data types are used to define the type of data that a variable can hold. They specify
the size and format of the data, as well as the operations that can be performed on it.
Here are some common data types in C++:
Integer Types:
int: Integer data type that can hold whole numbers.
short: Short integer data type, typically smaller than int. long:
Long integer data type, typically larger than int. unsigned int,
unsigned short, unsigned long: Unsigned integer types that
can only hold non-negative(positive) values.
Floating-Point Types:
ANUM NISA 2
0
COMPUTER SCIENCE (XII)
Different data types require different amounts of memory to store their values. By choosing an
appropriate data type, we can optimize memory usage and avoid unnecessary memory
wastage. e.g. datatype int takes 4 bytes of memory while char takes 1 byte of memory.
15. Draw the table for int datatype along with no. of bytes it occupied range of numbers.
Number of bytes reserved may vary depending on compiler (like turbo C++ reserves 2 bytes
for each integer element and Dev C++ reserves 4 bytes, both will be considered correct)
It is necessary to declare a variable before use in order to tell the compiler about the variable's
existence, data type, and memory allocation requirements. This allows the compiler to allocate
ANUM NISA 2
1
COMPUTER SCIENCE (XII)
memory for the variable and perform type checking to ensure that the variable is used
appropriately in the program.
Declaring variables before use helps prevent errors and ensures proper memory management
and type safety in the program.
Displaying Output:
To display output to the console, we can use the << operator with cout followed by the value
or variable we want to display.
ANUM NISA 2
2
COMPUTER SCIENCE (XII)
21. Write a C++ program that reads base and height of a triangle and displays its area by
using formula: area = ½ b h
#include <iostream>
using namespace std;
int main() {
// Declare variables to store base, height, and area
double base, height, area;
// Calculate the area of the triangle using the formula: area = 0.5 * base * height
area = 0.5 * base * height;
return 0;
}
22. The following C++ code has compile time errors. The line numbers are written along the
left column. They are not part of the program code. Identify and correct errors:
ANUM NISA 2
3
COMPUTER SCIENCE (XII)
ANUM NISA 2
4
COMPUTER SCIENCE (XII)
ANUM NISA 2
5
COMPUTER SCIENCE (XII)
25. Write the purpose of any three commonly used escape sequences in C++.
escape Function
Sequence
\ It moves the cursor to the start of the next line.
n
\t It moves the cursor to the next horizontal tabular position.
\\ Inserts a backslash character.
\ Inserts a double quote character.
"
\' Inserts a single quote character.
\ Moves the cursor back one position, effectively erasing the
b previous character.
a. endl:
Purpose: The use of the endl C++ manipulator is to move the cursor to the beginning of the
next line. Moreover, its working is similar to the '\n' escape sequence.
Example:
cout << "Hello, ";
cout << "world!" << endl; // Inserts a newline character and flushes the buffer cout <<
"Goodbye." << endl; Output:
Hello, world!
Goodbye.
b. setw():
ANUM NISA 2
6
COMPUTER SCIENCE (XII)
Purpose: The setw() manipulator is used to set the width of the next output field. It allows
formatting output by specifying the minimum width that the output should occupy, with
additional spaces added as padding if necessary.
Example:
#include <iostream>
#include <iomanip> // Needed for setw()
using namespace std; int main() {
cout << setw(10) << "Name:" << setw(20) << "ABC XYZ" << endl;
cout << setw(10) << "Age:" << setw(20) << 25 << endl; return 0;
}
Output:
Name: ABC XYZ
Age: 25
28. Write the purpose of commonly used header files.
ANUM NISA 2
7
COMPUTER SCIENCE (XII)
ANUM NISA 2
8
COMPUTER SCIENCE (XII)
+i; +;
Value of j j is assigned the value 6 . j is assigned the value 5 .
after
executio n
Value of i i is incremented 6 . i is incremented 6 .
after to to
executio n
Note: same can be used for decrement operators just by changing the context of
increase by one to decrease by 1.
32. Differentiate between relational and logical operators.
ANUM NISA 2
9
COMPUTER SCIENCE (XII)
Logical OR ( | | ) operator is required to determine, if count is outside the range of 0 through 100.
int x = 3, y = 17;
cout << x / y << y / x << (y / x) + (x % y);
Output:
058
35. Write down the output of the following statements.
i. (x > 0) && (y < 10) where x = 5, y = 5
ii. 13 + 21 % 4 – 2
iii. int m = 2, n = 4; m *= 2; n += m;
ANSWER
i. true/1 (5>0 && 5<10) -> (T && T) -> T
ii. 12 (13 + 1 – 2) -> (14-2) -> 12 iii.
m=4n=8
36. Compare unary, binary, and ternary operators with one example of each. Unary
Operator:
Unary operator takes single operand in an expression or statement and calculate the result.
Example: Increment operator (++), n++ Binary Operator:
Binary operator takes two operands in an expression or statement and calculate the result.
Example: Relational operator (>), a > b; Ternary Operator:
Ternary operator takes three operands in an expression or statement and calculate the result.
Example: Conditional operator (?:), (a < b) ? s = a : s=b;
37. Determine the output of the following code segment:
int i=2; cout
<<i; cout<<i++; cout <<+
+i; Output:
224
38. Write an expression to test each of the following relationships: (any three) a. age is from
18 to 25
b. temperature is less than 40.0 and greater than 25.0
c. year is divisible by 4 (Hint: use%)
d. speed is not greater than 80
e. y is greater than x and less than z
f. w is either equal to 6 or not greater than 3
ANUM NISA 3
0
COMPUTER SCIENCE (XII)
int main() {
char ch;
return 0; }
40. What will be the output of the following C++ program?
ANUM NISA 3
1
COMPUTER SCIENCE (XII)
void main ()
{ int a = 15, b;
b = a%9;
a = ++a-a(--b);
cout<<"a="<<a<<"b<<b<<endl; cout<<"a
now ="<<a++<<"b="<<b++<<endl;
cout<<"value of a="<<++a<<"value of
b="<<b<<endl; } OUTPUT:
1. b = a % 9;: The remainder of a divided by 9 is calculated and stored in
b. So, b becomes 6 (15 % 9 = 6).
2. a = ++a - a * (--b); --b decrements b to 5.
• ++a increments a to 16.
• a * (--b) multiplies the current value of a (16) by the decremented value of b (5), resulting in 80.
++a - 80 performs the subtraction (16 - 80), resulting in -64.
So, a becomes -64.
3. cout << "a=" << a << " b=" << b << endl;: Outputs: a=-64 b=5.
4. cout << "a now =" << a++ << " b=" << b++ << endl; Outputs the current
value of a (-64) and then increments a (-63).
Outputs the current value of b (5) and then increments b (6).
So, outputs: a now =-64 b=5.
5. cout << "value of a=" << ++a << " value of b=" << b << endl;
Increments a and outputs the incremented value (from -63 +1 to -62).
Outputs the current value of b (6).
So, outputs: value of a=-62 value of b=6
Therefore, the output of the given C++ program will be;
a=-64 b=5 a now =-64 b=5
value of a=-62 value of b=6
a. To get a numerical value from the keyboard and place it in the variable temp in C+
+, we can use the cin statement: int main() {
int temp; // Assuming temp is an integer variable
cout << "Enter a numerical value: "; cin >> temp;
return 0;
}
ANUM NISA 3
2
COMPUTER SCIENCE (XII)
b. To use setw() in a C++ program, we need to include the <iomanip> header file. So,
the header file required is <iomanip>:
ANUM NISA 3
3
COMPUTER SCIENCE (XII)
8.
• Evaluate the logical AND (&&) operator (Evaluate 21.3 && false)
• The expression 21.3 && false involves a logical AND operation between a non-zero
value (21.3, which is considered true in a Boolean context) and false.
• The result of a logical AND operation is false if any of the operands is false,
otherwise it is true.
• Therefore, the final result of the expression 10.0 + 15/2 + 4.3 && 5 > 8 is false.
Control structures are a very important concept in computer programming. Control structures
allow programmers to control the flow of program execution. Three types of control structures are
used in programming, sequential, conditional and repetition structures.
Sequential structure refers to execution of instructions one by one in the sequence in which they
appear in the program from top to bottom till the last instruction.
Iteration structure, also known as loop, refers to execution of same set of instructions several
times till a condition is met. E.g. for, while and do while loop.
2. Differentiate between if and if else statement.
Feature i Statement if- Statement
f else
Purpose Used when block of code Used when two codes of blocks need to
needs to be executed only if be executed, one if condition is true,
condition is true other if condition is false
Syntax if if
(condition) (condition)
{ code { code
block } block1 }
els
e
{ code
block2 }
Behavior Executes code block if Executes code block1 if condition is true,
condition is true executes code block2 if condition is false
ANUM NISA 3
4
COMPUTER SCIENCE (XII)
ANUM NISA 3
5
COMPUTER SCIENCE (XII)
Syntax: Syntax:
if (condition1) { // switch (expression/constant)
code block1 } else { case value1: // code block1 break;
if (condition2) { // case value2: // code block2 break;
code block2 } else default: // default code block
{ // code block3 } }
a. Switch code:
char ch; switch (ch)
{ case 'y':
cout << "Yes";
break;
case 'n': cout
<< "No";
break;
default:
ANUM NISA 3
6
COMPUTER SCIENCE (XII)
int main() {
float salary, allowance;
ANUM NISA 3
7
COMPUTER SCIENCE (XII)
cout << "Wer allowance is 25% of wer salary: " << allowance << endl;
}
return 0;
}
b. In this scenario, using the if-else selection structure is more appropriate because it allows us to
easily handle multiple conditions and select the appropriate activity based on the salary input.
Each condition checks a specific range of salary values and calculates the allowance
accordingly.
ANUM NISA 3
8
COMPUTER SCIENCE (XII)
Answer:
a)
Th
at
is
fu
nn
y
b)1
44
999
16 16 16 16
12. Convert the following while loop to a for loop:
count = 0;
while (count < 50)
{
cout << "count is " << count << endl;
count++;
}
Answer:
for (count = 0; count < 50; count++)
cout << "count is " << count << endl;
13. Write a do-while loop in C++ that asks the user to enter two numbers and display their
sum. The user should be asked to perform the operation again. If so, the loop should
repeat; otherwise, it should terminate.
enter two numbers: 20 50
sum = 70
Do we want to continue(Y/N))? Y
enter two numbers: 12 15 sum =
27
Do we want to continue(Y/N))? N Answer:
do
{
cout << "enter two numbers: ";
cin>>a>>b;
cout<< "sum = "<<a+b<<"\n"; cout <<
"Do we want to continue(Y/N))? ";
cin>>choice;
} while ( (choice = ='Y' ) || ( choice = =
'y' ) );
14. Write a C++ program that prints sum of squares of integers from 1 to 10.
ANUM NISA 3
9
COMPUTER SCIENCE (XII)
ANSWER
#include<iostream>
void main()
{
int i, sum=0,s;
for(i=1;i<=10;i++)
{
s=i*i;
sum+=s;
}
cout<<"\n Sum of square of integers = "<<sum;
}
15. Write a C++ code that prints sum of the following series: 1 2 + 3 2 + 5 2 + 7 2 + . . . . .
+ 992 #include <iostream> using namespace std;
int main() {
int sum = 0;
cout << "Sum of the series: " << sum << endl;
return 0;
}
16. Convert the following while loop to a for loop such that the output remains same.
int i = 20; while (i > 0)
{ cout << i << “\
t”; i = i - 2;
}
Answer:
for (int i = 20; i > 0; i = i - 2) {
cout << i << "\t";
}
17. Write down the output of the following program segment: char c = ‘A’; do
{
cout << c << ”\t”;
c = c + 2;
ANUM NISA 4
0
COMPUTER SCIENCE (XII)
}
while (c <= ‘K’ );
Answer:
The output of the following program segment will be:
A C E G I K
18.
a) How many times will the following
loop display "OK"? for (int i = 1; i<20; i++)
{
cout<<"OK”;
}
b) Rewrite the while loop as do-while
loop. int i = 1; while (i<=15) { cout<<"a";
i=i+1;
}
Answer:
a. The loop will
display "OK"
19 times. It
starts with i =
1 and iterates
until i
becomes
equal to 19,
printing "OK"
each time.
b. int i = 1; do {
cout << "a";
i = i + 1;
} while (i <= 15);
19. What will be the output of the following for loop? for (int i = 0; i < 5; )
{
cout << i << " ";
i++;
}
OUTPUT:
01234
20. Predict the output of the following while loop:
int x = 5;
while (x > 0)
{
ANUM NISA 4
1
COMPUTER SCIENCE (XII)
Syntax Synta
x
break; // exits from control structure exit(0); // exits program
without
ANUM NISA 4
2
COMPUTER SCIENCE (XII)
any error
24. Write down three differences between break and continue statement.
Break Continue
When a break statement is encountered then When the continue statement is
the control is exited from the loop construct encountered then the control
immediately. automatically passed to the beginning
of the loop statement.
It is often used to terminate from the control It is not used with the switch
structure like loop, switch statement. statement, but it can be used within
the loop.
More than one break statements can be Can be placed anywhere in the
executed in a program program
Leftover iterations are not executed after the Leftover iterations can be executed
break statement. even if the continue keyword appears
in a loop.
Synta Synta
x x
break; continue
;
25. Write a C++ program that reads a number and prints whether it is prime or composite.
#include <iostream>
using namespace std;
if (num <= 1) {
cout << "Neither prime nor composite." << endl;
}
else
{
for (int i = 2; i <= num ; ++i) {
if (num % i == 0)
{
ANUM NISA 4
3
COMPUTER SCIENCE (XII)
isPrime = 1;
break;
}
}
if (isPrime==0)
cout << num << " is a prime number." << endl;
else
cout << num << " is a composite number." << endl;
}
return 0;
}
26. Write the following code using if else if statement, to produce the same output.
switch (choice) { case 1: cout << "InSum=" << x + y;
break;
case 2:
cout << "InProduct= " << x * y;
break; default: cout <<
"InAverage= " << (x + y) / 2; break;
}
Answer:
if(choice = = 1)
cout<<"InSum="<<x+y; else
if(choice = = 2)
cout<<"InProduct= "<<x*y;
else cout<<"InAverage=
<<(x+y)/2;
27. What is the usage of break and continue statements in a C++ programs?
Usage of break statement:
The break statement is used to immediately terminate the execution of the innermost loop in
which it appears.
When a break statement is encountered within a loop, the control exits the loop and continues
with the statement immediately following the loop.
It is often used to terminate a loop early if a certain condition is met, avoiding unnecessary
iterations.
Usage of continue statement:
The continue statement is used to skip the remaining code within a loop for the current iteration
and proceed to the next iteration of the loop.
It is typically used to skip specific iterations of a loop based on certain conditions.
When a continue statement is encountered within a loop, the control jumps to the next iteration
of the loop, bypassing any remaining code within the current iteration.
ANUM NISA 4
4
COMPUTER SCIENCE (XII)
It is often used to skip certain iterations of a loop if a certain condition is met, without exiting
the loop entirely.
28. Find the output of the following error free code if the user enters a value 3568.
#include<iostream> int main( )
{ int no, res=0, r, n; cout<<”Enter any positive
number”; cin>>n; no=n; while(no>0)
{
r=no%10; res=res*10+r; no=no/10; }
cout<<”\n The Result is [“<<n<<”] is :: [“<<res<<”] \n”; }
Ouptut:
Enter any positive number: 3568
The Result is [3568] is :: [8653]
29. Rewrite the following code using if - else statement: rent = basic_pay>50000 ?
basic_pay*0.2 : basic_pay*0.4; Answer:
if (basic_pay > 50000)
{ rent = basic_pay * 0.2;
} else {
rent = basic_pay * 0.4;
}
30. Write a program that computes and displays the charges for a patient’s hospital
stay. The program should ask if the patient was admitted as an in-patient or an out-
patient.
• If the patient was an in-patient, the following data should be entered:
• The number of days spent in the hospital
• The daily rate
• Hospital medication charges
• Charges for hospital services (lab tests, etc.)
• If the patient was an out-patient the following data should be entered:
• Charges for hospital services (lab tests, etc.)
• Hospital medication charges
The program should use two overloaded functions to calculate the total charges. One of the
functions should accept arguments for the in-patient data, while the other function accepts
arguments for out-patient information. Both functions should return the total charges to the main
function.
Answer:
#include <iostream.h>
#include <conio.h>
float patient(int days, float rate, float medcharges, float hscharges);
float patient(float medcharges, float hscharges); void main(void)
{
ANUM NISA 4
5
COMPUTER SCIENCE (XII)
char p;
int days;
float rate, medcharges, hscharges, total;
cout<<"Enter I for in-patient or O for out-patient: ";
cin>>p;
if(p == 'I' || p == 'i')
{
cout<<"enter Number of days spent in the hospital: ";
cin>>days;
cout<<"enter Daily rate: ";
cin>>rate;
cout<<"enter Hospital medication charges: ";
cin>>medcharges;
cout<<"Charges for hospital services: ";
cin>>hscharges;
total = patient(days, rate, medcharges, hscharges);
cout<<"Patient total charges: "<<total;
}
else
if(ans == 'O' || ans == 'o')
{
cout<<"enter Hospital medication charges: ";
cin>>medcharges;
cout<<endl;
cout<<"enter Charges for hospital services: ";
cin>>hscharges; total = patient(medcharges,
hscharges);
cout<<"Patient total charges: "<<total;
}
getche();
}
float patient(int days, float rate, float medcharges, float hscharges)
{
float totalcharges;
totalcharges = (days * rate) + medcharges + hscharges;
return totalcharges;
}
float patient(float medcharges, float hscharges)
{
float totalcharges;
ANUM NISA 4
6
COMPUTER SCIENCE (XII)
ANUM NISA 4
7
COMPUTER SCIENCE (XII)
Random Access: Elements in an array can be accessed directly using their index, making it
easy to retrieve and manipulate data quickly.
ANUM NISA 4
8
COMPUTER SCIENCE (XII)
Simplified Code: Arrays simplify the code by allowing the use of loops for repetitive
operations, reducing the need for repetitive variable declarations and assignments.
Improved Performance: Array operations often have better performance compared to other
data structures for tasks like sorting, searching, and accessing elements due to their direct
memory access.
Versatility: Arrays can store a fixed-size collection of elements, making them suitable for a
wide range of applications from simple data storage to complex mathematical computations.
3. How to declare and initialize an array in C++.
In C++, we can declare and initialize an array using the following syntax:
data_type array_name[array_size] = {value1, value2, ..., valueN};
int numbers[5] = {10, 20, 30, 40, 50}; In this example:
• int is the data type of the array elements.
• “numbers” is the name of the array.
• [5] indicates the size of the array, which is 5 in this case.
• {10, 20, 30, 40, 50} is the list of initial values assigned to the array elements.
4. Rewrite the program segment after removing errors:
int a{10}, i; cout >> ” enter
ten numbers ; for (i = 0; i <
10; i--)
cin << a{i};
Answer:
The error free code is:
int a[10], i;
cout << "Enter ten numbers: ";
for (i = 0; i < 10; i++)
cin >> a[i];
• Replaced { } with [ ] to declare an array a.
• Changed >> to << for the output stream (cout).
• “ were missing at the end of cout string to display.
• Changed << to >> for the input stream (cin).
• Changed the loop condition from i-- to i++ to increment the loop variable i.
Removed the curly braces { } around a[i] inside the cin statement.
5. What is the difference between array size and index? Illustrate with example.
Feature Array Size Array Index
Definition It refers to total number of It refers to position of element within
elements array can hold array
Determination It is set when the array is It starts from 0 for first element,
created and does not increments by 1 for each subsequent
ANUM NISA 4
9
COMPUTER SCIENCE (XII)
change. element
Usage It specifies maximum It helps to get or change specific
capacity of array elements in an array.
Example int declares an arr[0 refers to first arr[1
arr[5]; array ] element, refers to ]
of size 5 second element,
and so on
6. Write down the purpose of sizeof() function. Give an example that finds the size of an
array.
The sizeof() function in C++ is used to determine the size in bytes of a data type or variable.
Its purpose includes:
Determining Size: It helps to find out the memory occupied by a data type or variable.
Memory Allocation: It assists in memory allocation calculations, especially in dynamic
memory allocation scenarios.
Example:
int main() {
int arr[5];
cout << "Size of int data type: " << sizeof(int) << " bytes" << endl;
cout << "Size of array arr: " << sizeof(arr) << " bytes" << endl;
return 0;
}
Output:
Size of int data type: 4 bytes
Size of array arr: 20 bytes
In this example, sizeof(int) returns the size of the integer data type (typically 4 bytes on most
systems), and sizeof(arr) returns the total size occupied by the array arr, which consists of 5
integers (hence 20 bytes).
7. Complete the following table to show the values of variables used in the
program during each iteration.
int i, s=0, count=5, v=0 ;
int a[5] =
{12,27,36,55,72};
for(i=0; i<=count; i++)
{ if(a[i] % 3 == 0)
{ cout<<a[i];
s += a[i];
v= s * 3 - a[i] % 7; } cout<<s<<"\t”<<v;
}
ANUM NISA 5
0
COMPUTER SCIENCE (XII)
9. Complete the following table to show the values of variables used in the
program during each iteration. int i, j, sum=1, count=1 ; int a[2][2] = {20,18,16,14};
for(i=0; i<=count; i++)
{ for(j=0; j<=count;j++)
sum += a[ i ][ j ];
cout<<" "sum<<endl; }
Iteration i j count a[i][j] sum
1 0 0 1 20 21
2 0 1 1 18 39
3 1 0 1 16 55
4 1 1 1 14 69
ANUM NISA 5
1
COMPUTER SCIENCE (XII)
10. Write the syntax of the declaration and initialization of a two-dimensional array.
also give an example.
The syntax for declaring and initializing a two-dimensional array in C++ is as follows:
data_type array_name[rows][columns] =
{ {value_1_1, value_1_2, ..., value_1_columns},
{value_2_1, value_2_2, ..., value_2_columns},
...
{value_rows_1, value_rows_2, ..., value_rows_columns}
};
Example:
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
This declares and initializes a 3x3 two-dimensional array named matrix with integer
elements. Each row is enclosed in curly braces, and the rows are separated by commas.
Answer:
20 // index 2 means 3rd element of array values
5 // index 0 means first element of an array values 4 with pre increment ->4+1=5
17 // index 1 means second element of an array values 17 with post increment
which means 17 will be displayed first and then incremented.
ANUM NISA 5
2
COMPUTER SCIENCE (XII)
Output:
3 6 8 13
14. Write a C++ program that lets the user to enter integer
numbers in a 2D array named matrix having 3 rows and 4
columns. The program should display the:
• Average of numbers stored in array.
• Minimum number in the array.
#include <iostream>
using namespace std; int
main() {
ANUM NISA 5
3
COMPUTER SCIENCE (XII)
// Display results
cout << "Average of numbers in the array: " << average << endl;
cout << "Minimum number in the array: " << min_num << endl;
return 0;
}
// Define a 2D array int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
cout << "Element at row 1, column 2: " << element << endl;
17. What is a String variable? Also write down the role of null character in C++ string.
Answer:
String:
ANUM NISA 5
4
COMPUTER SCIENCE (XII)
C++ automatically places the null terminator/ character at the end of string. An extra byte is
appended to the end of string when it is stored in memory. It does not print on the screen
and marks the end of the string. It is represented by ‘\0’.
18. Write down any three differences between string and array.
int main() {
char str[100];
return 0;
}
ANUM NISA 5
5
COMPUTER SCIENCE (XII)
In this example, cin.get() allows the user to input a string with spaces, while cin would stop
reading at the first space.
20. Compare strcpy( ) and strcat( ) functions with examples.
strcpy()
It is the string copy function. It copies one string into another string.
Syntax:
strcpy(string1, string2);
The two parameters to the function, string1 and string2, are strings. The function will copy the
string string2 into the string 1.
Example:
char dest[20], src[ ] = "Hello";
strcpy(dest, src);
In this example the contents of src are copied into dest.
strcat()
It is the string concatenate function. It concatenates / combines the sstrings.
Syntax:
strcat(string1, string2);
The two parameters to the function, string1 and string2 are the strings to be concatenated.
The above function will concatenate the string string2 to the end of the string string1.
Example:
char str1[20] = "Hello", str2[ ] = " World";
strcat(str1, str2);
In this example the contents of str2 are appended to str1, resulting in "Hello World".
21.Write the syntax of the declaration and initialization of a string.
In C++, a string can be declared and initialized in the following ways:
Declaration:
char str[20]; // Declares a character array named str with a capacity to hold 20 characters
Initialization: char str[ ] = "Hello"; // Initializes the string str with the content "Hello"
In the above example, the string str is initialized with the content "Hello". The size of the
array is determined automatically based on the length of the provided string.
22. Write the differences between strlen() and strcmp() functions.
Return Returns the length of the Returns an integer value indicating the
Value string (number of comparison result.
characters). • return 0 if string1 and string2 are
ANUM NISA 5
6
COMPUTER SCIENCE (XII)
the same.
• return 1 if string1 is greater than
string2.
• return -1 if string1 is less than
string2.
Functionality Provides the length of a Compares two strings character by
given string. character.
Example int len = int result = strcmp("Hello", "World");
strlen("Hello");
// len will be // result will be a negative integer (-
5 1)
based on the
comparison
ANUM NISA 5
7
COMPUTER SCIENCE (XII)
Chapter#6 Functions
Standard Library Functions: These are predefined functions provided by the C++
standard library, such as printf(), scanf(), strlen(), etc.
ANUM NISA 5
8
COMPUTER SCIENCE (XII)
5. What are three main components of function? Write their purposes also. Each
function consists of three components. These are:
• Function prototype/declaration
• Function definition
• Function call
Declaring a Function:
A Function Prototype/Declaration describes the function interface that specifies function's
name, parameters and return type. It does not contain function body. It gives information to
ANUM NISA 5
9
COMPUTER SCIENCE (XII)
the compiler that the function may later be used in the program. It is not needed(optional) if
the function is defined before the main( ) function.
long int factorial (int n); // function prototype showing the name of function (factorial),
argument of type (int) and return type of the function (long int).
Defining a Function:
A Function Definition contains the block of code (set of statements) to perform a specific
task. It tells the program what the function is doing. It is used to perform certain actions. It
defined once and can be reuse many times. It has two parts: Function header and body of
function. Function header is like function prototype except semicolon (;) at the end. The body
of function is the set of statements enclosed in curly braces{}.
Calling a Function:
A Function Call is a statement written in calling function to execute the code of defined
function. It invokes the statements of function. When a function is called, the control of the
program will be transferred to the function definition. The statements given in the function will
be executed and the control will be transfer back to the calling function.
fact = factorial(num); // function call, that requires parameter num and result store in fac
ANUM NISA 6
0
COMPUTER SCIENCE (XII)
70 1 3
7. Compare local and static variables in terms of scope, lifetime, and storage duration.
6. Compare local and global variables in terms of scope, lifetime, and storage duration.
Characteristic Local Variable Global Variable
Scope Local variables are accessible Global variables are accessible
only within the block or throughout the entire program,
function where they are including all functions and blocks.
declared or defined.
Lifetime It is created at the point of Its lifetime starts when the program
declaration / definition and begins and ends only when the
destroyed at the end of the program ends or terminates.
block in which it is defined.
Storage Duration Local variables have Global variables are allocated
automatic storage duration, memory when the program starts
meaning they are created and deallocated when the program
when the block is entered and ends. Therefore, they exist
destroyed when the block is throughout the entire execution of
exited. the program.
7. A program uses a function named convert( ) in addition to its main function. The function
main() declares the variable x within its body and the function convert() declares two
variables y and z within its body, variable z is made static. A fourth variable m is declared
ANUM NISA 6
1
COMPUTER SCIENCE (XII)
ahead (i.e. at the top) of both functions. State the visibility and lifetime of each of these
variables.
Answer:
Variable m, declared ahead of both functions, is a global variable. It is visible and accessible to
both the main() function and the convert() function. Its lifetime starts when the program begins
execution and ends when the program terminates.
Variable x, declared within the main() function, is a local variable. It is visible only within the
main() function and not accessible from outside. Its lifetime starts when the main() function is
called and ends when the main() function exits.
Variables y and z, declared within the convert() function, are also local variables. They are
visible only within the convert() function and not accessible from outside. Their lifetimes start
when the convert() function is called and end when the convert() function exits.
However, variable z being declared as static will retain its value across function calls, meaning
its lifetime ends only when the program ends or terminates.
8. If there is a function named "factorial" of integer type and has an integer parameter "n"
(a)Write the prototype for this function.
(b)What will be the header of its function definition?
(c)What will be the return type of this function?
Answer:
(a) int factorial(int n);
(b) int factorial(int n) { (c)
int
9. Distinguish between formal parameters and actual parameters used in functions.
ANUM NISA 6
2
COMPUTER SCIENCE (XII)
Calling a function generally causes a certain overhead, and for small functions, it may be more
efficient to insert the code of the function where it is called, instead of calling a function.
This overhead can be overcome by use of an Inline function. In Inline function the compiler
copies the code from the function definition directly into the code of the calling function rather
than creating a separate set of instructions in memory. The function call is replaced by the
contents of function itself.
It can be achieved by placing the keyword inline in function definition. This does not change
the behavior of a function, but the code generated by the function body shall be inserted at
each point where the function is called.
Example:
inline float sum(float a, float b)
{
return a+b;
}
11. Do inline functions improve performance? Justify wer answer.
Yes, inline functions can improve performance in certain cases. Here's a justification:
Reduced Function Call Overhead: Inline functions are expanded directly at the call site,
eliminating the overhead of function call. This can lead to faster execution, especially for
small, frequently called functions.
Avoidance of Function Call Stack: Since inline functions are expanded at the call site, they
do not create a separate stack frame for each call. This can reduce memory usage and
increase speed.
Compiler Optimization Opportunities: Inline functions enable the compiler to perform
context-specific optimization on the body of the function. Such optimizations are not possible
for normal function calls.
12. Write the disadvantages of using the inline function.
Increase Code Size: Inlining functions can result in increased code size, especially if the
function is large or used in multiple places. This can lead to larger executable files and
increased memory usage.
Increased Compilation Time: Inline functions can lead to longer compilation times, especially
in large codebases, as the compiler needs to duplicate the function's code at every call site.
Limited Usefulness for Embedded Systems: It is not useful for embedded system where
large binary size is not preferred at all due to memory size constraints.
13. Write down any three differences between passing arguments by value and by reference.
ANUM NISA 6
3
COMPUTER SCIENCE (XII)
14. Define default arguments. Give two advantages of using default arguments.
Default arguments in C++ allow we to specify default values for function parameters. These
default values are used when the corresponding argument is not provided during function
invocation.
Simplified Function Calls: Default arguments eliminate the need to specify values for all
parameters in every function call, making function calls more concise and readable.
Improved Readability: Default arguments can enhance code readability by reducing the need
for excessive function overloads or complex conditional logic to handle different argument
combinations.
15. Write a program that reads and passes a value to a function named factorial and print
its factorial.
#include <iostream>
using namespace std;
ANUM NISA 6
4
COMPUTER SCIENCE (XII)
int main() {
int num; //
Reading
input from
user cout
<< "Enter a
number: ";
cin >> num;
return 0; }
16. Briefly describe the features of function overloading.
• Using function overloading, we can declare multiple functions with the same name that
have slightly different purposes.
• Function overloading can significantly lower complexity of programs.
• As multiple functions have same name, therefore, remembering them is easier as
compared to remembering more names. It increases the readability of programs.
• It exhibits the behavior of polymorphism.
17. How a function can be overloaded?
Function overloading in C++ allows to define multiple functions with the same name but
different parameter lists. It allows to create functions that perform similar tasks but operate on
different types of data or accept different numbers of arguments. Function overloading can be
achieved by following these rules:
Same Function Name: All overloaded functions must have the same name.
a. Number of arguments
Functions can be overloaded if they have different numbers of parameters. More than one
functions with the same name but different number of parameters can be used in a single
program.
b. Data types of arguments
Another way to achieve function overloading is to define multiple functions with the same name
but different data types of parameters.
ANUM NISA 6
5
COMPUTER SCIENCE (XII)
c. Return Type Alone Isn't Enough: Function overloading cannot be based solely on
differences in return types. Two functions with the same parameter list but different return
types cannot be overloaded.
int main() { int sum1 = add(3, 4); // Calls the first add
function float sum2 = add(3.5, 4.5); // Calls the second add
function
return 0;
}
18. Write a C++ program to overload area() function to calculate area of circle, triangle,
square and rectangle.
Answer:
#include <iostream>
ANUM NISA 6
6
COMPUTER SCIENCE (XII)
int main() {
// Calculate and display the area of a circle
float circleArea = area(5.0);
cout << "Area of circle: " << circleArea << endl;
return 0;
}
19. Write declarations for two overloaded functions named FBISE(). Both have return type
int. The first takes one argument of type char, and the second takes two arguments of
type char. If this is impossible, justify why?
Yes, it's possible to have two overloaded functions named FBISE() with different argument
lists, as long as the parameter lists differ in number or types of parameters. Here's how the
declarations would look like: int FBISE(char c);
ANUM NISA 6
7
COMPUTER SCIENCE (XII)
These declarations define two overloaded versions of the FBISE() function. The first version
takes one argument of type char, while the second version takes two arguments of type char.
It's important to note that function overloading is based on the function's parameter list, not just
its return type. As long as the parameter lists differ in some way, such as the number or types
of parameters, we can overload functions with the same name.
20. Write a C++ program with a function named rectangle that inputs the length and width of
a rectangle and finds its area. The result is returned to the main () to be displayed on the
screen. Answer:
#include <iostream>
int main() {
// Calculate the area using the rectangleArea function
double area = rectangleArea();
return 0;
}
21. Write a C++ program using a function to find the quotient and remainder. The dividend
and divisor will be passed by reference to the function to calculate the quotient and
remainder.
Answer:
#include <iostream>
using namespace std;
ANUM NISA 6
8
COMPUTER SCIENCE (XII)
int main() {
int dividend, divisor;
return 0;
}
Chapter#7 Pointer
1. What is a pointer variable? Differentiate between reference operator (&) and dereference
operator (*).
A pointer variable in C++ is a variable that stores the memory address of another variable.
It "points to" the location of a data element in memory rather than containing the actual
data itself.
Feature Reference Operator (&) Dereference Operator (*)
Definition Reference/ Address operator The Dereference Operator operator is
provides the address of used to access the value stored at the
memory location associated memory address pointed to by a pointer.
with it.
ANUM NISA 6
9
COMPUTER SCIENCE (XII)
Symbol & *
Example int x = 10; int* int x = 10; int*
ptr = &x; ptr = &x; int
cout << "ptr = "<< ptr << endl; value = *ptr;
// prints address of X cout << "*Ptr = "<< *ptr<< endl; // prints
value of X
cout << "value = "<< value << endl; //
prints value of X
•
Pointer provides direct access to the memory.
•
Pointers save memory space.
•
Execution time with pointers is faster because data are manipulated with the address,
that is, direct access to memory location.
• Memory is accessed efficiently with the pointers. The pointer assigns and releases the
memory as well. Hence it can be said the Memory of pointers is dynamically allocated.
• Pointers reduces the storage space and complexity of the program.
4. how to declare and initialize a pointer?
To declare a pointer in C++, specify the data type followed by an asterisk (*) and then the
pointer variable name. Here's the basic syntax:
dataType *pointerVariableName;
For example, to declare a pointer to an integer variable: int
*ptr;
ANUM NISA 7
0
COMPUTER SCIENCE (XII)
This declares a pointer named ptr that can point to an integer variable. then the address of an
integer variable can be assigned to this pointer using the address-of operator (&). Example:
int x = 10;
int *ptr = &x; // Pointer ptr now holds the memory address of variable x
The asterisk (*) in the declaration indicates that ptr is a pointer, while the int before the asterisk
specifies the type of data the pointer can point to.
5. Write down the purpose of asterisk (*) in the following statements:
Answer:
a) distance = speed * time;
* used as the multiplication arithmetic operator. It gives the product of speed and time.
b) int *ptr = &n;
* used as the definition/ declaration of a pointer variable. It assigns address of variable n
to a pointer variable ptr. (Affecting variable ptr by storing memory address) c) *ptr = 100;
* used as the dereference operator. It assigns 100 to the memory location whose
address is stored in ptr variable (Not affecting ptr, but the value ptr points to).
6. If ptr is a pointer variable, what will be the output of the following statements? int n =
245, *ptr = &n; cout << ptr ; cout << *ptr ;
ANSWER
cout << ptr ; it will print the address of variable n.
cout << *ptr ; this pointer variable will print the value of variable n (* is used as
dereference operator here).
7. Write the purpose of the following:
i. Void pointer ii. Null pointer
Answer:
i. A void pointer or generic pointer in C++ is a pointer that has no associated data
type information. It's used to store the address of any data type, allowing for a
more flexible approach to pointer manipulation.
ii. A null pointer is a pointer that does not point to any memory address. It's typically
used to indicate that a pointer is not currently pointing to a valid memory location.
Null pointer is mostly used for dynamic memory allocation.
Chapter#8 Object and classes
1. What is the relationship between a class and an object?
Class:
A class is a template for defining objects. A class is a user-defined datatype that has its own
data members and member functions. It defines the structure, properties, behavior, and
contents of the objects that belong to it. It specifies how instances are created and how they
behave.
Object:
ANUM NISA 7
1
COMPUTER SCIENCE (XII)
An object is an instance of a class by which we can access the data members and member
functions of the class. An object exhibits the properties and behaviors defined by its class.
Multiple objects can be created from one class.
Example: Car is a class with properties and functions. Honda and Toyota are objects of Car.
2. How to declare a class in a C++ program? give an example.
In C++ a class can be declared by using the class keyword followed by the class name and a
pair of curly braces {} enclosing the data member (variables) and member functions. Here's a
simple example of how to declare a class:
#include <iostream>
// Member functions
void display() {
cout << "Integer: " << myInt << endl;
cout << "Double: " << myDouble << endl;
}
};
int main() {
// Creating an object of MyClass
MyClass obj;
return 0;
}
In this example:
• We declare a class named MyClass.
• Inside the class, we have two member variables (myInt and myDouble) and one member
function (display()).
ANUM NISA 7
2
COMPUTER SCIENCE (XII)
Memory for a class in C++ is typically allocated when we create an object (instance) of that
class. This process is known as instantiation. Memory allocation for a class involves
allocating memory for all its member variables and member functions.
Member Functions:
• Member functions are functions that operate on the data members of a class.
They define the behavior of the class and encapsulate the operations that can be performed
on the class's objects.
Member functions are also declared within the class body and can have different access
specifiers.
Example:
ANUM NISA 7
3
COMPUTER SCIENCE (XII)
};
• In the above example, display() is a member function of the class MyClass that prints the
values of myInt and myDouble.
8. Define a class Student that contains private and public data members including function
get( ).
ANSWER
class Student
{ private: int
age; int
rollNumber;
public:
void get(int Age, int studentRollNumber) {
age = Age;
rollNumber = studentRollNumber;
}
};
9. What are access specifiers.
Access specifiers in C++ are keywords used to define the accessibility of class members
(variables and functions) within the class and from outside the class. C++ provides three
access specifiers: public, private, and protected.
11. Compare Private and Public access specifiers with respect to accessibility in:
a) Same Class b) Derived Class c) Outside the Class
ANUM NISA 7
4
COMPUTER SCIENCE (XII)
Encapsulation:
Data hiding is often achieved through encapsulation, which involves combining similar data
and functions into a single unit called a class.
By encapsulating data within a class and making it private, we can control access to that data
and prevent direct manipulation from outside the class.
13. What is a constructor? write its characteristics?
Answer:
A constructor in C++ is a special member function that is automatically called when an object
of a class is created. It is used to initialize the object's data members and perform any
necessary setup tasks before the object is used. Constructors have several characteristics:
• Constructors have the same name as that of the class
• Constructors have no return type (not even void)
• Constructor is always public
• Constructors initialize the object's data members to their initial values or perform other
initialization tasks.
14. Compare Private and protected access specifiers with respect to accessibility in:
a) Same Class b) Derived Class c) Outside the Class
Answer:
ANUM NISA 7
5
COMPUTER SCIENCE (XII)
16. How is constructor different from other member functions in a class? Justify your
answer with at least three reasons.
ANUM NISA 7
6
COMPUTER SCIENCE (XII)
Syntax: object.memberName
19. What is constructor overloading? Briefly explain with the help of an example.
Constructor overloading in C++ refers to the ability to define multiple constructors within a
class, each with a different signature (i.e., a different number or type of parameters). This
allows objects of the class to be initialized in various ways, depending on the arguments
provided to the constructor.
public:
ANUM NISA 7
7
COMPUTER SCIENCE (XII)
// Default constructor
Rectangle()
{ length = 0.0;
width = 0.0;
}
ANUM NISA 7
8
COMPUTER SCIENCE (XII)
}
20. Define a class declaration named Inventory in a retail store with following members:
• Private members named item number, quantity, price, and total cost.
• Constructor to the class that initialize item number, quantity, and price to 0.
• Public member function get to accept data of item number, quantity, and price.
• Public member function display to calculate and print total cost of inventory Answer: Answer:
// Inventory class declaration class
inventory
{
private: // declarations of private members
int item_number; int quantity; float price;
float total_cost;
public: // declarations of public members
inventory ( )
{
item_number = 0;
quantity = 0;
price = 0;
}
void get (void)
{
cout<< “enter item number, quantity and price:”
cin >> item_number; cin>> quantity;
cin>> price;
}
void display (void)
{
total_cost = quantity * price; cout<< “total
cost of inventory:” << total_cost;
}
};
21. Explain the concept of inheritance and polymorphism in C++ with daily life examples.
Inheritance:
Inheritance is a fundamental concept in object-oriented programming (OOP) where a class
(known as the derived class or subclass) can inherit properties and behaviors from another
class (known as the base class or superclass). This allows for code reuse and promotes the
creation of a hierarchical relationship between classes.
ANUM NISA 7
9
COMPUTER SCIENCE (XII)
Everyday Example:
Consider the concept of vehicles. We can have a base class called Vehicle with properties
and behaviors common to all vehicles, such as speed, fuelType, and startEngine(). Now, we
can create derived classes like Car, Truck, and Motorcycle, which inherit from the Vehicle
class. Each derived class can have additional properties and behaviors specific to that type of
vehicle, such as numSeats for cars or cargoCapacity for trucks. By inheriting from the
Vehicle class, these derived classes automatically gain access to the common properties and
behaviors defined in the base class.
Polymorphism:
Everyday Example:
Let's extend the previous example of vehicles. Suppose we have a function called drive() that
takes a Vehicle object as a parameter and calls its startEngine() method. With polymorphism,
this function can accept objects of any class derived from Vehicle, such as cars, trucks, or
motorcycles. When the drive() function is called with a specific type of vehicle object, it
automatically calls the appropriate startEngine() method defined in the derived class, thanks
to dynamic binding.
22. What is Polymorphism? Give example to achieve polymorphism in C++.
Answer:
Polymorphism means many forms. It allows to perform a single action in different ways. The same
function or object behaves differently in different situations. For example, a person at the same
time has different behaviors like a father, a son, and an employee.
Example:
C++ provides overloading of operators. An operator (‘+’) is used to add two numbers (integers or
floating point), imaginary or complex numbers or concatenation of two strings. A single operator
adds these numbers and when placed between string, concatenates them. Hence, we have
achieved polymorphism.
ANUM NISA 8
0
COMPUTER SCIENCE (XII)
A file is a collection of data or information that is stored on a computer's storage medium, such
as a hard drive, solid-state drive, or external storage device.
File handling, also known as file I/O (Input/Output), refers to the process of reading from and
writing to files in a computer system.
It involves various operations, such as opening files, reading data from files, writing data to
files, closing files, and performing other file-related operations like moving, copying, or deleting
files.
File handling allows programs to interact with external data stored in files, enabling them to
perform tasks such as, Reading, Writing, and Modifying existing files.
2. Write down the differences between a text file and a binary file?
Text File Binary File
In text file, text, character, numbers In binary file data is stored in binary format
are stored one character per byte in in memory.
memory
Text files are used to store data more Binary files are used to store data more
user friendly. compactly.
Content written in text files is human Content written in binary files is not human
readable. readable and looks like encrypted content.
In text file, a special character In binary file no such character is present.
inserted after the last character to
mark the end of file.
Widely supported across different Compatibility may vary depending on the
platforms and programming specific binary format and the applications
languages. or systems that support it.
Suitable for storing and exchanging Used for storing and exchanging
textual data, source code, and nontextual data, such as multimedia files,
human-readable documents. program executables etc.
3. Write down the purpose of any three modes of file opening.
ANSWER
a. ios::app
Append mode. All output to that file to be appended to the end.
b. ios::ate
Open a file for output and move the read/write control to the end of the file.
c.ios::in
ANUM NISA 8
1
COMPUTER SCIENCE (XII)
a. getline( ) getline( ) is a standard library function defined in <fstream.h> used to read a string
or a line from an input stream. It extracts characters from the input stream and appends it to
the string object.
For example: file1.getline(name,50); // reads a string name of 50 characters from
file linked to file1
b. get( ) get( ) is a standard library function defined in <fstream.h> used to handle a single
character. It is used to fetch or read a character from file including blank space, tab, new
line character etc. For example: file2.get(ch); // reads a character ch from file linked to
file2
5. Consider the following statements and complete the following table:
Line No. Statement Purpose
1. #include<fstream.h>
2. fstream datafile;
3. datafile.open("datafile.txt" , ios::in);
4. if (! datafile)
5. { cout << ”no such file”; }
6. datafile >> ch;
7. if (datafile . eof( ))
8. datafile.close( );
Answer:
Line No. Statement Purpose
1. #include<fstream.h> Include the fstream header file in the program to use
its classes.
2. fstream datafile; Create an object of fstream class and give it the
name datafile.
3. datafile.open("datafile.txt" Use the open( ) function to open a file name
, ios::in); datafile.txt in input mode for reading data from it
4. if (! datafile) Use an if statement to check whether the file does
not exist.
ANUM NISA 8
2
COMPUTER SCIENCE (XII)
5. { cout << ”no such file”; } Text to print on the screen if the file is not found.
6. datafile >> ch; Write/store contents of the file in the variable ch.
7. if (datafile . eof( )) Use if condition and eof( ) function to ensure the
compiler keeps on reading from the file if the end is
not reached.
8. datafile.close( ); Call the close( ) function to close the file.
6. Identify and correct the errors in the following program code, that writes data to the file.
The line numbers are written along the left column. They are not part of the program
code.
Line No. Code
1 void
main(void)
2 {
3 i fstream
myfile;
4 myfile.open(writefile.txt)
;
5 myfile >> " Writing data to the file. \n
";
6 myfile.close()
;
7 }
ANUM NISA 8
3
COMPUTER SCIENCE (XII)
7 }
The bof() property is automatically set to true when the record pointer is before the first record
in the record set. The BOF property is also true if the record set is empty.
18. Explain the steps involved in reading and writing to a file in C++ program.
Reading from and writing to a file in a C++ program involves several steps. Here's
an explanation of each step involved in both processes:
Writing to a File:
1. Include Necessary Headers: Begin by including the necessary header file(s) for file
input/output operations, such as <fstream>.
2. Declare File Stream Object: Declare an object of the appropriate file stream class
(ofstream for writing) to handle file operations.
3. Open the File: Use the open() method of the file stream object to open the file in the
desired mode (std::ios::out for writing). Provide the file name.
4. Write Data to the File: Use output stream operators (<<) or the write() method to write
data to the file. This can include text, numbers, or any other data that needs to be stored in
the file.
5. Close the File: After writing all the necessary data, close the file using the close() method
of the file stream object to ensure that the file is properly closed.
ANUM NISA 8
4
COMPUTER SCIENCE (XII)
ANUM NISA 8
5
COMPUTER SCIENCE (XII)
ANUM NISA 8
6