0% found this document useful (0 votes)
4 views32 pages

C++ Programming Concepts and Examples

The document is an assignment for a student named Prashi Bansala, covering various topics in C++ programming. It includes sections on identifiers, data types, pointers, output of code snippets, inheritance, error handling, and programming examples. Additionally, it discusses concepts like jump statements, header files, and provides sample programs for specific tasks.

Uploaded by

PULKIT
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)
4 views32 pages

C++ Programming Concepts and Examples

The document is an assignment for a student named Prashi Bansala, covering various topics in C++ programming. It includes sections on identifiers, data types, pointers, output of code snippets, inheritance, error handling, and programming examples. Additionally, it discusses concepts like jump statements, header files, and provides sample programs for specific tasks.

Uploaded by

PULKIT
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

ASSIGNMENT (for 1st sem)

NAME-PRASHI BANSALA 2023771

BA PROGRAM (ENGLISH+COMPUTER SCIENCE) 5th sem

Section A (Compulsory)

1. (a) Identifiers and Validity

Identifiers in C++ are names given to entities like variables, functions, classes, and so on.
They are constructed according to specific rules.

• Rules for Identifiers:

1. Can include letters (A-Z, a-z), digits (0-9), and the underscore (_).

2. Must start with a letter or an underscore.

3. Cannot be a reserved C++ keyword (like for, if, while).

4. Cannot contain spaces or special characters (like ;, !, @, -).

5. C++ is case-sensitive.

Identifier Validity Reason

(i)
Valid Starts with a letter, contains letters, digits, and an underscore.
Po178_ddm

(ii) _78hhvt4 Valid Starts with an underscore, contains letters and digits.

(iii) 902gt1 Invalid Starts with a digit.

(iv) Tyy;ui8 Invalid Contains the invalid special character semi-colon (;).
Identifier Validity Reason

Although for is a keyword, C++ is case-sensitive, so For is a distinct


(v) For Valid
(and valid) identifier.

(vi) Fg026
Invalid Contains a space.
neo

1. (b) Data Types

Data Types specify the size and type of values that can be stored in a variable.

• (i) Built-In Data Types: These are fundamental data types that are predefined and
directly supported by the C++ language. They include:

o Integer types: int, char, short, long, long long (used for whole numbers).

o Floating-point types: float, double, long double (used for real numbers with
fractional parts).

o Boolean type: bool (used for logical values: true or false).

• (ii) User-Defined Data Types: These are types created by the programmer based on
the built-in types to meet specific application requirements. They include:

o Structures (struct)

o Classes (class)

o Unions (union)

o Enumerations (enum)

• (iii) Derived Data Types: These are data types that are built from or derived from the
built-in or user-defined types. They include:

o Arrays

o Pointers

o References

o Functions

1. (c) Pointers in C++

A pointer is a variable that holds the memory address of another variable. The declaration
uses the asterisk $(*)$ operator.
• Example:

C++

int var = 20; // A regular integer variable

int* ptr; // A pointer variable that can hold the address of an integer

ptr = &var; // The address-of operator (&) assigns the address of 'var' to 'ptr'

// Now, *ptr (the dereferenced pointer) gives the value of 'var', which is 20.

• Difference from a Regular Variable:

Regular Variable (e.g., int


Feature Pointer Variable (e.g., int* ptr)
var)

The actual data value The memory address of another variable (e.g.,
Stores
(e.g., 20). 0x7ffee...).

Manipulated using its Manipulated using the address-of operator (&)


Manipulation
name. and the dereference operator (*).

Holds a memory address, but is bound to a


Holds a value of its
Type specific data type (e.g., int* can only point to an
declared type (e.g., int).
int).

1. (d) Output of C++ Code

The code snippet performs a type conversion (implicit widening conversion or promotion)
from int to double.

C++

