Unit6 - Subjective Questions
CSE101 • Practice Questions with Detailed Answers
Define a Structure in C/C++. Explain the syntax for declaring a structure, defining structure variables, and accessing their members with an example.
Definition of Structure
A structure is a user-defined data type in C/C++ that allows you to combine data items of different kinds (types) under a single name. It is used to represent a record, such as a student's profile (name, roll number, marks).
Syntax
c
struct structure_name {
data_type member1;
data_type member2;
...
};
Defining Structure Variables
Variables can be defined either at the time of declaration or separately inside the main function.
c
struct Student s1; // In C
Student s2; // In C++
Accessing Members
Members are accessed using the dot operator (.).
Example
c
struct Point {
int x;
int y;
};
int main() {
struct Point p1;
p1.x = 10; // Accessing member x
p1.y = 20; // Accessing member y
return 0;
}
Explain the concept of Pointers to Structures. How are structure members accessed using a pointer? Illustrate with a code snippet.
Pointers to Structures
A pointer to a structure is a variable that holds the memory address of a structure variable. This is useful for passing structures to functions efficiently (by reference) rather than by value.
Accessing Members
When using a pointer to a structure, members are accessed using the arrow operator (->), which is a combination of dereference and dot operators.
- Syntax:
pointer_name->member_name - Alternative:
(*pointer_name).member_name
Example
c
include <stdio.h>
struct Rectangle {
int length;
int width;
};
int main() {
struct Rectangle r = {10, 5};
struct Rectangle *ptr = &r;
// Accessing using arrow operator
printf("Length: %d
", ptr->length);
// Accessing using dereference and dot
printf("Width: %d
", (*ptr).width);
return 0;
}
Differentiate between Structure and Union with respect to memory allocation and value access. Provide a comparative table.
Difference between Structure and Union
| Feature | Structure (struct) |
Union (union) |
|---|---|---|
| Keyword | Defined using the struct keyword. |
Defined using the union keyword. |
| Memory Allocation | Memory is allocated for all members explicitly. The size is greater than or equal to the sum of sizes of all members. | Memory is allocated only for the largest member. All members share this same memory location. |
| Accessing Members | All members can be accessed and store distinct values simultaneously. | Only one member can be accessed or store a meaningful value at a time. |
| Value Alteration | Changing one member does not affect others. | Changing one member overwrites the values of other members. |
| Size Example | struct A { int i; char c; }; Size sizeof(int) + sizeof(char). |
union B { int i; char c; }; Size = sizeof(int) (assuming int > char). |
What are Nested Structures? Describe how to declare and access members of a nested structure using an example.
Nested Structures
A nested structure is a structure that contains another structure as one of its members. This allows for the creation of complex data types organized hierarchically.
Declaration
One structure is defined first, and then an object of that structure is used as a member in another structure.
Example
c
struct Date {
int day, month, year;
};
struct Employee {
int id;
char name[20];
struct Date dob; // Nested structure
};
Accessing Members
To access the inner structure members, the dot operator is chained.
c
int main() {
struct Employee e1;
e1.id = 101;
// Accessing nested members
e1.dob.day = 15;
e1.dob.month = 8;
e1.dob.year = 1995;
return 0;
}
Compare Procedural Oriented Programming (POP) and Object-Oriented Programming (OOP) paradigms.
POP vs OOP
-
Focus:
- POP: Focuses on functions and the sequence of actions (algorithms). It follows a step-by-step approach.
- OOP: Focuses on objects and data. It models real-world entities.
-
Data Security:
- POP: Data is often global and moves freely from function to function. Less secure.
- OOP: Supports data hiding (encapsulation). Data access is restricted using access specifiers (private, public).
-
Approach:
- POP: Follows a Top-Down approach (breaking main problem into sub-functions).
- OOP: Follows a Bottom-Up approach (designing objects first, then integrating them).
-
Reusability:
- POP: Limited reusability.
- OOP: High reusability through Inheritance.
-
Examples:
- POP: C, Pascal, FORTRAN.
- OOP: C++, Java, Python.
Explain the input and output mechanisms in C++ using cin and cout with appropriate syntax and examples.
Input and Output in C++
C++ uses the standard library iostream for input and output operations via streams.
1. Standard Output (cout)
- Object:
coutstands for "Console Output". It is an object of theostreamclass. - Operator: Uses the Insertion Operator (
<<) to send data to the output stream. - Syntax:
cout << variable/string; - Example:
cpp
int age = 20;
cout << "Age is: " << age << endl;
2. Standard Input (cin)
- Object:
cinstands for "Console Input". It is an object of theistreamclass. - Operator: Uses the Extraction Operator (
>>) to take data from the input stream. - Syntax:
cin >> variable; - Example:
cpp
int x;
cout << "Enter a number: ";
cin >> x;
Note: endl is a manipulator used to insert a new line.
Define Class and Object in C++. How are they related? Write a simple C++ program to define a class Student with data members and member functions.
Definition
- Class: A class is a user-defined data type that acts as a blueprint or template. It encapsulates data (data members) and functions (member functions) that operate on the data into a single unit.
- Object: An object is an instance of a class. When a class is defined, no memory is allocated; memory is allocated only when an object is instantiated.
Relationship
A class is the logical definition (type), while an object is the physical entity (variable) of that type.
Example Program
cpp
include <iostream>
using namespace std;
class Student {
public:
string name;
int rollNo;
void display() {
cout << "Name: " << name << endl;
cout << "Roll No: " << rollNo << endl;
}
};
int main() {
Student s1; // Object creation
s1.name = "John";
s1.rollNo = 101;
s1.display(); // Calling member function
return 0;
}
What are Inline Functions? How do they differ from normal functions? Discuss their advantages.
Inline Functions
An inline function is a function that is expanded in line when it is called. When the compiler encounters the call to an inline function, it replaces the function call with the actual code of the function, rather than jumping to a separate memory location.
Syntax:
cpp
inline return_type function_name(parameters) { ... }
Difference from Normal Functions
- Normal Function: Involves overhead of pushing arguments to stack, jumping to function address, and returning.
- Inline Function: Code substitution happens at compile time. No function call overhead.
Advantages
- Performance: Reduces function call overhead, making execution faster for small functions.
- Optimization: Enables compiler optimizations specific to the context where the code is used.
Note: The inline keyword is a request, not a command. The compiler may ignore it if the function is too complex (e.g., contains loops or recursion).
Explain the concept of Static Data Members in C++ classes. How are they initialized and accessed?
Static Data Members
A static data member is a variable in a class that is shared by all objects of that class.
Key Characteristics:
- There is only one copy of the static member, regardless of how many objects are created.
- It is stored in the static memory area, not inside the object's memory allocation.
- It is initialized to zero by default if no other initialization is provided.
Declaration and Definition
It must be declared inside the class and defined/initialized outside the class.
Example
cpp
class Demo {
public:
static int count; // Declaration
};
// Definition outside class
int Demo::count = 0;
int main() {
Demo d1, d2;
d1.count = 10;
// d2.count will also be 10 because memory is shared
cout << d2.count;
return 0;
}
It can also be accessed using the scope resolution operator: Demo::count.
What are Static Member Functions? How do they differ from non-static member functions?
Static Member Functions
A static member function is a function that belongs to the class rather than any specific object instance.
Key Differences from Non-Static Functions:
- Access Rules: A static member function can only access static data members and other static member functions. It cannot access non-static (instance) members directly.
thisPointer: Static functions do not have athispointer because they are not associated with a specific object instance.- Invocation: They can be called using the class name and scope resolution operator
::, without creating an object.
Example
cpp
class Test {
static int x;
public:
static void show() {
cout << x; // Allowed
// cout << y; // Error if y is non-static
}
};
// In main:
Test::show(); // Calling without object
Explain the method of defining member functions outside the class definition in C++. What operator is used?
Member Functions Outside Class
Member functions can be declared inside the class body but defined (implementation logic) outside the class. This keeps the class definition clean and separates interface from implementation.
Operator Used
The Scope Resolution Operator (::) is used to link the function definition to the class.
Syntax
cpp
return_type ClassName::function_name(parameter_list) {
// body
}
Example
cpp
class Circle {
float radius;
public:
void setRadius(float r);
float getArea();
};
// Definition outside
void Circle::setRadius(float r) {
radius = r;
}
float Circle::getArea() {
return 3.14 radius radius;
}
Distinguish between Structures and Classes in C++. What is the default access specifier for each?
Structures (struct) vs Classes (class) in C++
While both structures and classes in C++ can have data members and member functions, there are fundamental differences in their default behaviors regarding access control.
| Feature | Structure (struct) |
Class (class) |
|---|---|---|
| Default Access Specifier | Members are public by default. | Members are private by default. |
| Usage Convention | Typically used for passive objects that carry data (POD - Plain Old Data). | Typically used for active objects involving data hiding, encapsulation, and behavior. |
| Inheritance Default | When inheriting from a struct, the default mode is public. | When inheriting from a class, the default mode is private. |
Example
cpp
struct A {
int x; // Public by default
};
class B {
int y; // Private by default
};
What is a Union? Write a C program to demonstrate the declaration of a union and how modifying one member affects the others.
Definition
A Union is a user-defined data type where all members share the same memory location. The size of the union is determined by the size of its largest member. At any given time, a union can store a value for only one of its members.
Program Demonstration
c
include <stdio.h>
include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data;
data.i = 10;
printf("data.i : %d
", data.i);
data.f = 220.5;
printf("data.f : %f
", data.f);
// Note: data.i is now corrupted because memory is overwritten
printf("data.i (after float assignment): %d
", data.i);
strcpy(data.str, "C Programming");
printf("data.str : %s
", data.str);
// Note: data.f is now corrupted
printf("data.f (after string assignment): %f
", data.f);
return 0;
}
Compare Enumerations, Structures, Unions, and Classes.
Comparison of User-Defined Types
-
Enumeration (
enum):- Purpose: Used to define a set of named integer constants.
- Memory: Stores a single integer value.
- Usage: Increases code readability (e.g., days of week, colors).
-
Structure (
struct):- Purpose: Groups variables of different types.
- Memory: Sum of sizes of all members (plus padding).
- Default Access (C++): Public.
-
Union (
union):- Purpose: Groups variables sharing the same memory.
- Memory: Size of the largest member.
- Usage: Memory constrained environments.
-
Class (
class):- Purpose: Core of OOP; binds data and functions together.
- Memory: Similar to struct (sum of data members).
- Default Access: Private.
- Features: Supports encapsulation, inheritance, polymorphism.
How are structure members initialized? Discuss both compile-time initialization and designation initialization (C99 standard).
Initialization of Structures
Structure variables can be initialized when they are declared, similar to arrays.
1. Compile-time Initialization (Standard)
Values are assigned in the order of the members defined in the structure.
c
struct Point {
int x, y;
};
struct Point p1 = {10, 20};
If partial values are provided, the remaining are initialized to 0.
2. Designated Initialization (C99 Standard)
Allows initialization of specific members by name, in any order.
c
struct Point p2 = {.y = 50, .x = 100};
3. Copy Initialization
A structure variable can be initialized by another existing structure variable of the same type.
c
struct Point p3 = p1;
Explain Access Specifiers in C++. What are public and private members?
Access Specifiers
Access specifiers determine the visibility and accessibility of class members (variables and functions).
-
Private:
- Scope: Members declared as
privatecan only be accessed from within the class (by member functions or friends). - Purpose: Implements data hiding and encapsulation. External code cannot modify these directly.
- Default: In a
class, members are private by default.
- Scope: Members declared as
-
Public:
- Scope: Members declared as
publiccan be accessed from anywhere in the program (e.g., insidemainor other functions). - Purpose: Defines the interface of the class through which the outside world interacts with the object.
- Scope: Members declared as
Example
cpp
class Box {
private:
double width; // Hidden data
public:
void setWidth(double w) { width = w; } // Public interface
};
What is an Array of Structures? Describe how to declare and traverse an array of structures with an example.
Array of Structures
An array of structures is an array where each element is a structure variable. This is useful for storing multiple records of the same type, such as a list of 50 students.
Declaration Syntax
c
struct StructureName arrayName[size];
Accessing
Access individual structures using the array index: arrayName[index].memberName.
Example
c
include <stdio.h>
struct Book {
char title[30];
int price;
};
int main() {
struct Book library[2]; // Array of 2 books
// Input
for(int i=0; i<2; i++) {
printf("Enter title and price: ");
scanf("%s %d", library[i].title, &library[i].price);
}
// Output
for(int i=0; i<2; i++) {
printf("Book %d: %s, $%d
", i+1, library[i].title, library[i].price);
}
return 0;
}
Describe the syntax for declaring a Union. Can a union contain a structure? Explain with an example.
Union Declaration Syntax
c
union union_name {
data_type member1;
data_type member2;
...
};
Union Containing a Structure
Yes, a union can contain a structure, and a structure can contain a union. This is often used when data interpretation depends on a specific type tag.
Example
c
struct Point {
int x, y;
};
union ShapeData {
int radius; // For Circle
struct Point p; // For a Point coordinate
};
int main() {
union ShapeData sd;
sd.p.x = 10;
sd.p.y = 20;
// sd.radius and sd.p share memory
}
Explain the role of the Scope Resolution Operator (::) in C++ with respect to class member definition and static members.
Role of Scope Resolution Operator (::)
-
Defining Member Functions Outside Class:
It binds a function definition to a specific class. It tells the compiler that the function being defined belongs to the class specified before::.- Syntax:
ClassName::functionName() { ... }
- Syntax:
-
Accessing Static Members:
Static variables and functions belong to the class, not instances. They can be accessed directly using the class name and::.- Syntax:
ClassName::staticVariableorClassName::staticFunction()
- Syntax:
-
Accessing Global Variables:
If a local variable has the same name as a global variable,::variableNameallows access to the global version.
Write a C++ program to create a class Employee with private data members id and salary, and public member functions to input and display the data.
C++ Program: Employee Class
cpp
include <iostream>
using namespace std;
class Employee {
private:
int id;
float salary;
public:
// Function to read data
void getData() {
cout << "Enter Employee ID: ";
cin >> id;
cout << "Enter Salary: ";
cin >> salary;
}
// Function to display data
void showData() {
cout << "------------------" << endl;
cout << "Employee Details:" << endl;
cout << "ID: " << id << endl;
cout << "Salary: $" << salary << endl;
}
};
int main() {
Employee emp;
// Accessing public functions
emp.getData();
emp.showData();
return 0;
}