Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PC Questions

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 17

PC Question Bank

2 Marks Question

Q1. What do you mean by an array? Give any 2 differences between 1D array and 2D
array.

A1. An array is a data structure that stores elements.

Two differences:
1. 1D array is a single line of elements, while 2D array is a grid.
2. In 1D array, you use one index to access elements; in 2D array, you use two (row
and column).

Q2 How to declare 1D and 2D arrays, and also initialize the 1D array and 2D array.

A2 To declare and initialize a 1D array in C:


int arr1D[5] = {1, 2, 3, 4, 5};
To declare and initialize a 2D array in C:
int arr2D[2][3] = {{1, 2, 3}, {4, 5, 6}};

In this code, `arr1D` is a 1D array with 5 elements, and `arr2D` is a 2D array with
2 rows and 3 columns.

Q3. What do you mean by user defined functions?

A3. User-defined functions are custom functions created by the programmer to


perform specific tasks in a program. They allow for modular and reusable code,
improving the organization and readability of a program.

Q4. Main function is a special kind of user defined function, how is it different
from other user defined functions?

A4. `main` is the program's starting point, fixed in name, and runs automatically.
Other user-defined functions are created by the programmer and executed when
explicitly called.

Q5. Can we have the number of initializers in a given 1D array more than its size?

A5. No, the number of initializers in a 1D array cannot exceed its size. It must
have the same or fewer initializers than the size specified during declaration.

Q6. Can we access any given 1D array beyond its size? Comment.

A6. Accessing elements beyond the size of a 1D array can lead to unpredictable
behavior, memory corruption, or program crashes. It's crucial to ensure you stay
within the array's defined bounds to maintain program stability and correctness.

Q7. Can we use string variables with assignment operators?

A7. Yes, you can use assignment operators (like '=') with string variables to
assign values to them or to update their contents in many programming languages.

Q8. How many arguments are there in ‘strncpy()’ function?

A8. The `strncpy()` function typically takes three arguments:

1. The destination string where the data is copied.


2. The source string from which data is copied.
3. The maximum number of characters to copy from the source to the destination.
Q9. What is the importance of ‘null’ character in strings?

A9. The null character (`'\0'`) is vital in strings as it indicates the string's
endpoint, enabling proper handling and determination of string length.

Q10. Write down the ways to initialize a given character array.

A10. You can initialize a character array:


1. Directly with a string.
2. Using the `strcpy` function.
3. By assigning individual elements.
4. By filling the array in a loop.

Q11. Is it compulsory to put ‘/0’ in the following initialization? - char name[50]


= “vikas”;

A11.Yes, it's essential to include `'\0'` in the initialization of a character


array to make it a null-terminated string, which is a requirement for proper string
handling in C

Q12. Memory is given to an array at ___RUN___________ time

Q13. Calculate the address of an element in a given array at index 14.


(Hint: - Array is an integer array and base address is 2000)

A13. Memory allocation for an array occurs either at **compile time** for static
arrays, where the size is known beforehand, or at **run time** for dynamic arrays,
where the size can be determined during program execution.

Q14. Is it compulsory to declare callee function before function call in the body
of a called function?

A14. It's not required, but it's a recommended practice to declare functions before
calling them within another function to ensure the compiler knows the function's
signature and improve code organization.

Q15. Can a function return more than 2 values? Justify your answer.

A15. A function can directly return only one value, but it can indirectly return
multiple values by encapsulating them in data structures like arrays, structs, or
tuples. This allows for practical multiple-value return.

Q16. Can we have more than 1 return statement in a user defined function?

A16. Yes, a user-defined function can have more than one return statement. The
function will return the value from the first executed return statement it
encounters, and subsequent return statements will terminate the function's
execution.

Q17. What is the default return type of a user defined function where a return type
is not specified?

A17. The default return type of a user-defined function, when not specified, is
typically assumed to be `int` in languages like C

Q18. Is it compulsory to mention the name of dummy arguments in function


prototyping?
A18. No, it's not mandatory to mention the names of dummy arguments in function
prototypes in C/C++, but it's a good practice for code readability and
documentation.

Q19. What is a self-referential structure?

A19. A self-referential structure is a data structure where one of its parts


contains a reference or a pointer to another element of the same type, enabling the
creation of linked data structures such as linked lists or trees.

Q20. What is the difference between structures and unions in terms of object size?

