FOP-2 Question Bank Solutions Unit-1, 2, 3 & 4
FOP-2 Question Bank Solutions Unit-1, 2, 3 & 4
Unit-1 Pointers
Q1) Define an array of 10 integer pointers.
Ans 1)
Page 1 of 33
• We then call performOperation with num1, num2, and the add function
pointer as arguments.
• The add function simply adds the two numbers and returns the result.
• Finally, we print the sum obtained from the performOperation function call.
Page 2 of 33
Q3) Give the meaning of int (*f)(int,int) and int *f(int,int).
Ans 3) The expressions `int (*f)(int, int)` and `int *f(int, int)` are both related to
function pointers in C, but they have different meanings:
1. `int (*f)(int, int)`: This declares a pointer `f` to a function that takes two `int`
arguments and returns an `int`. The syntax `(*f)` denotes that `f` is a pointer,
and `(int, int)` specifies the parameter types of the function pointed to by `f`.
This is commonly used to declare function pointers.
2. `int *f(int, int)`: This declares a function `f` that takes two `int` arguments
and returns a pointer to an `int`. The `*` before `f` indicates that `f` is a function
returning a pointer, and `(int, int)` specifies the parameter types of the function
`f`. This is a function declaration.
In summary:
Page 3 of 33
2. **Passing Parameters by Reference**: In C, function arguments are passed
by value by default, meaning a copy of the data is passed to the function.
However, using pointers, you can pass parameters by reference, allowing the
function to modify the original data. This is useful when dealing with large data
structures or when you need to modify variables in a function and reflect those
changes outside the function scope.
Q5) How to initialize Pointer? Explain arrays of pointer using suitable sample
program.
int x = 10;
int *ptr = &x; // ptr now points to the memory address of variable x
When initializing arrays of pointers, each element of the array holds the address
of another variable or memory location. Here's a simple example demonstrating
arrays of pointers:
This example illustrates the concept of arrays of pointers, where each element
of the array holds the address of another variable or memory location. It's a
fundamental concept in C programming, often used in scenarios like arrays of
strings, dynamic memory allocation, and data structure implementations.
Page 4 of 33
Q6) What is a pointer? How and when it is used? How it is initialized?
Ans 6) A pointer in C is a variable that stores the memory address of another
variable. It allows indirect access to the memory location where data is stored,
enabling manipulation and interaction with that data.
Pointers are extensively used in C for various purposes, such as dynamic
memory allocation, passing arguments to functions by reference, accessing
hardware, and implementing data structures like linked lists and trees.
In this code:
• We declare an integer variable num to store an integer value.
• We declare a pointer variable ptr without initializing it.
• We then assign the address of the variable num to the pointer variable ptr
using the address-of operator &.
• Finally, we print the value of num, the address of num, the value of ptr
(which holds the address of num), and the value stored at the address pointed
to by ptr.
This simple code demonstrates how pointers are initialized and used to
indirectly access the memory location of another variable in C.
Page 6 of 33
Q7) What is Pointer in C? Explain its advantages. Also write a program to swap
two elements using pointer.
Ans 7) Refer to answer 4
In this program:
• We define a function swap that takes two integer pointers as arguments.
• Inside the swap function, we use pointer dereferencing (*) to access the
values stored at the memory addresses pointed to by a and b, and then swap
these values.
Page 7 of 33
• In the main function, we declare two integer variables num1 and num2.
• We prompt the user to input two numbers, and store them in num1 and num2.
• We call the swap function, passing the addresses of num1 and num2 as
arguments, to swap their values.
• Finally, we print the original and swapped values of num1 and num2.
Q8) Explain call by value (pass by value) and call by reference (pass by
reference) with examples in brief.
Ans 8)
Call by Value (Pass by Value):
In call by value, the value of the actual parameters (arguments) is copied to the
formal parameters of the function. Any modifications made to the formal
parameters inside the function do not affect the actual parameters outside the
function.
Output:
Page 8 of 33
Explanation:
• The increment function takes an integer parameter x.
• Inside the main function, num is initialized to 10.
• When increment(num) is called, the value of num (10) is passed to x.
• Inside the increment function, x is incremented to 11.
• However, the increment operation only affects the local variable x, and does
not modify the original num variable.
• Therefore, after the function call, num remains unchanged at its original
value (10).
Output:
Page 9 of 33
Explanation:
• The increment function takes an integer pointer x.
• Inside the main function, num is initialized to 10.
• When increment(&num) is called, the address of num is passed to x.
• Inside the increment function, the value at the address pointed to by x is
incremented using the dereference operator (*x)++.
• This modification directly affects the original variable num.
• Therefore, after the function call, num is incremented to 11.
Q9) What is pointer to pointer? Write suitable example to demonstrate the
concept.
Ans 9) A pointer to a pointer, also known as a double pointer, is a pointer that
points to the memory address of another pointer. It is used to create dynamic
data structures such as linked lists of arrays and to implement multi-level
indirection.
Output:
Value of num using ptr1: 10
Value of num using ptr2: 10
Page 10 of 33
In this code:
• We declare an integer variable num.
• We declare a pointer to an integer ptr1.
• We declare a pointer to a pointer to an integer ptr2.
• We assign the address of num to ptr1.
• We assign the address of ptr1 to ptr2.
• We use ptr1 to access the value of num and print it.
• We use ptr2 to access the value of num indirectly through two levels of
indirection and print it.
Complex question hai, last mein krna agar time ho toh, nhi toh leave this
question
In C programming, a function can return a pointer just like it can return any
other data type. Returning a pointer from a function allows you to dynamically
allocate memory inside the function and then pass the address of that memory
back to the caller. This is useful when you want to create and manipulate data
structures such as arrays or linked lists.
In this code:
• The createArray function dynamically allocates memory for an array of
integers based on the provided size.
• It initializes the array elements with some values (in this case, consecutive
even numbers).
• The function returns the pointer to the dynamically allocated array back to
the caller.
• In the main function, we call createArray and store the returned pointer in
the arr variable.
• We then use this pointer to access and print the elements of the dynamically
allocated array.
• Finally, we free the memory allocated for the array using the free function to
prevent memory leaks.
Page 11 of 33
Page 12 of 33
Unit-2 Structures
Q11) Define an array of structure with integer, string and float as members. Size
of array is 10.
Ans 11)
Page 13 of 33
In this code:
• We define a structure named Data with integer (id), string (name), and float
(value) members.
• We declare an array of Data structures named dataArray with a size of 10.
• We populate the array with sample data using a loop.
• We print the contents of the array, displaying the ID, name, and value of each
structure member for each item in the array.
Q12) Define Structure and write the general syntax for declaring and accessing
members.
Ans 12) In programming, a structure is a composite data type that groups
together variables of different types under a single name. It allows you to
organize related data items more efficiently. Here's a general definition and
syntax for declaring and accessing members of a structure:
1. Structure Definition:
A structure is typically defined using a struct keyword followed by a name for
the structure. Inside the structure definition, you declare variables of various
types to represent the members of the structure.
struct structure_name {
data_type1 member1;
data_type2 member2;
// Additional members...
};
2. Declaration:
Once the structure is defined, you can declare variables of that structure type.
3. Initialization:
You can also initialize structure variables during declaration.
4. Accessing Members:
You can access members of a structure variable using the dot (.) operator.
Page 14 of 33
Q13) What is structure? How can we access structure members? Clear use of
nested structure using example. Compare structure with union
Ans 13) A structure, also known as a struct, is a composite data type in
programming that allows you to group together variables of different types
under a single name. It provides a way to organize related data items efficiently.
Each member within a structure has its own data type and name, and these
members can be accessed individually.
Accessing Members:
You can access members of a structure variable using the dot (.) operator.
————————————————————————————————
variable_name.member1 = value; // Accessing member1
variable_name.member2 = value; // Accessing member2
————————————————————————————————
Page 15 of 33
In this example, we have two structures: Point to represent a point in a 2D space
with coordinates x and y, and Rectangle to represent a rectangle using two Point
structures for its top-left and bottom-right corners. We then declare a variable
rect of type Rectangle and set values for its nested structure members (topLeft
and bottomRight). Finally, we access and print the coordinates of the rectangle's
corners using nested structure member access.
Structures and unions are both composite data types in C, but they have some
key differences:
1. Memory Allocation:
• In a structure, each member has its own memory location, and the size of
the structure is the sum of the sizes of its members.
• In a union, all members share the same memory location, and the size of
the union is determined by the size of its largest member.
2. Usage:
• Structures are used to group related data items together.
• Unions are used when you want to store different types of data in the
same memory location, but you only need to access one member at a time.
C Code:
————————————————————————————————
struct Rectangle {
int width;
int height;
};
union Shape {
int radius;
struct Rectangle rect;
};
————————————————————————————————
In this example, a Rectangle structure is used to represent a rectangle with
width and height, while a Shape union can represent either a rectangle or a
circle (with a radius).
Q14) Give one example for Array of structure and explain the meaning.
Ans 14) Refer question 11
Page 16 of 33
Q15) What is structure? How does a structure differ from an array? How is an
array of structure initialized?
1. Composition:
• A structure can hold variables of different data types as its members.
• An array holds variables of the same data type in a contiguous block of
memory.
2. Access:
• Structure members are accessed using the dot (.) operator, providing direct
access to individual elements.
• Array elements are accessed using index notation ([]), and elements are
accessed sequentially.
3. Memory Allocation:
• Memory for each structure member is allocated separately, and the size of a
structure is the sum of the sizes of its members.
• Array elements are allocated consecutively in memory, and the size of an
array is the product of the size of its elements and the number of elements.
Page 17 of 33
Q16) Distinguish between “structure” and “array”. Discuss the meaning and
purpose of following:(1) struct keyword (2) typdef keyword (3) sizeof operator.
Ans 16)
1. **Structure**:
- A structure, also known as a "struct" in many programming languages, is a
composite data type that groups together variables of different data types under
a single name.
- Each variable within a structure is called a member or a field. These
members can be of any data type, including primitive types (like integers,
floats, characters) or even other structures.
Page 18 of 33
- Structures allow you to create custom data types to represent complex
entities in your program. For example, you might create a "Person" structure
with members such as name, age, and address.
- Structures are typically used to organize related data into a single unit,
making it easier to manage and manipulate.
2. **Array**:
- An array is a data structure that stores a fixed-size collection of elements of
the same data type.
- Elements in an array are accessed by their index, which is typically an
integer value starting from zero.
- Arrays are used to store multiple values of the same data type sequentially in
memory, allowing for efficient access to individual elements based on their
positions.
- Unlike structures, which can store variables of different data types, arrays
can only store elements of a single data type. For example, an array of integers
can only hold integer values.
- Arrays are commonly used for tasks such as storing lists of items, managing
collections of data, and implementing various algorithms.
In summary, while both structures and arrays are used for organizing and
storing data in computer programs, structures are used to group together
variables of different data types under a single name, whereas arrays are used to
store a fixed-size collection of elements of the same data type in a sequential
manner.
1. **struct keyword**:
- The `struct` keyword is used in many programming languages, including C
and C++, to define a new user-defined data type known as a "structure."
- Structures allow you to combine multiple variables of different data types
under a single name.
- The purpose of using the `struct` keyword is to create custom data types that
represent complex entities in your program. For example, you might create a
`struct` to represent a "Person" with members such as name, age, and address.
- Structures provide a way to organize related data into a single unit, making
it easier to manage and manipulate.
2. **typedef keyword**:
- The `typedef` keyword is used to create an alias or a new name for an
existing data type.
Page 19 of 33
- This keyword is particularly useful for defining complex data types or
simplifying complex declarations, especially when dealing with structures,
pointers, or function pointers.
- The purpose of `typedef` is to improve code readability, enhance portability,
and simplify the declaration of complex types.
- For example, you can use `typedef` to define a new name for a structure,
making it easier to declare variables of that type without having to use the
`struct` keyword each time.
3. **sizeof operator**:
- The `sizeof` operator is used to determine the size, in bytes, of a variable or
a data type in memory.
- It is an operator rather than a keyword, and it returns the size of its operand.
- The purpose of `sizeof` is to enable developers to write portable code by
providing a way to determine the size of data types and structures at compile
time.
- It is commonly used in scenarios such as memory allocation, serialization,
and low-level programming where knowledge of data sizes is critical.
- For example, `sizeof(int)` would return the size of an integer in bytes, and
`sizeof(struct Person)` would return the size of a `Person` structure in bytes.
In summary, the `struct` keyword is used to define new data types called
structures, the `typedef` keyword is used to create aliases for existing data
types, and the `sizeof` operator is used to determine the size of variables or data
types in memory. Each of these concepts serves a distinct purpose in
programming, contributing to code organization, readability, and portability.
1. **Structure**:
- A structure, often abbreviated as `struct`, is a composite data type that allows
you to group together variables of different data types under a single name.
- Each variable within a structure is called a member or a field, and these
members can be accessed individually.
- Structures are used to create custom data types to represent complex entities,
such as a person with attributes like name, age, and address.
Page 20 of 33
- Memory is allocated for each member of the structure separately, and the
total size of a structure is the sum of the sizes of its individual members.
- Structures are typically used when you want to group related but distinct
pieces of data together.
2. **Union**:
- A union is also a composite data type like a structure, but it only allows one
member to be stored in memory at a time, sharing the same memory location.
- Unlike structures, where each member has its memory space, unions allocate
memory that is large enough to hold the largest member.
- All members of a union share the same memory location, so modifying one
member can affect the values of other members.
- Unions are useful when you want to store different types of data in the same
memory location and only need to access one of them at a time.
- Common use cases for unions include implementing variant data types,
optimizing memory usage, and working with hardware registers where multiple
data types share the same memory location.
Page 21 of 33
Page 22 of 33
Unit-3 Dynamic Memory Allocation
Q21) How can you allocate memory dynamically for 10 floating point
numbers?
Ans 21)
Page 23 of 33
In this program:
• We declare a pointer floatArray to hold the address of the dynamically
allocated memory.
• We use malloc to allocate memory for an array of 10 floating-point numbers
(10 * sizeof(float) bytes).
• We check if the memory allocation was successful by ensuring that the
pointer is not NULL.
• We input values for the array using a loop.
• We display the entered values using another loop.
• Finally, we free the dynamically allocated memory using the free function to
prevent memory leaks.
Make sure to include <stdlib.h> header file for malloc and free functions.
Ans 22) Dynamic memory allocation refers to the process of allocating memory
at runtime (during program execution) rather than at compile time. This allows
programs to allocate memory as needed, enabling flexibility and efficiency in
memory usage.
Page 24 of 33
Dynamic memory allocation allows programs to allocate memory as needed,
which is especially useful when the size of data structures is not known at
compile time or when memory requirements vary during program execution.
However, it's important to manage dynamically allocated memory properly to
avoid memory leaks, where allocated memory is not deallocated properly,
leading to inefficient memory usage over time.
`malloc` and `calloc` are both functions in C used for dynamic memory
allocation, but they have some differences in their behavior:
1. **malloc**:
- The `malloc` function allocates a block of memory of a specified size in
bytes.
- It takes a single argument, which is the size of the memory block to allocate
in bytes.
- The memory allocated by `malloc` is uninitialized, meaning it contains
garbage values. It does not initialize the memory to zero.
- If `malloc` is unable to allocate the requested amount of memory, it returns a
`NULL` pointer.
2. **calloc**:
- The `calloc` function allocates memory for an array of elements, initializing
them to zero.
- It takes two arguments: the number of elements to allocate memory for and
the size of each element in bytes.
- The total amount of memory allocated by `calloc` is equal to the product of
the number of elements and the size of each element.
- `calloc` initializes the allocated memory to zero, ensuring that all bytes in
the allocated memory block are set to zero.
- If `calloc` is unable to allocate the requested amount of memory, it returns a
`NULL` pointer.
Page 25 of 33
CODE
#include <stdio.h>
#include <stdlib.h>
int main() {
// Example using malloc
int *ptr1;
int size1 = 5;
return 0;
}
Page 26 of 33
In this example:
• We first allocate memory for an array of integers using malloc and calloc.
• We check if memory allocation was successful by verifying that the pointers
are not NULL.
• We display the memory addresses of the allocated memory blocks.
• Finally, we free the dynamically allocated memory using the free function to
prevent memory leaks.
Both malloc and calloc are used to allocate memory dynamically, but malloc
allocates uninitialized memory, while calloc initializes the allocated memory to
zero.
Ans 24) The `fseek()` function in C is used to set the file position indicator for a
given file stream. It allows you to move the position indicator within a file,
which can be useful for random access or seeking within files.
Page 27 of 33
Explanation of `fseek(fp, 10, 0)`:
- This statement seeks 10 bytes forward from the beginning (`SEEK_SET`) of
the file associated with the file pointer `fp`.
- The `offset` is `10`, indicating that the position should be moved 10 bytes
forward.
- The `origin` is `0`, indicating the beginning of the file (`SEEK_SET`).
Q25) Distinguish between the following functions:
1. getc and getchar.
2. fprintf and printf.
3. feod and ferror.
- **getc**:
- `getc` is used to read a character from a specified file stream.
- It takes a file pointer as an argument and returns the next character from
the file.
- If successful, it returns the character read as an `unsigned char` cast to an
`int`, or `EOF` if the end of the file is reached or if an error occurs.
- **getchar**:
- `getchar` is used to read a character from the standard input (stdin).
- It does not take any arguments and reads a character from the standard
input stream.
- If successful, it returns the next character read as an `unsigned char` cast
to an `int`, or `EOF` if the end of the input stream is reached or if an error
occurs.
- **Difference**:
- `getc` reads from a specified file stream, whereas `getchar` reads from
the standard input.
- Both functions return the next character read, but their sources of input
differ.
- **fprintf**:
- `fprintf` is used to write formatted data to a specified file stream.
Page 28 of 33
- It takes a file pointer as its first argument, followed by a format string
and additional arguments to be formatted.
- It writes the formatted data to the specified file stream.
- **printf**:
- `printf` is used to write formatted data to the standard output (stdout).
- It takes a format string and additional arguments to be formatted.
- It writes the formatted data to the standard output stream.
- **Difference**:
- `fprintf` writes formatted data to a specified file stream, while `printf`
writes to the standard output.
- Both functions use the same formatting syntax but differ in their output
destinations.
- **feof**:
- `feof` is used to check whether the end-of-file indicator for a given file
stream has been set.
- It takes a file pointer as an argument and returns a non-zero value if the
end-of-file indicator is set, indicating that the end of the file has been reached.
- **ferror**:
- `ferror` is used to check whether an error indicator for a given file stream
has been set.
- It takes a file pointer as an argument and returns a non-zero value if the
error indicator is set, indicating that an error has occurred during an operation
on the file stream.
- **Difference**:
- `feof` checks for the end-of-file condition, while `ferror` checks for error
conditions.
- `feof` returns non-zero if the end-of-file indicator is set, while `ferror`
returns non-zero if the error indicator is set.
- Both functions are used to check the state of a file stream after reading or
writing operations.
Page 29 of 33
CODE:
#include <stdio.h>
int main() {
FILE *filePtr;
return 0;
}
In this program:
- We first open a file named "output.txt" in write mode using `fopen()`.
- We use `fputc()` to write a single character ('H') to the file.
- We use `fputs()` to write a string ("ello, World!") to the file.
- Finally, we close the file using `fclose()`.
- If the file cannot be opened, we print an error message.
This program illustrates the use of `fputc()` to write individual characters and
`fputs()` to write strings to a file.
Page 30 of 33
Q27) Explain fopen() and fclose() file handling functions.
Ans 27) `fopen()` and `fclose()` are file handling functions commonly used in
programming languages like C and C++. Here's an explanation of each:
1. **fopen() Function**:
- `fopen()` is used to open a file and associate it with a stream, which serves
as a connection between the file and the program.
- Syntax: `FILE *fopen(const char *filename, const char *mode);`
- Parameters:
- `filename`: A string containing the name of the file to be opened.
- `mode`: A string specifying the mode in which the file is to be opened (e.g.,
read mode, write mode, append mode, etc.).
- Return Value:
- If successful, `fopen()` returns a pointer to a `FILE` object that is used to
identify the stream.
- If unsuccessful, it returns `NULL`.
Example:
————————————————————————————————
FILE *fp;
fp = fopen("example.txt", "r"); // Opens a file named "example.txt" in read
mode
if (fp == NULL) {
printf("Error opening file!\n");
exit(1);
}
————————————————————————————————
2. **fclose() Function**:
- `fclose()` is used to close a file stream that was previously opened with
`fopen()`.
- Syntax: `int fclose(FILE *stream);`
- Parameters:
- `stream`: A pointer to the `FILE` object that represents the file stream to be
closed.
- Return Value:
- `fclose()` returns `0` upon successful closing of the file stream.
- It returns `EOF` (End-of-File) if an error occurs while closing the file.
Page 31 of 33
Example:
————————————————————————————————
2. **Opening and Closing Files**: Files are opened to perform read or write
operations, and they must be closed after use to release system resources.
3. **Reading and Writing Files**: Reading from files involves retrieving data
stored in them, while writing to files involves storing new data or modifying
existing data.
4. **File Modes**: File modes specify the type of access permitted when
opening a file. Common file modes include:
- **"r"**: Open for reading. The file must exist.
- **"w"**: Open for writing. If the file exists, its contents are overwritten. If
the file does not exist, it's created.
- **"a"**: Open for appending. Data is added to the end of the file. If the file
does not exist, it's created.
- **"r+"**: Open for reading and writing. The file must exist.
Page 32 of 33
- **"w+"**: Open for reading and writing. If the file exists, its contents are
overwritten. If the file does not exist, it's created.
- **"a+"**: Open for reading and appending. Data can be read from and
added to the end of the file. If the file does not exist, it's created.
Effective file management is crucial for organizing data, ensuring data integrity,
and optimizing resource usage on computer systems. It involves understanding
and using various file operations and modes effectively to perform tasks
efficiently and securely.
Page 33 of 33