Unit
1
Q1. List two memory management operators available in C++. Also state its use. (2 Marks)
Ans.
The two memory management operators in C++
are:
- new Operator
- Use: Allocates memory
dynamically on the heap for an object or array during runtime and returns
a pointer to the allocated memory.
int* ptr =
new int; // Allocates memory for an
integer
int* arr =
new int[5]; // Allocates memory for an
array of 5 integers
- delete Operator
- Use: Frees the memory that
was dynamically allocated using new to prevent memory leaks.
delete
ptr; // Deallocates memory for the
integer
delete[]
arr; // Deallocates memory for the array
Q2. Write any four applications of OOP. (2
Marks)
Ans. four applications of
Object-Oriented Programming (OOP):
- Real-Time Systems:
Used in simulations and real-time applications like traffic management, robotics, and process control. - Game Development:
OOP helps in designing reusable game objects such as players, enemies, and game environments with attributes and behaviors. - Database Management Systems (DBMS):
Used to model and manipulate real-world entities such as tables, rows, and columns with encapsulation and inheritance. - Graphical User Interface (GUI) Applications:
OOP is widely used in GUI-based software such as desktop applications, where components like buttons, windows, and menus are modeled as objects.
Q3. State and describe the characteristics of Object Oriented programming. (4 Marks)
Ans. main characteristics of
Object-Oriented Programming (OOP):
- Encapsulation:
- Encapsulation is
defined as the wrapping up of data under a single unit. It is the mechanism
that binds together code and the data it manipulates.
- It helps in data hiding by restricting access to certain
components and exposing only necessary details.
Example: Private variables and public methods in a class. - Inheritance:
- Inheritance allows a class (child or derived class) to inherit
properties and behaviors from another class (parent or base class).
- It promotes code reusability and helps in implementing
hierarchical relationships.
Example: A Car class inheriting from a Vehicle class. - Polymorphism:
- Polymorphism enables the same function or operator to behave
differently based on the context or input.
- It can be achieved through function overloading, operator
overloading, and method overriding.
Example: A function draw() can behave differently for Circle, Rectangle, or Triangle objects. - Abstraction:
- Abstraction focuses on showing only essential features of an
object and hiding unnecessary details.
- It is implemented using abstract classes and interfaces.
Example: A Vehicle class may define a general function start() without specifying its implementation, leaving it to derived classes like Car or Bike.
Q4. Describe concept of type casting using suitable example. (4 Marks)
Ans. Type Casting is the process of converting a value of one data type into another. In C++, type casting can be done explicitly (manual) or implicitly (automatic). It is often used to ensure compatibility between data types during operations.
- Implicit Type Casting (Type Conversion):
- Performed automatically by the compiler when converting a smaller
data type to a larger one.
Example:
int num =
10;
double
result = num; // Implicit conversion
from int to double
std::cout
<< "Result: " << result;
// Output: 10.0
- Explicit Type Casting (Type Casting):
- Done manually using cast operators to convert one data type into
another.
Example:
double num
= 9.75;
int result
= (int)num; // Explicit casting from
double to int
std::cout
<< "Result: " << result;
// Output: 9
C++ Style
Type Casting
C++ also provides specialized casting
operators for better clarity and type safety:
- static_cast
- dynamic_cast
- const_cast
- reinterpret_cast
Example with static_cast:
float pi =
3.14;
int pi_int
= static_cast<int>(pi); //
Converts float to int
std::cout
<< "Pi as integer: " << pi_int; // Output: 3
Type casting is essential for ensuring type
compatibility and achieving desired results in operations involving mixed data
types.
Winter 2022
Q5. Describe use of scope resolution operator with example. (4 Marks)
Ans. The scope resolution
operator (::)
in C++ is used to specify the scope in which an identifier (such as a variable,
function, or class member) resides. It helps in resolving ambiguity when
multiple scopes contain entities with the same name or when accessing global
and class-specific members.
Uses of
Scope Resolution Operator
- Accessing Global Variables:
- When a local variable has the same name as a global variable, the
scope resolution operator can be used to access the global variable.
int x =
10; // Global variable
int main()
{
int x = 20;
// Local variable
std::cout << "Local x: "
<< x << "\n";
std::cout << "Global x: "
<< ::x << "\n"; //
Access global variable
return 0;
}
- Defining Class Member Functions Outside the Class:
- The operator is used to define member functions outside the class
definition.
class
MyClass {
public:
void display(); // Member function declaration
};
void
MyClass::display() { // Defined outside
the class
std::cout << "Member function
defined using scope resolution operator.\n";
}
int main()
{
MyClass obj;
obj.display();
return 0;
}
- Accessing a Class's Static Members:
- Used to access static members of a class without creating an object.
class
MyClass {
public:
static int count; // Static member
};
int
MyClass::count = 0; // Initialize static
member outside the class
int main()
{
std::cout << "Static count:
" << MyClass::count << "\n";
return 0;
}
- Resolving Namespace Ambiguities:
- Helps in accessing members of a specific namespace.
cpp
Copy code
namespace A
{
int num = 10;
}
namespace B
{
int num = 20;
}
int main()
{
std::cout << "Namespace A num:
" << A::num << "\n";
std::cout << "Namespace B num:
" << B::num << "\n";
return 0;
}
Summary
The scope resolution operator (::) plays a vital role in accessing variables, functions, and static
members while avoiding ambiguity between scopes.
Q6. Develop a C++ program to print Fibonacci
series. (4 Marks)
Ans.
#include <iostream>
using namespace std;
int main() {
int n; // Number of terms
cout << "Enter the number of terms for Fibonacci series:
";
cin >> n;
if (n <= 0) {
cout << "Number of terms must be positive." <<
endl;
return 0;
}
int first = 0, second = 1, next;
cout << "Fibonacci series: ";
for (int i = 1; i <= n; ++i) {
cout << first << " "; // Print the current term
// Calculate the next term
next = first + second;
first = second;
second = next;
}
cout << endl;
return 0;
}
Input:
Enter the number of terms for Fibonacci series: 5
Output:
Fibonacci series: 0 1 1 2 3
Q7. Develop a C++ program for accept data from user to calculate percentage for five (5) subjects display grade according to percentage.
Ans.
#include <iostream>
#include <string>
using namespace std;
// Structure definition
struct Student {
char Name[20];
int Roll_No;
float Percentage;
};
int main() {
Student s[5]; // Array to store
details of 5 students
int i;
// Input student data
for (i = 0; i < 5; i++) {
cout << "Enter name of student " << i + 1 <<
": ";
cin >> s[i].Name;
cout << "Enter Roll Number of student " << i + 1
<< ": ";
cin >> s[i].Roll_No;
cout << "Enter percentage of student " << i + 1
<< ": ";
cin >> s[i].Percentage;
cout << endl;
}
// Display student data
cout << "\nStudents' data is:\n";
for (i = 0; i < 5; i++)
{
cout << "Student " << i + 1 << " Name:
" << s[i].Name << endl;
cout << "Student " << i + 1 << " Roll Number: " <<
s[i].Roll_No << endl;
cout << "Student " << i + 1 << " Percentage: " <<
s[i].Percentage << "%" <<
endl;
cout << endl;
}
return 0;
}
Summer 2023
Ans. Static Initialization
In static initialization, variables are assigned values at
the time of their declaration in the code. The values are known and fixed at
compile time.
Example:
#include <iostream>using namespace std; int main() { int a = 10; // Static initialization float b = 3.14; // Static initialization cout << "Static Initialization:" << endl; cout << "a = " << a << ", b = " << b << endl; return 0;}
Output:
Static Initialization:a = 10, b = 3.14Dynamic Initialization
In dynamic initialization, variables are assigned values at
runtime, typically based on user input or computations.
Example:
#include <iostream>using namespace std;int main() { int x, y; cout << "Enter two numbers: "; cin >> x >> y; int sum = x + y; // Dynamic initialization based on runtime input cout << "Dynamic Initialization:" << endl; cout << "Sum = " << sum << endl; return 0;}
Input:
Enter two numbers: 5 7
Output:
Dynamic Initialization:Sum = 12Summary
- Static Initialization:
Values are assigned at compile time (e.g.,
int a = 10;). - Dynamic Initialization:
Values are assigned at runtime based on inputs or computations (e.g.,
int sum = x + y;).
Q9. Write the syntax for declaration of a class. (2 Marks)
Ans. The syntax for the declaration of a class in C++ is as follows:
class ClassName {private:
// Private data members and member functions (accessible only within the class)
protected:
// Protected data members and member functions (accessible within the class and derived classes)
public:
// Public data members and member functions (accessible from outside the class)
// Constructor(s) and Destructor (optional)
};
Example
class Student {
private:
int rollNo;
float marks;
public:
void setDetails(int r, float m)
rollNo = r;marks = m;
void displayDetails() {
std::cout << "Roll Number: " << rollNo << ", Marks: " << marks << std::endl;
};
Explanation:
- class: Keyword used to define a class.
- ClassName: Name of the class.
- Access Specifiers:
- private: Members accessible only
within the class.
- protected:
Members accessible within the class and derived classes.
- public: Members accessible from
outside the class.
Ans . features of Object-Oriented
Programming (OOP):
- Encapsulation:
- Combines data (attributes) and methods (functions) into a single
unit called a class.
- Restricts direct access to some components, promoting data
security and abstraction.
- Inheritance:
- Enables a class (child/derived class) to inherit attributes and
behaviors from another class (parent/base class).
- Facilitates code reusability and hierarchical relationships.
- Polymorphism:
- Allows functions or methods to have multiple forms.
- Examples include function overloading (compile-time polymorphism)
and method overriding (runtime polymorphism).
- Abstraction:
- Focuses on showing only essential details to the user and hiding
complex implementation details.
- Achieved through abstract classes and interfaces.
- Class and Object:
- A class acts as a blueprint for creating objects, which are
instances of the class.
- Objects represent real-world entities with attributes and
behaviors.
- Dynamic Binding:
- Refers to linking a function call to the function definition at
runtime.
- Supports flexibility in program behavior through polymorphism.
- Message Passing:
- Objects communicate with one another by sending and receiving
information, typically through function calls.
These features collectively make OOP powerful for designing modular, reusable, and maintainable software.
Q11. Explain the structure of C program.
(4 Marks)
Ans. The structure of a C++
program consists of various components that work together to create a complete
program. Below is a breakdown of the structure:
1.
Preprocessor Directives
- These are instructions that are processed by the preprocessor before compilation starts. They usually include header files, macros, or other preprocessor commands.
#include
<iostream> // Preprocessor
directive to include the standard input-output stream library
2. Global
Declarations
- This section includes global variables, constants, or functions that can be accessed throughout the program. Global declarations are typically placed after the preprocessor directives.
int
globalVar; // A global variable
3. Main
Function
- Every C++ program must have a main() function. It is the entry point of the program, where execution begins.
int main()
{
// Code to execute
}
- The main()
function may return an integer, usually 0 to indicate successful completion.
4. Variable
Declarations and Initialization
- Local variables are declared and initialized inside the main() function (or any other functions) as needed.
int a = 10,
b = 20; // Local variable declarations
5. Function
Definitions
- Additional functions can be defined outside the main() function to break the program into modular blocks of code. These functions may be called from the main() function or other functions.
void
display() {
std::cout << "Hello,
World!" << std::endl;
}
6.
Statements and Expressions
- These are the core operations within the program that perform actions, such as calculations, printing output, and controlling flow.
int sum = a
+ b; // Example of a statement
7. Control
Structures
- C++ supports various control structures such as conditionals (if, else, switch),
loops (for, while), and function calls to control the flow
of the program.
if (a >
b) {
std::cout << "a is greater than
b";
}
8. Return
Statement
- The main()
function typically ends with a return
0; statement, indicating that the program
has executed successfully.
return
0; // Return statement
Example of
a Complete C++ Program:
#include <iostream> // Preprocessor directive
// Global Declarations
int globalVar = 100;
void
display() { // Function definition
std::cout << "Hello,
World!" << std::endl;
}
int main()
{ // Main function (Entry point)
int a = 10, b = 20; // Variable declarations
int sum = a + b; // Expression
std::cout << "Sum: "
<< sum << std::endl; //
Output statement
display(); // Function call
if (a > b) { // Control structure (if)
std::cout << "a is greater
than b" << std::endl;
}
return 0;
// Return statement
}
Explanation
of Structure:
- Preprocessor Directives (#include <iostream>) are
used for including external libraries.
- Global Declarations
define variables that can be accessed throughout the program.
- The main() function is the entry point where execution
begins.
- Function Definitions
provide modular code for specific tasks (e.g., display()).
- Statements and Expressions carry
out the operations like addition or printing.
- Control Structures
determine the flow based on conditions.
- The Return Statement signals the end of the main() function.
Ans.
#include <iostream>
using namespace std;
int main() {
int n, sum = 0;
// Input the value of n
cout << "Enter a positive integer n: ";
cin >> n;
// Print the first n natural numbers and calculate their sum
cout << "First " << n << " natural
numbers are:" << endl;
for (int i = 1; i <= n; ++i)
{
cout << i << " ";
// Print the natural number
sum += i; // Add the
number to the sum
}
// Print the sum
cout << "\nSum of first " << n << "
natural numbers is: " << sum << endl;
return 0;
}
Explanation:
1. Input:
The program takes an integer n
from the user to determine how many natural numbers should be printed.
2. For
Loop:
The for loop runs from 1 to n.
Each number is printed, and it is also added to the sum variable.
3. Sum
Calculation:
Inside the loop, the current number i
is added to sum, which keeps
track of the cumulative sum.
4. Output:
The program prints the first n
natural numbers and the total sum after the loop finishes.
Example Output:
Input:
Enter a positive integer n: 5
Output:
First 5 natural numbers are:1 2 3 4 5 Sum of first 5 natural numbers is: 15
Winter 2023
Ans.
|
Aspect |
C |
C++ |
|
Programming Paradigm |
Procedural Programming Language (focuses on functions and procedures). |
Object-Oriented Programming Language (focuses on objects and classes). |
|
Support for Classes |
Does not support classes and objects. |
Supports classes and objects, enabling OOP concepts like inheritance,
polymorphism, and encapsulation. |
Q14. Explain the input operator in C++. (2
Marks)
Ans. In C++, the input
operator is the extraction operator (>>), which is
used to read data from the standard input (usually the keyboard). It is
commonly used with the cin
object, which is part of the <iostream>
library.
Syntax:
cin >> variable;
Explanation:
cin: Represents the standard input stream.>>: Extracts data from the input stream and stores it in the specified variable.
Example:
#include <iostream>using namespace std;int main() { int num; cout << "Enter a number: "; cin >> num; // Input operator used to read the number cout << "You entered: " << num << endl; return 0;}
Input:
Enter a number: 10
Output:
You entered: 10
Key Features:
- Reads Data Sequentially:
The operator reads input data from left to right.
- Handles Multiple Variables:
It can read multiple inputs in a single statement.
int a, b;cin >> a >> b; // Reads two numbers from the user
- Type-Sensitive: The data
entered must match the type of the variable. For example, entering
non-integer data for an
intvariable will cause input failure.
The input operator simplifies user input in C++ and is widely used for
interactive programs.
Q15. Explain the rules for naming variables in C++, (Any four points). (4 Marks)
Ans. Four key rules for naming
variables in C++:
Valid Characters:
- A variable name can include letters (a-z, A-Z), digits (0-9), and the underscore (_).
- It cannot contain spaces or special characters like @, #, &, etc.
int
my_var; // Valid
int my@var; // Invalid
Cannot Start with a Digit:
- A variable name must not begin with a digit.
int
var1; // Valid
int
1var; // Invalid
No Reserved Keywords:
- Variable names cannot use reserved keywords or identifiers in C++
(e.g., int, return, class).
int
class; // Invalid
int
myClass; // Valid
Case Sensitivity:
- C++ variable names are case-sensitive, meaning MyVar and myvar are treated as different
variables.
int MyVar =
10;
int myvar =
20;
Additional
Good Practice (Optional):
- Use meaningful names to improve code readability (e.g., age instead of a).
- Avoid starting names with underscores (_) unless necessary, as some names starting with _ are reserved for the compiler.
Q16. Write a C++ program to find out whether the given number is even or odd (taking input from keyboard).
Ans.
#include <iostream>
using namespace std;
int main() {
int num;
// Input: Take a number from the user
cout << "Enter an integer: ";
cin >> num;
// Check if the number is even or odd
if (num % 2 == 0) {
cout << num << " is an even number." <<
endl;
} else {
cout << num << " is an odd number." << endl;
}
return 0;
}
Explanation:
1. Input:
- The
program prompts the user to enter an integer using
cout. - The
input is read using
cinand stored in the variablenum.
2. Even
or Odd Check:
- The
program checks if the remainder when
numis divided by 2 (num % 2) is0. - If
num % 2 == 0, the number is even; otherwise, it is odd.
3. Output:
- The
program prints whether the number is even or odd using
cout.
Example Input/Output:
Input:
Enter an integer: 5
Output:
5 is an odd number.
Q17. Explain the access specifiers in C++.
(4 Marks)
Ans. In C++, access specifiers
define the accessibility or visibility of class members (attributes and
methods). They control how members of a class can be accessed from outside the
class or from derived classes. The three main access specifiers are:
1. Private:
- Members declared as private are accessible only within the class in which they are
defined.
- They are not accessible from outside the class or by derived
classes.
- Default access specifier for members of a class if no specifier is
explicitly mentioned.
Syntax:
class
MyClass {
private:
int x;
// Private member
};
Example:
class
MyClass {
private:
int x;
public:
void setX(int value) {
x = value; // Allowed within the class
}
};
int main()
{
MyClass obj;
// obj.x = 10; // Error: Cannot access private member
return 0;
}
2.
Protected:
- Members declared as protected are accessible within the class and its derived classes, but not
outside them.
- Useful in inheritance to allow derived classes to access parent
class members.
Syntax:
class
MyClass {
protected:
int x;
// Protected member
};
Example:
class
Parent {
protected:
int x = 5;
};
class Child
: public Parent {
public:
void display() {
cout << "Value of x: "
<< x << endl; // Allowed
}
};
int main()
{
Child obj;
obj.display(); // Allowed via the derived class
// obj.x = 10; // Error: Cannot access protected member
directly
return 0;
}
3. Public:
- Members declared as public are accessible from anywhere in the program (outside the class,
within the class, and in derived classes).
Syntax:
class
MyClass {
public:
int x;
// Public member
};
Example:
class
MyClass {
public:
int x;
void display() {
cout << "Value of x: "
<< x << endl;
}
};
int main()
{
MyClass obj;
obj.x = 10;
// Allowed: Public member
obj.display();
return 0;
}
Summary of
Accessibility:
|
Access Specifier |
Within Class |
Derived Class |
Outside Class |
|
Private |
Yes |
No |
No |
|
Protected |
Yes |
Yes |
No |
|
Public |
Yes |
Yes |
Yes |
These access specifiers enable encapsulation,
ensuring proper data security and control in object-oriented programming.
i)Accept length and breadth from user.
ii) Calculate the area
iii) Display the result
Ans.
#include <iostream>
using namespace std;
class Rectangle {
int length, breadth;
public:
// Member function to accept length and breadth
void accept() {
cout << "Enter length & breadth: ";
cin >> length >> breadth;
}
// Member function to calculate and display the area
void displayArea() {
int area = length * breadth;
cout << "Area of the rectangle: " << area << endl;
}
};
int main() {
Rectangle r; // Create an object of the Rectangle class
r.accept(); // Call the accept function to get input
r.displayArea(); // Call the function to calculate and display area
return 0;
}
Q19. Define class and object. (2 Marks)
Ans. Class:
A class is a blueprint or template for
creating objects in C++. It defines the data (attributes) and functions
(methods) that the objects created from the class will have. A class
encapsulates data and methods into a single unit, promoting reusability and
modularity.
Example:
class
Rectangle {
int length, breadth; // Attributes
public:
void setDimensions(int l, int b) { // Method
length = l;
breadth = b;
}
int area() {
return length * breadth;
}
};
Object:
An object is an instance of a class. It
is a real-world entity that uses the blueprint (class) to store data and
perform operations. Objects interact with each other using the methods defined
in their class.
Example:
int main()
{
Rectangle r; // Object created from the Rectangle
class
r.setDimensions(5, 10);
cout << "Area: " <<
r.area(); // Output: Area: 50
return 0;
}
Ans.
#include <iostream>
using namespace std;
int main()
{
int num;
unsigned long long factorial = 1;
// Input: Take a number from the user
cout << "Enter a positive integer: ";
cin >> num;
// Factorial of 0 and 1 is 1
if (num < 0) {
cout << "Factorial is not defined for negative numbers."
<< endl;
} else {
for (int i = 1; i <= num; ++i)
{
factorial *= i; // Multiply each number from 1 to num
}
// Output the result
cout << "Factorial of " << num << " =
" << factorial << endl;
}
return 0;
}
Ans
#include <iostream>
using namespace std;
class Student
{
int rollno;
char name[20];
float marks;
public:
void accept();
void display();
};
// Member function definitions
void Student::accept()
{
cout << "\nEnter data of student:";
cout << "\nRoll number: ";
cin >> rollno;
cout << "Name: ";
cin >> name;
cout << "Marks: ";
cin >> marks;
}
void Student::display() {
cout << "\nStudent's data is:";
cout << "\nRoll number: " << rollno;
cout << "\nName: " << name;
cout << "\nMarks: " << marks;
}
int main() {
Student s; // Create an object of Student class
s.accept(); // Accept data for the student
s.display(); // Display data of the student
return 0;
}
No comments:
Post a Comment