A20. Structures allocate separate memory for each member, potentially resulting in
a larger object size, while unions share the same memory space and have a size
equal to the largest member.

Q21. Give some examples of user defined data types in C.

A21. User-defined data types in C include structures (structs), enumerations


(enums), and typedefs. For example, you can define a struct to group related data,
an enum to create a set of named constants, or use typedef to create custom type
aliases.

Q22. Write a program that prints the size of a structure data type.

A22. #include <stdio.h>


struct SampleStruct {
int a;
char b;
double c;
};
int main() {
struct SampleStruct myStruct ;

size_t size = sizeof(myStruct);

printf("Size of SampleStruct: %lu bytes\n", size);

return 0;
}

5 Marks Question

Q1. Write a Program to input or to populate a given array ‘a’ of 5x5.

A1. #include <stdio.h>

int main() {
int a[5][5];

printf("Enter elements for the 5x5 array:\n");

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


for (int j = 0; j < 5; j++) {
printf("Enter element at a[%d][%d]: ", i, j);
scanf("%d", &a[i][j]);
}
}
printf("The populated array 'a' is:\n");

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


for (int j = 0; j < 5; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}

return 0;
}

Q2. Write a Program to copy 1 string to another string without string copy
function.

A2. #include <stdio.h>

void stringCopy(char *dest, const char *src) {


while (*src) {
*dest = *src;
dest++;
src++;
}
*dest = '\0';
}

int main() {
char source[] = "Hello, World!";
char destination[50];

stringCopy(destination, source);

printf("Source string: %s\n", source);


printf("Copied string: %s\n", destination);

return 0;
}

Q3. Write a code to input string without ‘scanf’ and ‘gets’ function.

A3. #include <stdio.h>

int main() {
char inputString[100];
char c;
int i = 0;

printf("Enter a string: ");

while ((c = getchar()) != '\n' && i < sizeof(inputString) - 1) {


inputString[i] = c;
i++;
}

inputString[i] = '\0';

printf("You entered: %s\n", inputString);


return 0;
}

Q4. Write down the name, purpose and general syntax of any 10 in-built string
functions.

A4. 1. **strlen**: Get string length


- Syntax: `size_t strlen(const char *str);`

2. **strcpy**: Copy a string


- Syntax: `char *strcpy(char *dest, const char *src);`

3. **strcat**: Concatenate strings


- Syntax: `char *strcat(char *dest, const char *src);`

4. **strcmp**: Compare strings


- Syntax: `int strcmp(const char *str1, const char *str2);`

5. **strchr**: Find character in a string


- Syntax: `char *strchr(const char *str, int c);`

6. **strstr**: Find substring in a string


- Syntax: `char *strstr(const char *haystack, const char *needle);`

7. **strtok**: Tokenize a string


- Syntax: `char *strtok(char *str, const char *delimiters);`

8. **strncat**: Concatenate with limit


- Syntax: `char *strncat(char *dest, const char *src, size_t n);`

9. **strncmp**: Compare with limit


- Syntax: `int strncmp(const char *str1, const char *str2, size_t n);`

10. **strncpy**: Copy with limit


- Syntax: `char *strncpy(char *dest, const char *src, size_t n);`

Q5. Differentiate between the working of ‘gets’ and ‘scanf’ using a suitable code.
OR
Differentiate between the working of reading a string using ‘gets’ and ‘scanf’.

A5. #include <stdio.h>

int main() {
char name[50];

printf("Enter your name using 'gets': ");


gets(name);

printf("You entered: %s\n", name);

fflush(stdin);

printf("Enter your name using 'scanf': ");


scanf("%s", name);

printf("You entered: %s\n", name);

return 0;
}

Q6. Write down a program to input 10 strings.

A6. #include <stdio.h>

int main() {
char strings[10][50];

printf("Enter 10 strings:\n");

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


printf("Enter string %d: ", i + 1);
scanf("%s", strings[i]);
}

printf("You entered the following strings:\n");

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


printf("String %d: %s\n", i + 1, strings[i]);
}

return 0;
}

Q7. Write down the advantages of array. Or when it is necessary to use arrays.

A7. Arrays have several advantages:

1. **Data Storage**: Arrays allow you to efficiently store and organize a


collection of data elements of the same type in a single structure.

2. **Sequential Access**: Elements in an array are stored in contiguous memory