int main() {

int num1 = 10;

double num2 = num1; // num1 (int: 10) is implicitly converted to double (10.0)

cout << "num1: " << num1 << endl;

cout << "num2: " << num2 << endl;

return 0;

Output:
num1: 10

num2: 10

(Note: Although num2 holds the value 10.0, the standard output often prints it as 10 unless
stream manipulators are used.)

1. (e) C++ Program to Find Largest of 2 Numbers

C++

#include <iostream>

using namespace std;

int main() {

int num1, num2;

cout << "Enter the first number: ";

cin >> num1;

cout << "Enter the second number: ";

cin >> num2;

if (num1 > num2) {

cout << "The largest number is: " << num1 << endl;

} else if (num2 > num1) {

cout << "The largest number is: " << num2 << endl;

} else {

cout << "Both numbers are equal." << endl;

return 0;

}
1. (f) Output of C++ Code

The code involves arithmetic operators, compound expressions, operator precedence, and
the pre/post increment/decrement operators.

Initial values: a = 15, b = 4

1. int result1 = a / b * b + a % b;

o a / b: $15 / 4 = 3$ (Integer division)

o 3 * b: $3 \times 4 = 12$

o a % b: $15 \pmod 4 = 3$ (Remainder)

o 12 + 3: $15$

o $\implies$ result1 is $\mathbf{15}$. (After this, a=15, b=4)

2. bool result2 = (a == 15) && (b < 10);

o (a == 15): 15 == 15 is true (1)

o (b < 10): 4 < 10 is true (1)

o true && true: is true (1)

o $\implies$ result2 is $\mathbf{1}$ (true). (After this, a=15, b=4)

3. int result3 = a++ - --b;

o --b: Pre-decrement $\implies$ b becomes $3$. (Value used: 3)

o a++: Post-increment $\implies$ a's original value ($15$) is used in the


expression, then a becomes $16$.

o 15 - 3: $12$

o $\implies$ result3 is $\mathbf{12}$. (After this, a=16, b=3)

4. int result4 = 10 + 2 * 3 / 4 - 5; (Multiplication/Division have higher precedence than


Addition/Subtraction, and are evaluated left-to-right.)

o 2 * 3: $6$

o 6 / 4: $1$ (Integer division)

o 10 + 1 - 5: $11 - 5 = 6$

o $\implies$ result4 is $\mathbf{6}$.

Output:

Result 1: 15
Result 2: 1

Result 3: 12

Result 4: 6

1. (g) True or False Statements

• (i) A constructor is automatically invoked on object creation, cannot have a return


type-not even void, and does not return any value.

o True. Constructors are special member functions called at the time of object
creation. They cannot have an explicit return type and should not return any
value.

• (ii) A destructor is a member function that is specifically called on an object by a


programmer when the object goes out of scope.

o False. A destructor is a member function that is automatically invoked when


an object is destroyed or goes out of scope, but it is not typically called
explicitly by the programmer (except in special memory management cases).

• (iii) The constructor can be overloaded. That is, you can have more than one
constructor in a class having different parameter lists.

o True. Constructor overloading allows a class to have multiple constructors


with the same name (the class name) but different parameter lists (different
types or number of arguments).

1. (h) C++ Program for Positive Integer Input Validation

C++

#include <iostream>

using namespace std;

int main() {

int number;

// Initially ask the user for a number

cout << "Enter a positive integer: ";


cin >> number;

// Use a while loop to keep asking until a valid positive number is provided

while (number <= 0) {

cout << "Invalid input. Please enter a positive integer: ";

cin >> number;

cout << "You entered a valid positive integer: " << number << endl;

return 0;

1. (i) Single vs. Multiple Inheritance

Inheritance is a mechanism in OOP where one class (the derived or child class) acquires the
properties and behavior (member variables and methods) of another class (the base or
parent class).

| Feature | Single Inheritance | Multiple Inheritance |

| :--- | :--- | :--- |

| Definition | A derived class inherits from only one base class. | A derived class inherits
from two or more base classes. |

| Structure | Linear: $A \rightarrow B$ (B inherits from A). | Complex: $A, B \rightarrow C$


(C inherits from A and B). |

| Simplicity | Simpler to implement and manage. | More complex and can lead to the
Diamond Problem (ambiguity when two base classes inherit from a common ancestor). |

| Example | class Dog : public Animal {}; | class StudentAthlete : public Student, public
Athlete {}; |

1. (j) Identify and Correct Error in Try-Catch Block


The error is in the catch block's parameter type. The throw statement throws a C-style string
literal ("Division by zero error!"), which is of type const char* (a pointer to a constant
character). However, the catch block is trying to catch an int (catch (int e)).

When the program throws a const char*, the catch (int e) block will not catch it, and the
program will terminate unexpectedly (the exception is uncaught).

Original Code Snippet (Error):

C++

// ... inside main

throw "Division by zero error!"; // throws a const char*

// ...

} catch (int e) { // tries to catch an int

cout << "Error: Division by zero!" << endl;

Corrected Code Snippet:

The catch block must be changed to catch the thrown type, which is const char* or a generic
catch block (...).

C++

int main() {

int a = 10, b = 0; // Corrected declaration: comma instead of space

try {

if (b == 0) {

throw "Division by zero error!";

} else {

cout << "Result: " << a / b << endl;

} catch (const char* e) { // Corrected: Catching the thrown const char*

cout << "Error: " << e << endl; // Optionally print the error message

return 0;
}

(Also corrected the syntax int a=10 b=0; to int a=10, b=0; to be valid C++.)

Section B (Attempt any 4)

2. (a) C++ Program for Number Pattern

The pattern requires nested loops. The outer loop controls the number of rows (n), and the
inner loop prints the numbers from 1 up to the current row number.

• Input n=4

• Output:

• 1

• 12

• 123

• 1234

C++

#include <iostream>

using namespace std;

int main() {

int n;

cout << "Enter a positive integer n: ";

cin >> n;

// Outer loop for the number of lines (rows)

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

// Inner loop for printing numbers from 1 up to the current row number 'i'

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

cout << j;

}
cout << endl; // Move to the next line after each row

return 0;

2. (b) Jump Statements

Jump statements transfer the program control to a different part of the program.

• (i) break:

o Used to terminate the execution of the innermost loop (for, while, do-while)
or a switch statement.

o Control passes to the statement immediately following the loop or switch


structure.

o Example: Terminating a search early.

C++

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

if (i == 5) {

break; // Exit the loop entirely when i is 5

cout << i << " "; // Prints: 0 1 2 3 4

cout << "Loop finished." << endl;

• (ii) continue:

o Used to skip the rest of the current iteration of the innermost loop and
proceed directly to the next iteration.

o Example: Skipping an undesirable value.

C++

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

if (i % 2 == 0) {
continue; // Skip printing for even numbers

cout << i << " "; // Prints: 1 3 5

• (iii) return:

o Used to terminate the execution of a function and return control to the


calling function.

o It can optionally return a value to the caller, corresponding to the function's


return type.

o Example: Returning the result of a calculation.

C++

int add(int a, int b) {

return a + b; // Exits the function and returns the sum

// ... in main: int sum = add(5, 3);

2. (c) Header Files in C++

Header files in C++ are files containing declarations of functions, classes, constants, and
other components. They typically have a .h or no extension (for standard library headers).

• Purpose: They allow the programmer to use pre-written code (like standard library
functions) without having to write the function definitions themselves. For example,
iostream provides the input/output functions (cout, cin).

• How they reduce compilation time and efforts:

o Effort Reduction: Programmers don't need to re-implement common


functionalities (like math functions, IO operations, string manipulation).

o Compilation Time Reduction: The actual code (definitions) for the library
functions are often pre-compiled and stored in separate library files. The
header file only contains the declarations, which are small. The compiler
checks the syntax and type-safety based on these declarations, speeding up
the compilation process compared to having all the code definitions in the
main file.
• How to include a header file:

Header files are included using the #include preprocessor directive.

o For standard library headers (e.g., iostream):

C++

#include <header_name>

#include <iostream>

o For user-defined or local header files (e.g., myheader.h):

C++

#include "header_name.h"

#include "myheader.h"

3. (a) C++ Program to Compute Sum of First n Natural Numbers

C++

#include <iostream>

using namespace std;

int main() {

int n;

long long sum = 0; // Use long long for the sum to prevent overflow for large n

cout << "Enter a positive integer n: ";

cin >> n;

if (n < 1) {

cout << "Please enter a positive integer." << endl;

return 1;

}
// Use a for loop to iterate from 1 up to n

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

sum += i; // Add the current number to the sum

cout << "The sum of the first " << n << " natural numbers is: " << sum << endl;

return 0;

3. (b) C++ Program to Reverse the Digits of an Integer

This is typically done by repeatedly taking the last digit using the modulo operator (% 10)
and building the reversed number, while simultaneously removing the last digit from the
original number using integer division (/ 10).

C++

#include <iostream>

using namespace std;

int main() {

int originalNumber, reversedNumber = 0, remainder;

cout << "Enter an integer: ";

cin >> originalNumber;

int tempNumber = originalNumber; // Store the original for processing

// Loop until the number becomes 0

while (tempNumber != 0) {

// Get the last digit


remainder = tempNumber % 10;

// Build the reversed number

// Multiply by 10 to shift current digits to the left

reversedNumber = reversedNumber * 10 + remainder;

// Remove the last digit from the original number

tempNumber /= 10;

cout << "The reverse of " << originalNumber << " is: " << reversedNumber << endl;

return 0;

3. (c) C++ Program for Fibonacci Sequence

The Fibonacci sequence is a series where the next term is the sum of the previous two
terms. The sequence usually starts with 0 and 1: 0, 1, 1, 2, 3, 5, 8, 13, ...

C++

#include <iostream>

using namespace std;

int main() {

int n, first = 0, second = 1, next;

cout << "Enter the number of Fibonacci terms (n): ";

cin >> n;
if (n <= 0) {

cout << "Please enter a positive integer." << endl;

return 1;

cout << "Fibonacci Sequence up to term " << n << ":\n";

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

if (i <= 1) {

// The first two terms are fixed (0 and 1)

next = i;

} else {

// Next term is the sum of the previous two

next = first + second;

// Shift the values for the next iteration

first = second;

second = next;

cout << next << " ";

cout << endl;

return 0;

4. (a) Pointer Statements (True or False)

• (i) In C++ a pointer may be assigned the address of a variable of any type without
any problem.
o False. C++ is strongly typed. A pointer must be of the same type as the
variable it points to (e.g., an int* must point to an int), or an explicit cast is
required, or it must be a void* (a generic pointer). Implicitly assigning a
different type's address will typically result in a compiler warning or error.

• (ii) The * stands for address of the pointer variable.

o False. The asterisk * has two main uses with pointers:

1. In declaration (int* ptr;), it declares a pointer.

2. In an expression (*ptr), it is the dereference operator and gives the


value at the address stored in the pointer. The & symbol is the
address-of operator.

• (iii) You can increment a pointer to point at the next memory location of the type
that it is pointing at.

o True. This is called Pointer Arithmetic. Incrementing an int* by 1 moves the


pointer address by sizeof(int) bytes, making it point to the next integer
element in memory (e.g., in an array).

• (iv) A pointer can be dereferenced before it is declared, and the program will still
run with no issues.

o False. Dereferencing an undeclared (or uninitialized) pointer leads to


Undefined Behavior (e.g., crashing or accessing random memory), and the
compiler will usually flag a dereferencing before declaration as an error.

• (v) In C++, delete is used to free up memory which was allocated using malloc().

o False. The delete operator is used to free up memory allocated using the C++-
specific operator new. Memory allocated with the C function malloc() must
be freed using the C function free().

4. (b) C++ Program for Simple Shape Hierarchy

This program demonstrates Polymorphism using a virtual function in the base class.

C++

#include <iostream>

#include <cmath> // For M_PI

// Base Class
class Shape {

public:

// Virtual function - allows dynamic method resolution at runtime

virtual double area() const = 0; // = 0 makes it a pure virtual function (abstract class)

// Virtual destructor is good practice for polymorphic classes

virtual ~Shape() {}

};

// Derived Class 1

class Circle : public Shape {

private:

double radius;

public:

Circle(double r) : radius(r) {}

// Override the virtual function to calculate circle area

double area() const override {

// Use 3.14159 or M_PI for pi

return 3.14159 * radius * radius;

};

// Derived Class 2

class Rectangle : public Shape {

private:

double length;

double width;
public:

Rectangle(double l, double w) : length(l), width(w) {}

// Override the virtual function to calculate rectangle area

double area() const override {

return length * width;

};

int main() {

double r, l, w;

// --- Circle Input and Calculation ---

std::cout << "Enter the radius for the Circle: ";

std::cin >> r;

Circle circle(r);

// --- Rectangle Input and Calculation ---

std::cout << "Enter the length for the Rectangle: ";

std::cin >> l;

std::cout << "Enter the width for the Rectangle: ";

std::cin >> w;

Rectangle rectangle(l, w);

// Use base class pointers to demonstrate polymorphism

Shape* s1 = &circle;

Shape* s2 = &rectangle;
// Print Results

std::cout << "\n--- Area Results ---\n";

// Calls Circle::area()

std::cout << "Area of Circle: " << s1->area() << std::endl;

// Calls Rectangle::area()

std::cout << "Area of Rectangle: " << s2->area() << std::endl;

return 0;

4. (c) Characteristics of Object-Oriented Programming (OOP)

The five fundamental characteristics (or pillars) of Object-Oriented Programming are:

1. Encapsulation: The mechanism of binding the data (variables) and the code
(methods) that operates on the data into a single unit (a class). It hides the internal
implementation details from the outside world.

2. Abstraction: The process of showing only essential information to the user and
hiding the complex background details. It focuses on what an object does rather than
how it achieves it.

3. Inheritance: The mechanism where a new class (derived class) is created from an
existing class (base class), acquiring the base class's properties and behaviors. This
promotes code reuse.

4. Polymorphism: The ability of an object or function to take on multiple forms. In C++,


this is achieved through function overloading (compile-time) and virtual functions
(runtime). The word means "many forms."

5. Classes and Objects:

o Class: A blueprint or a template for creating objects. It defines the structure


and behavior of objects.

o Object: A run-time entity and an instance of a class. It represents the real-


world entity defined by the class.

5. (a) Output of Switch Statement


The switch statement logic relies on the flow of control and the placement of the break
keyword. Without break, execution continues (falls through) to the next case label.

Code Snippet:

C++

switch (num) {

case 1: cout << "One" << endl;

case 2: cout << "Two" << endl;

break; // Break here

case 3: cout << "Three" << endl;

break;

case 4: cout << "Four" << endl;

break;

default: cout << "Invalid" << endl;

Value of
Execution Flow Output
num

Starts at case 1. Prints "One". Falls through to case 2. Prints "Two".


(i) 1 One\nTwo
Hits break.

(ii) 67 Does not match any case. Jumps to default. Prints "Invalid". Invalid

(iii) 2 Starts at case 2. Prints "Two". Hits break. Two

Assuming num is an int, character 'A' converts to its ASCII value


(iv) A Invalid
(65). Does not match any case. Jumps to default. Prints "Invalid".

(v) This is not a value, but an execution path. If no case matches the
Invalid
default input, the flow jumps to the default label. Prints "Invalid".

5. (b) Default Constructors

A default constructor is a constructor that can be called without any arguments. This means
it either has no parameters or all its parameters have default values.
• If a class does not define any constructor, the C++ compiler automatically provides a
public, inline, and parameterless implicit default constructor that performs basic
initialization.

• If a class defines any constructor (even a parameterized one), the compiler will not
generate the implicit default constructor. In this case, if you still want a
parameterless constructor, you must define it explicitly (an explicit default
constructor).

Example (Explicit Default Constructor):

C++

#include <iostream>

using namespace std;

class MyClass {

private:

int value;

public:

// Explicit Default Constructor (no arguments)

MyClass() {

value = 0; // Initializes value to 0

cout << "Default constructor called. Value set to: " << value << endl;

// Another constructor (parameterized)

MyClass(int v) {

value = v;

cout << "Parameterized constructor called. Value set to: " << value << endl;

};
int main() {

// Calls the Default Constructor (parameterless)

MyClass obj1;

// Calls the Parameterized Constructor

MyClass obj2(50);

return 0;

5. (c) Constructor Overloading

Constructor Overloading is when a class has multiple constructors with the same name
(which must be the class name) but with a different signature (i.e., a different number or
type of parameters).

This allows objects of the same class to be initialized in different ways, providing flexibility to
the user.

Example:

C++

#include <iostream>

#include <string>

using namespace std;

class Book {

private:

string title;

string author;

int year;

public:

// 1. Default Constructor (Signature: No parameters)


Book() {

title = "Unknown";

author = "Unknown";

year = 0;

cout << "Default Book created." << endl;

// 2. Parameterized Constructor (Signature: string, string)

Book(string t, string a) {

title = t;

author = a;

year = 2024; // Default year

cout << "Book with Title/Author created." << endl;

// 3. Parameterized Constructor (Signature: string, string, int)

Book(string t, string a, int y) {

title = t;

author = a;

year = y;

cout << "Full Book record created." << endl;

void display() {

cout << "Title: " << title << ", Author: " << author << ", Year: " << year << endl;

};
int main() {

// Uses Constructor 1

Book book1;

// Uses Constructor 2

Book book2("1984", "George Orwell");

// Uses Constructor 3

Book book3("Dune", "Frank Herbert", 1965);

cout << "\n--- Book Details ---\n";

[Link]();

[Link]();

[Link]();

return 0;

6. (a) C++ Program for Simple Library System

This program uses an array of pointers to dynamically allocated Book objects and
demonstrates the requested functionalities.

C++

#include <iostream>

#include <string>

#include <vector> // Using vector for dynamic array functionality

#include <limits> // For numeric_limits

using namespace std;


// Class to hold Book information

class Book {

public:

string title;

string author;

int year;

Book(string t, string a, int y) : title(t), author(a), year(y) {}

void display() const {

cout << " Title: " << title

<< ", Author: " << author

<< ", Year: " << year << endl;

// Virtual destructor is good practice when deleting objects via base class pointers,

// though here we only use Book pointers.

virtual ~Book() {}

};

// Global container to store pointers to dynamically allocated Book objects

vector<Book*> library;

// Function to add a new book

void addBook() {

string title, author;

int year;
[Link](numeric_limits<streamsize>::max(), '\n'); // Clear buffer for getline

cout << "Enter Title: ";

getline(cin, title);

cout << "Enter Author: ";

getline(cin, author);

cout << "Enter Year of Publication: ";

cin >> year;

// Dynamically allocate a new Book object and store its pointer

Book* newBook = new Book(title, author, year);

library.push_back(newBook);

cout << "Book added successfully!" << endl;

// Function to display all books

void displayBooks() {

if ([Link]()) {

cout << "The library is empty." << endl;

return;

cout << "\n--- Library Catalogue (" << [Link]() << " Books) ---\n";

for (size_t i = 0; i < [Link](); ++i) {

cout << "[" << i + 1 << "]: ";

library[i]->display(); // Use pointer -> operator

cout << "--------------------------------\n";

}
// Function to delete a book

void deleteBook() {

if ([Link]()) {

cout << "No books to delete." << endl;

return;

displayBooks(); // Show current list

int index;

cout << "Enter the book number (1 to " << [Link]() << ") to delete: ";

cin >> index;

if (index >= 1 && index <= (int)[Link]()) {

// Index in vector is 0-based

Book* bookToDelete = library[index - 1];

// 1. Free the dynamically allocated memory

delete bookToDelete;

// 2. Remove the pointer from the vector

[Link]([Link]() + (index - 1));

cout << "Book " << index << " deleted successfully." << endl;

} else {

cout << "Invalid book number." << endl;

}
int main() {

int choice;

do {

cout << "\n--- Library System Menu ---\n";

cout << "1. Add New Book\n";

cout << "2. Display All Books\n";

cout << "3. Delete a Book\n";

cout << "4. Exit\n";

cout << "Enter your choice: ";

cin >> choice;

switch (choice) {

case 1: addBook(); break;

case 2: displayBooks(); break;

case 3: deleteBook(); break;

case 4: cout << "Exiting Library System. Goodbye!" << endl; break;

default: cout << "Invalid choice. Please try again." << endl;

} while (choice != 4);

// IMPORTANT: Cleanup any remaining dynamically allocated memory before program exit

for (Book* book : library) {

delete book;

[Link](); // Clear the vector of pointers

return 0;
}

6. (b) C++ Program to Swap Values Using Pointers

The core idea is that the function must accept pointers (addresses) and use the dereference
operator (*) to modify the actual values stored at those addresses.

C++

#include <iostream>

using namespace std;

// Function to swap the values of two integers using pointers

void swapValues(int* ptrA, int* ptrB) {

// Create a temporary variable to hold the value of the first variable

int temp = *ptrA;

// Assign the value of the second variable to the first

*ptrA = *ptrB;

// Assign the original value of the first variable (stored in temp) to the second

*ptrB = temp;

int main() {

int x = 100;

int y = 200;

cout << "Before swap: x = " << x << ", y = " << y << endl;

// Pass the addresses of x and y to the function


swapValues(&x, &y);

cout << "After swap: x = " << x << ", y = " << y << endl;

return 0;

6. (c) Pointer Declaration Validity

Declaration Valid/Invalid Explanation

(i) char* ptr = Declares ptr as a pointer to a char and initializes it


Valid
&someCharVariable; with the address of a char variable.

Declares ptr as a pointer to an int. However, ptr2 is


declared as a regular int variable, not a pointer. A
(ii) int* ptr, ptr2; Valid
more clear/safer way for two pointers is int *ptr,
*ptr2;

Declares ptr as a pointer to a float and initializes it


(iii) float* ptr = new
Valid with the memory address of a newly dynamically
float;
allocated float variable.

Declares ptr1 as a pointer to an integer pointer (a


(iv) int** ptrl; Valid double pointer). This is often used for 2D arrays or
dynamic arrays of pointers.

The correct syntax for declaring a pointer to a


(v) double ptr*; Invalid double is double* ptr;. The asterisk must follow the
type or precede the variable name.

7. Explain the following:

(i) Function Overloading

Function Overloading is a feature of C++ that allows you to define multiple functions with
the same name but with a different signature (different number or type of parameters). The
return type alone is not sufficient to distinguish overloaded functions.
• The compiler decides which function to call based on the number and types of
arguments passed during the function call (this is a form of compile-time
polymorphism).

• Example:

C++

int add(int a, int b) { return a + b; } // Signature: (int, int)

double add(double a, double b) { return a + b; } // Signature: (double, double)

int add(int a, int b, int c) { return a + b + c; } // Signature: (int, int, int)

(ii) Arrays in C++

An array is a collection of items of the same data type stored at contiguous memory
locations. These items are accessed using a common name and an index (or subscript),
which starts from 0.

• Fixed Size: Standard C++ arrays have a fixed size that must be known at compile time.

• Syntax: dataType arrayName[arraySize];

• Example:

C++

int numbers[5] = {10, 20, 30, 40, 50};

// The first element is numbers[0] (value 10).

// The last element is numbers[4] (value 50).

(iii) Inheritance

Inheritance is a fundamental principle of Object-Oriented Programming (OOP) that allows a


new class to be based on an existing class.

• The existing class is called the Base Class (or Parent Class).

• The new class is called the Derived Class (or Child Class).

• The derived class inherits the public and protected members (data and methods) of
the base class.

• This mechanism promotes code reusability and establishes an "is-a" relationship


(e.g., a Dog is a Animal).

• Syntax:

C++
class DerivedClass : accessSpecifier BaseClass {

// new members

};

You might also like