locations, enabling fast and efficient sequential access using indices.

3. **Memory Efficiency**: Arrays use minimal memory overhead as they store elements
in a contiguous block, avoiding the need for additional data structures to manage
element addresses.

4. **Simplicity**: Arrays are easy to understand and work with, using basic
indexing for element access.

5. **Performance**: Array elements can be accessed quickly by index, making them


ideal for situations requiring rapid data retrieval.

Arrays are necessary to use when:

1. **Organizing Data**: You need to group and manage related data efficiently
within a single structure.

2. **Sequential Access**: Your program requires efficient, sequential access to


elements.

3. **Fixed Size**: The number of elements is known and remains constant during
program execution.

4. **Performance**: Speed and efficiency are critical for data retrieval and
manipulation.
5. **Consistency**: You want a straightforward and uniform way to handle elements
of the same type.

Q8. What do you mean by modular programming? Write down its advantages.

A8. Modular programming is an approach to software development that involves


dividing a program into smaller, independent modules or components. Here are its
key advantages in a concise format:

1. **Ease of Development**: Modular programming simplifies the development process


by breaking a complex program into smaller, manageable modules, allowing developers
to work on individual parts.

2. **Code Reusability**: Modules are self-contained and can be reused in different


parts of the program, reducing redundancy and saving development time.

3. **Maintenance and Debugging**: Modular design makes it easier to identify and


fix issues since problems are localized within specific modules, simplifying
maintenance and debugging.

4. **Scalability**: New features or functionality can be added by creating and


integrating new modules, ensuring the program remains adaptable and extensible.

5. **Improved Collaboration**: Multiple developers can work on different modules


simultaneously, promoting collaboration and speeding up development efforts.

Q9. Demonstrate the concepts of modular programming with the help of a small code.

A9. #include <stdio.h>

float calculateArea(float length, float width) {


return length * width;
}

float calculatePerimeter(float length, float width) {


return 2 * (length + width);
}

int main() {
float length, width;

printf("Enter the length of the rectangle: ");


scanf("%f", &length);

printf("Enter the width of the rectangle: ");


scanf("%f", &width);

float area = calculateArea(length, width);


float perimeter = calculatePerimeter(length, width);

printf("Area of the rectangle: %.2f\n", area);


printf("Perimeter of the rectangle: %.2f\n", perimeter);

return 0;
}

Q10. Write a code to multiply 2 numbers using a function ‘mul()’ which takes 2
arguments and returns 1 value.
A10. #include <stdio.h>

float mul(float num1, float num2) {


return num1 * num2;
}

int main() {
float number1, number2, result;

printf("Enter the first number: ");


scanf("%f", &number1);

printf("Enter the second number: ");


scanf("%f", &number2);

result = mul(number1, number2);

printf("Result of multiplication: %.2f\n", result);

return 0;
}

Q11. Compare and contrast actual arguments and formal arguments.

Actual arguments and formal arguments are essential concepts related to function
parameters in programming. Here's a concise comparison in 5 points:

**Actual Arguments (Actual Parameters):**

1. Actual arguments are the values or expressions provided when calling a function.
2. They represent the real data that the function will operate on during its
execution.
3. The data types of actual arguments must match the expected data types of the
corresponding formal parameters.
4. Actual arguments are typically passed by value, meaning a copy of the argument
is sent to the function.
5. For example, in a function call like `foo(5, "Hello")`, `5` and `"Hello"` are
actual arguments.

**Formal Arguments (Formal Parameters):**

1. Formal arguments are the placeholders defined in the function's parameter list.
2. They act as variables within the function, receiving values from the actual
arguments when the function is called.
3. Formal arguments specify the expected data type and name of the parameters that
the function will work with.
4. By default, formal arguments are passed by value, where they receive copies of
values from the actual arguments.
5. In a function declaration like `void foo(int x, char *str)`, `int x` and `char
*str` are formal arguments.

**Comparison:**

- Actual arguments represent the actual data provided when calling a function,
while formal arguments are variables declared within the function's definition.
- There should be a match in data types between actual arguments and the expected
data types of the formal parameters in the function.
- Both actual and formal arguments are typically passed by value, which involves
working with copies of the values.

**Contrast:**

- Actual arguments are values or expressions passed during the function call, while
formal arguments are variables defined in the function's parameter list.
- Actual arguments represent specific, real values, while formal arguments act as
placeholders for data to be used within the function's scope.

Q12. What are the rules that govern the passing of arrays to a function?

A12. When passing arrays to a function in programming, there are important rules to
consider, summarized in 5 points:

1. **Pass by Reference**: Arrays are passed to functions by reference, meaning that


the function receives a reference to the original array in memory, not a copy of
the entire array.

2. **No Array Size**: You typically don't need to specify the array size when
passing it to a function. The function can determine the size based on the data
type and pointer arithmetic.

3. **Array Declaration**: The function parameter for receiving an array should be


declared as a pointer to the array's data type (e.g., `int[]` or `int*`).

4. **Array Modification**: Any modifications made to the array within the function
affect the original array outside the function since you are working with the same
memory location.

5. **Array Bounds**: Be careful to avoid accessing elements beyond the array's


bounds to prevent undefined behavior or memory corruption.

Q13. Distinguish between global and local variables with the help of an example.

A13. Global Variables:

1. Scope: Global variables are declared outside of any function or block


and are accessible from anywhere in the program.
2. Lifetime: They exist for the entire duration of the program, from the
program’s start to its end.
3. Example:

#include <stdio.h>

int globalVar = 10; // Global variable

int main() {
printf("Global variable: %d\n", globalVar);
return 0;
}

Local Variables:

1. Scope: Local variables are declared inside a specific function or block


and are only accessible within that function or block.
2. Lifetime: They exist only while the function or block is executing and
are destroyed when it exits.
3. Example:
#include <stdio.h>

void exampleFunction() {
int localVar = 5; // Local variable
printf("Local variable: %d\n", localVar);
}

int main() {
exampleFunction();
// printf("Local variable: %d\n"); // This would result in an error
return 0;
}

Q14. What is function prototyping? Why is it necessary?

A14. Function prototyping is the declaration of a function’s signature before it’s


used in a program. Here are 5 key points:

1. Declaration: Prototyping provides the compiler with essential


information about a function’s name, return type, and parameter types.
2. Compile-Time Checks: It allows the compiler to check for correct
function usage during compilation, catching errors early.
3. Order Independence: Functions can be called in any order because the
compiler knows their signatures.
4. Modular Programming: Prototypes in header files enable code reuse and
modular programming.
5. Documentation and Error Detection: Prototypes serve as documentation
and help detect usage discrepancies, reducing runtime errors.

Q15. Describe the ways of passing parameters to functions. When do you prefer to
use each of them?

A15. Parameters can be passed to functions in various ways in programming, and the
choice depends on the specific needs of your code. Here are common ways and when to
use them:

1. **Pass by Value**:
- A copy of the argument's value is passed to the function.
- Use when you want to work with a local copy of the data and prevent changes to
the original value.

2. **Pass by Reference/Pointer**:
- A reference or pointer to the original data is passed to the function.
- Use when you need to modify the original data or avoid copying large data
structures for efficiency.

3. **Passing Arrays**:
- Arrays are often passed as pointers to their first element (pass by
reference).
- Use this when you want to work with the original array and potentially modify
its contents.

4. **Passing by Constant Reference/Pointer**:


- Parameters can be declared as constant (e.g., `const int *`) to prevent
modifications.
- Use when you want to ensure data integrity and prevent accidental changes.

5. **Pass by Name** (Not common):


- In some languages, you can pass parameters by their name for explicit mapping.
- Use when you need to specify which arguments correspond to which parameter

Q16. What is recursion? Explain recursion with the help of an example.

A16. Recursion is a programming technique where a function calls itself to solve a


problem. It involves a base case to terminate the recursion and a recursive case to
break down the problem.

Example: Calculating the factorial of a number with a recursive function.

```c
int factorial(int n) {
if (n == 0) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive case
}
}

Q17. How does a structure differ from an array?

A17. Structure:

1. Data Types: Structures can store variables of different data types


within a single unit. They allow for grouping diverse data types together.
2. Elements Access: Elements in a structure are accessed using names
(member names or fields). Each element has a unique identifier within the
structure.
3. Size: The size of a structure is not fixed and depends on the sizes of
its individual members. It is typically larger than an array of the same number of
elements due to potential padding.
4. Usage: Structures are used to represent complex data types or objects.
For example, you might define a structure to represent a point with both x and y
coordinates.

Array:

1. Data Types: Arrays store variables of the same data type. All elements
in an array are of the identical data type.
2. Element Access: Elements in an array are accessed using indices
(numeric positions). They do not have unique names; their identification is based
on their position in the array.
3. Size: The size of an array is fixed when declared and remains constant
throughout its lifetime. It is determined by the number of elements and the data
type.
4. Usage: Arrays are used when you need a collection of homogeneous data,
such as a list of integers, or when you want to work with data in a systematic,
ordered manner.

Q18. State the rules for initializing structures.

A18. Rules for initializing structures in programming:

1. **Member-wise Initialization**: Initialize structure members one by one in the


order they are defined. For example, if you have a structure `struct Point` with
members `x` and `y`, you initialize them as `struct Point p; p.x = 3; p.y = 4;`.

2. **Order Matters**: The order in which you provide initial values should match
the order of structure members. The first value initializes the first member, the
second initializes the second member, and so on.

3. **Designated Initializers (C99+)**: In C99 and later, you can use designated
initializers to specify which members are being initialized. For instance, you can
write `struct Point p = {.x = 7};` to initialize only the `x` member.

4. **Initialization List**: You can use an initialization list enclosed in curly


braces `{}` to initialize all the structure members. The values in the list should
correspond to the order of member declaration. For example, `struct Point p = {5,
6};` initializes both `x` and `y`.

5. **Omitted Members**: If you don't initialize all the members in a structure, the
remaining members will be initialized with default values based on their data types
(e.g., 0 for numeric types or `null` for pointers).

Q19. Compare and contrast unions and structures.

A19. Structures and unions are both compound data types in programming, but they
differ significantly:

**Structures**:

- Group variables of different data types.


- Allocate memory for each member individually.
- Members do not share memory.
- Access using unique member names with the dot `.` operator.
- Commonly used for objects with multiple attributes.

**Unions**:

- Also group variables of different data types.


- Allocate memory for the largest member; all members share this memory.
- Members share memory, and only one member can hold a value at a time.
- Access using unique member names with the dot `.` operator.
- Used when you need to store different types of data in a shared memory location,
often for switching between them.

10 Marks Questions

Q1. Write a program to transpose a given Matrix.

A1. #include <stdio.h>

int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int transposed[3][3];

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


for (int j = 0; j < 3; j++) {
transposed[i][j] = matrix[j][i];
}
}

printf("Original Matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}

printf("Transposed Matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d\t", transposed[i][j]);
}
printf("\n");
}

return 0;
}

Q2. Write a program to add 2 matrices.

A2. #include <stdio.h>

int main() {
int rows, cols;

printf("Enter the number of rows: ");


scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);

int matrix1[rows][cols];
int matrix2[rows][cols];
int result[rows][cols];

printf("Enter elements of the first matrix:\n");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix1[i][j]);
}
}

printf("Enter elements of the second matrix:\n");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix2[i][j]);
}
}

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


for (int j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

printf("Resultant Matrix after addition:\n");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d\t", result[i][j]);
}
printf("\n");
}

return 0;
}

Q3. Write a program to multiply 2 matrices.

A3. #include <stdio.h>

int main() {
int r1, c1, r2, c2;
printf("Enter dimensions: ");
scanf("%d%d%d%d", &r1, &c1, &r2, &c2);
if (c1 != r2) {
printf("Matrix multiplication is not possible.\n");
return 1;
}
int a[r1][c1], b[r2][c2], result[r1][c2];
for (int i = 0; i < r1; i++)
for (int j = 0; j < c1; j++)
scanf("%d", &a[i][j]);
for (int i = 0; i < r2; i++)
for (int j = 0; j < c2; j++)
scanf("%d", &b[i][j]);
for (int i = 0; i < r1; i++)
for (int j = 0; j < c2; j++) {
result[i][j] = 0;
for (int k = 0; k < c1; k++)
result[i][j] += a[i][k] * b[k][j];
}
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
printf("%d\t", result[i][j]);
}
printf("\n");
}
return 0;
}

Q4. Write a program to find sum of diagonal elements of a square matrix.

A4. #include <stdio.h>

int main() {
int n;

printf("Enter the size of the square matrix: ");


scanf("%d", &n);

int matrix[n][n];

printf("Enter the elements of the matrix:\n");


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
int sum = 0;

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


sum += matrix[i][i];
}

printf("Sum of diagonal elements: %d\n");

return 0;
}

Q5. Perform the following: -


i. Define a structure that can describe a hotel. It should have members that
include name, address, average room charge, hotel grade and number of rooms.
ii. Write a function to perform the following operations to print out hotels with
room charges less than a given value.
iii. To print out the hotels of a given grade in order of charges.

A5. #include <stdio.h>


#include <string.h>

// Define a structure for a hotel


struct Hotel {
char name[100];
char address[200];
double avgRoomCharge;
char grade;
int numRooms;
};

// Function to print hotels with room charges less than a given value
void printHotelsWithChargesLessThan(struct Hotel hotels[], int numHotels, double
maxCharge) {
printf("Hotels with room charges less than %.2f:\n", maxCharge);
for (int i = 0; i < numHotels; i++) {
if (hotels[i].avgRoomCharge < maxCharge) {
printf("Name: %s\n", hotels[i].name);
printf("Address: %s\n", hotels[i].address);
printf("Room Charge: %.2f\n", hotels[i].avgRoomCharge);
printf("Grade: %c\n", hotels[i].grade);
printf("Number of Rooms: %d\n", hotels[i].numRooms);
printf("\n");
}
}
}

// Function to print hotels of a given grade in order of charges


void printHotelsByGradeAndCharge(struct Hotel hotels[], int numHotels, char grade)
{
printf("Hotels of Grade %c in order of room charges:\n", grade);

// Sort hotels by room charges within the specified grade


for (int i = 0; i < numHotels - 1; i++) {
for (int j = 0; j < numHotels - i - 1; j++) {
if (hotels[j].grade == grade && hotels[j].avgRoomCharge > hotels[j +
1].avgRoomCharge) {
struct Hotel temp = hotels[j];
hotels[j] = hotels[j + 1];
hotels[j + 1] = temp;
}
}
}

// Print the sorted list


for (int i = 0; i < numHotels; i++) {
if (hotels[i].grade == grade) {
printf("Name: %s\n", hotels[i].name);
printf("Address: %s\n", hotels[i].address);
printf("Room Charge: %.2f\n", hotels[i].avgRoomCharge);
printf("Grade: %c\n", hotels[i].grade);
printf("Number of Rooms: %d\n", hotels[i].numRooms);
printf("\n");
}
}
}

int main() {
struct Hotel hotels[5] = {
{"Hotel A", "123 Main St", 75.0, 'A', 50},
{"Hotel B", "456 Elm St", 90.0, 'B', 75},
{"Hotel C", "789 Oak St", 65.0, 'A', 60},
{"Hotel D", "101 Pine St", 100.0, 'C', 80},
{"Hotel E", "202 Cedar St", 55.0, 'B', 70}
};

double maxCharge = 80.0;


char gradeToPrint = 'B';

printHotelsWithChargesLessThan(hotels, 5, maxCharge);
printf("\n");
printHotelsByGradeAndCharge(hotels, 5, gradeToPrint);

return 0;
}

Q6. Write a note along with demonstration of Arrays of Nested Structures.

A6. **Arrays of Nested Structures (10 Marks)**

In programming, arrays of nested structures provide an organized way to manage


complex data. Using C as an example, we'll explore this concept concisely.

**Definition of Nested Structure:**

Nested structures contain other structures or data types as members, creating a


structured hierarchy. For instance:

```c
#include <stdio.h>

struct Student {
char name[50];
int age;
};
```

Here, we define a `Student` structure with `name` and `age` members to represent
student data.
**Creating an Array of Nested Structures:**

We can create an array of structures to store data for multiple students:

```c
int main() {
struct Student students[3];
```

This declares an array `students` capable of storing data for three students.

**Initializing and Accessing Data:**

We initialize and access data for each student in the array:

```c
strcpy(students[0].name, "Alice");
students[0].age = 20;

strcpy(students[1].name, "Bob");
students[1].age = 22;

strcpy(students[2].name, "Charlie");
students[2].age = 19;
```

This sets the `name` and `age` for each student in the array.

**Using Loops for Processing:**

Loops help efficiently process array data. For example, printing student
information:

```c
for (int i = 0; i < 3; i++) {
printf("Student %d:\n", i + 1);
printf("Name: %s\n", students[i].name);
printf("Age: %d\n", students[i].age);
printf("\n");
}

return 0;
}

You might also like