0% found this document useful (0 votes)
10 views25 pages

C Programming Theory Question Bank

The document is a comprehensive question bank on C programming, covering fundamental concepts such as problem-solving, algorithms, flowcharts, data types, and memory layout. It includes short and long answer questions on decision control structures, looping constructs, and the compilation process, providing detailed explanations and examples. Additionally, it discusses operators, functions, and type conversions, making it a valuable resource for understanding C programming.

Uploaded by

areebmirofficial
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)
10 views25 pages

C Programming Theory Question Bank

The document is a comprehensive question bank on C programming, covering fundamental concepts such as problem-solving, algorithms, flowcharts, data types, and memory layout. It includes short and long answer questions on decision control structures, looping constructs, and the compilation process, providing detailed explanations and examples. Additionally, it discusses operators, functions, and type conversions, making it a valuable resource for understanding C programming.

Uploaded by

areebmirofficial
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

C Programming: Complete Theory Question Bank

UNIT I — Basics of C, Problem Solving, Bits, Data Types


PART A: Short Answer Questions (2–5 Marks)
Target Length: 3–5 sentences or bullet points.

1. Define problem-solving in engineering.

Problem-solving in engineering is the systematic process of analyzing a problem,


defining it clearly, and designing a solution that can be implemented using a computer
program. It involves identifying the input, determining the desired output, and figuring
out the logic (algorithm) to transform the input into the output.

2. What is an algorithm? Write its characteristics.

An algorithm is a step-by-step finite sequence of instructions to solve a specific


problem.

Characteristics:

• Finiteness: It must terminate after a finite number of steps.


• Definiteness: Each step must be unambiguous and clear.
• Input/Output: It accepts zero or more inputs and produces at least one output.
• Effectiveness: Operations must be basic enough to be performed exactly.

3. What is a flowchart? Draw symbols used in flowcharts.

A flowchart is a pictorial or graphical representation of an algorithm. It uses standard


symbols to represent different types of instructions.

• Oval: Start/Stop
• Parallelogram: Input/Output
• Rectangle: Processing/Calculations
• Diamond: Decision making (Yes/No)
• Arrows: Flow of control

4. Differentiate between high-level and low-level languages.


• High-Level Language (HLL): User-friendly, machine-independent, and
resembles English (e.g., C, Python). It requires a compiler/interpreter to translate
to machine code.
• Low-Level Language (LLL): Machine-friendly and hardware-dependent.
Includes Machine Language (0s and 1s) and Assembly Language (mnemonics).
LLL code runs faster but is harder to write.

5. What is the memory layout of a C program?

When a C program runs, its memory is divided into:

1. Text Segment: Stores executable instructions.


2. Data Segment: Stores global and static variables.
3. Heap: Used for dynamic memory allocation.
4. Stack: Stores local variables and function call data.

6. What is GCC?

GCC stands for GNU Compiler Collection. It is a popular, open-source compiler system
that supports various programming languages, including C. It translates C source code
into an executable binary file.

7. Explain 1’s complement and 2’s complement of a binary number.

• 1’s Complement: Obtained by inverting all bits of a binary number (0 becomes


1, 1 becomes 0).
o Example: 1010 → 0101.
• 2’s Complement: Obtained by adding 1 to the 1’s complement. It is used by
computers to represent negative integers.
o Formula: 2’s Complement = 1’s Complement + 1.

8. Explain octal and hexadecimal number systems.

• Octal (Base-8): Uses digits 0–7. Each octal digit represents 3 bits of binary.
(e.g., 012)
• Hexadecimal (Base-16): Uses digits 0–9 and letters A–F (where A=10, F=15).
Each hex digit represents 4 bits of binary. It is widely used in memory
addressing. (e.g., 0x1A)

9. What are identifiers and keywords in C?


• Identifiers: User-defined names given to variables, functions, or arrays (e.g.,
total, calc_sum).
• Keywords: Reserved words with predefined meanings in the C compiler. They
cannot be used as identifiers (e.g., int, return, if, while).

10. Define variables. What are rules for naming variables?

A variable is a named memory location used to store data that can change during
program execution.

Rules:

1. Must start with a letter or underscore (_).


2. Cannot contain spaces or special characters (except _).
3. Cannot be a keyword.
4. Case sensitive (Sum and sum are different).

11. List different data types in C.

• Primary (Primitive): int, char, float, double, void.


• Derived: Arrays, Pointers.
• User-Defined: Structures (struct), Unions (union), Enumerations (enum).

12. What is a header file? Give examples.

A header file contains function declarations and macro definitions to be shared


between source files. It ends with .h.

• Examples: <stdio.h> (Standard I/O), <math.h> (Math functions), <string.h>


(String manipulation).

13. What is type conversion? Explain implicit and explicit conversion.

Type conversion is converting one data type into another.

• Implicit (Type Promotion): Done automatically by the compiler (e.g., int to


float).
• Explicit (Type Casting): Done manually by the programmer using a cast
operator (e.g., (float)a / b).

14. Explain operator precedence and associativity.


• Precedence: Determines which operator is evaluated first in an expression (e.g.,
* has higher precedence than +).
• Associativity: Determines the direction of evaluation if operators have the same
precedence (usually Left-to-Right, but Assignment is Right-to-Left).

15. What are library functions? Give examples.

These are pre-written functions provided by C standard libraries.

• Examples: sqrt() (calculates square root), pow() (power), exit() (terminates


program).

16. Write structure of a C program.

C
/* Documentation Section */
#include <header_files> /* Link Section */
#define PI 3.14 /* Definition Section */
int global_var; /* Global Declaration */

int main() { /* Main Function */


// Local variables
// Executable statements
return 0;
}

17. What is the use of printf() and scanf()?

• printf(): Used to output formatted data to the standard output (screen).


• scanf(): Used to take formatted input from the standard input (keyboard).

18. Explain comments in C.

Comments are non-executable text used for documentation.

• Single-line: Starts with //.


• Multi-line: Enclosed between /* and */.
PART B: Long Answer Questions (8–12 Marks)
Target Length: Detailed explanation, diagrams, and examples.

1. Explain program development steps with a neat diagram.

The development of a C program involves several distinct stages:

1. Problem Definition: Understanding what the program needs to do.


2. Design (Algorithm/Flowchart): Planning the logic.
3. Coding: Writing the source code (.c file) using a text editor.
4. Compilation: The compiler translates source code into object code (.obj). If
there are syntax errors, they are reported here.
5. Linking: The linker combines the object code with library files (like stdio.h) to
create an executable file (.exe or .out).
6. Testing & Debugging: Running the program to check for logical errors (bugs)
and fixing them.
7. Maintenance: Updating the software as needed.

Opens in a new windowGetty Images Software Development Life Cycle

2. Describe the memory layout of a C program (Text, Data, Heap, Stack, Code).

When a program is loaded into memory, the operating system allocates four primary
segments:

• Text (Code) Segment:


o This is the read-only area where the compiled binary instructions (machine
code) reside. It prevents the program from accidentally modifying its own
instructions.
• Data Segment (Initialized and Uninitialized):
o Initialized Data: Stores global and static variables that are initialized (e.g.,
int x = 10;).
o BSS (Block Started by Symbol): Stores global/static variables not
initialized (default to zero).
• Heap:
o Used for Dynamic Memory Allocation. Memory here is manually
allocated using malloc() or calloc() and must be freed using free(). It grows
upward.
• Stack:
o Used for static memory allocation. It stores local variables, function
parameters, and return addresses. The stack grows downward. If the stack
runs out of memory, a "Stack Overflow" occurs.

3. Explain in detail the compilation process of a C program.

The transformation from human-readable C code to machine-executable code


happens in four phases:

1. Preprocessing:
a. Handles lines starting with #.
b. Expands macros (#define) and includes header files (#include).
c. Removes comments.
d. Output: Expanded source code.
2. Compilation:
a. Translates the preprocessed code into Assembly Language specific to the
target architecture.
b. Checks for syntax errors.
3. Assembly:
a. Converts the assembly code into Object Code (machine language, binary
0s and 1s).
b. Output: .obj (Windows) or .o (Linux) file.
4. Linking:
a. Combines the object code with C standard libraries (like implementation of
printf).
b. Resolves references to external functions.
c. Output: Final Executable file (.exe).

4. Explain different types of operators in C with examples.

Operators perform operations on operands (variables/values).

1. Arithmetic Operators: +, -, *, /, % (Modulus).


a. Ex: 10 % 3 results in 1.
2. Relational Operators: ==, !=, >, <, >=, <=. Returns true (1) or false (0).
a. Ex: 5 > 3 is true.
3. Logical Operators: && (AND), || (OR), ! (NOT).
a. Ex: (5>3) && (2<4) is true.
4. Assignment Operators: =, +=, -=, *=.
a. Ex: a += 5 is same as a = a + 5.
5. Increment/Decrement: ++, --.
a. Ex: i++ (Post-increment), ++i (Pre-increment).
6. Bitwise Operators: & (AND), | (OR), ^ (XOR), ~ (NOT), << (Left Shift), >> (Right
Shift).
7. Ternary (Conditional) Operator: Condition ? True : False.
a. Ex: max = (a > b) ? a : b;

5. Explain binary representations: signed, unsigned, 1’s and 2’s complement.

Computers store numbers in binary.

• Unsigned Representation:
o Can only represent positive numbers. All bits are used for magnitude.
o Range (8-bit): 0 to 255.
• Signed Representation (Sign-Magnitude):
o The Most Significant Bit (MSB) is the sign bit (0 = positive, 1 = negative).
o Remaining bits are magnitude.
• 1’s Complement:
o Negative numbers are stored by flipping all bits of the positive equivalent.
o Issue: It has two zeros (+0 and -0).
• 2’s Complement:
o The standard method for modern computers.
o Negative numbers are stored by adding 1 to the 1’s complement.
o Advantage: Only one zero exists, and arithmetic operations are easier for
hardware.

6. Explain the various data types in C with memory size and range.

Data types specify the type of data a variable can hold. (Sizes below are for a typical
32-bit GCC compiler).

Data Memory Format


Description Range (Approx)
Type Size Specifier

char Single character 1 byte %c -128 to 127


Integer (whole 2 or 4 -32,768 to 32,767 (if
int %d
number) bytes 2 bytes)

Single precision 6 decimal places


float 4 bytes %f
decimal precision

Double precision 15 decimal places


double 8 bytes %lf
decimal precision

void Valueless/Empty 0 bytes - -

UNIT II — Decision Control, Looping, Functions


PART A: Short Answer Questions (2–5 Marks)
1. What are decision-making statements?

Decision-making (or conditional) statements allow the program to execute a certain


block of code only if a specific condition is true. They control the flow of execution
based on logic. Common types include if, if-else, and switch.

2. Difference between if, if-else, and nested if-else.

• if: Executes a block only if the condition is true. If false, it does nothing.
• if-else: Executes one block if true, and a different "else" block if false.
• Nested if-else: An if-else statement inside another if or else block. Used to
check multiple conditions hierarchically.

3. Explain switch-case with syntax.

The switch statement is a multi-way decision control statement. It tests a variable


against a list of values (cases).

Syntax:

C
switch(expression) {
case constant1:
// code
break;
case constant2:
// code
break;
default:
// code if no case matches
}

4. What is a loop? Name different types.

A loop is a control structure that repeats a block of code as long as a specified


condition remains true.

Types:

1. Entry Controlled: Condition checked before execution (e.g., while, for).


2. Exit Controlled: Condition checked after execution (e.g., do-while).

5. Difference between while and do-while loop.

• while loop: Checks the condition first. If the condition is false initially, the code
never runs.
• do-while loop: Executes the code first, then checks the condition. The code
always runs at least once.

6. What is a nested loop?

A nested loop is a loop inside another loop. The "inner loop" finishes all its iterations for
every single iteration of the "outer loop". This is commonly used for working with 2D
arrays or printing patterns.

7. Explain break, continue, and goto.

• break: Immediately terminates the loop or switch case.


• continue: Skips the rest of the current loop iteration and jumps to the next
iteration.
• goto: Unconditionally jumps to a labeled part of the code (generally discouraged
as it makes code messy).

8. What is a function prototype?

A function prototype is a declaration that tells the compiler about the function's name,
return type, and parameters before the function is actually defined. It ensures type
checking.

• Example: int add(int, int);

9. What is a library function?

Library functions are pre-compiled functions provided by C standard libraries (like


printf, sqrt, strcpy). You do not need to write their logic; you just include the header file
and call them.

10. What is recursion?

Recursion is a process where a function calls itself directly or indirectly. The problem is
solved by breaking it down into smaller instances of the same problem. It must have a
base case to stop the infinite loop.

11. What is the difference between call by value and call by reference?

• Call by Value: Passes a copy of the variable. Changes inside the function do not
affect the original variable.
• Call by Reference: Passes the address (pointer) of the variable. Changes inside
the function do affect the original variable.

PART B: Long Answer Questions (8–12 Marks)


1. Explain all decision control structures in C with examples.

Decision control structures allow the program to choose different paths of execution.

• Simple if: Checks one condition.

C
if (age >= 18) printf("Allowed");
• If-else: Checks a condition, provides an alternative.

C
if (num % 2 == 0) printf("Even");
else printf("Odd");

• Else-if Ladder: Used to check multiple distinct conditions.

C
if (marks > 90) grade = 'A';
else if (marks > 80) grade = 'B';
else grade = 'C';

• Switch Case: Used when selecting one option from many fixed values
(explained in Short Q3).

2. Describe the different looping constructs (while, do-while, for).

Opens in a new windowGetty Images for loop and while loop in flowchart process in
condition

• While Loop (Entry Controlled):


o Syntax: while(condition) { // code }
o Used when the number of iterations is unknown beforehand.
• Do-While Loop (Exit Controlled):
o Syntax: do { // code } while(condition);
o Used when the loop must execute at least once (e.g., menu-driven
programs).
• For Loop (Entry Controlled):
o Syntax: for(initialization; condition; update) { // code }
o Most compact loop; used when the number of iterations is known.

3. Explain break, continue, and goto with suitable programs.

These are "Jump Statements."

• Break: Used to exit a loop early (e.g., searching for a number; if found, stop
searching).
• Continue: Used to skip specific iterations (e.g., print 1 to 10 but skip 5).

C
for(int i=1; i<=10; i++) {
if(i==5) continue; // Skips 5
printf("%d ", i);
}

• Goto: Jumps to a label.

C
start:
printf("Loop");
goto start; // Infinite loop

4. Explain functions in C: declaration, definition, and calling.

A function has three main parts:

1. Function Declaration (Prototype): Tells the compiler what to expect.


a. int sum(int a, int b); (Placed before main).
2. Function Definition: The actual body of the code.

C
int sum(int a, int b) {
return a + b;
}

3. Function Call: Using the function in main.


a. int result = sum(5, 10);

5. Explain recursion with advantages and disadvantages.

Recursion is when a function calls itself.


• Mechanism: It uses the Stack memory. Each recursive call pushes a new frame
onto the stack. When the base case is reached, the stack unwinds.
• Advantages: Code is cleaner and shorter for problems like tree traversals,
Factorial, and Fibonacci series.
• Disadvantages: Slower than iteration due to overhead of function calls;
consumes more memory (Stack Overflow risk).

6. Discuss user-defined functions with examples (all 4 categories).

Functions are classified based on arguments and return values:

1. No Arguments, No Return Type:


a. void greet() { printf("Hello"); }
2. No Arguments, With Return Type:
a. int getNum() { return 10; }
3. With Arguments, No Return Type:
a. void printSum(int a, int b) { printf("%d", a+b); }
4. With Arguments, With Return Type:
a. int multiply(int a, int b) { return a * b; }

7. Explain static functions.

• In C, if a function is defined as static, its scope is limited to the file in which it is


declared.
• It cannot be called from another file using extern.
• This provides data hiding and encapsulation in C.
o Example: static void helperFunction() { ... }
8. Write differences between iterative and recursive approaches.

Feature Recursion Iteration (Loops)

Definition Function calls itself. Block of code repeats.

Low usage (CPU


Memory High usage (Stack).
registers).

Slower (Context
Speed Faster.
switching).

Code Size Smaller, cleaner logic. Larger, complex logic.

Termination Base Case. Loop Condition.

UNIT III — Arrays, Strings, Pointers, Structures & Unions


PART A: Short Answer Questions (2–5 Marks)
1. What is an array? Give its advantages.

An array is a collection of variables of the same data type stored in contiguous


(adjacent) memory locations.

Advantages:

• Allows storing multiple values under a single name.


• Easy access to elements using an index.
• Efficient for implementing data structures like stacks and queues.

2. Difference between 1D and 2D array.

• 1D Array: A linear list of items (like a single row). Accessed using one subscript:
arr[i].
• 2D Array: A grid or matrix of items (rows and columns). Accessed using two
subscripts: arr[row][col].

3. What is a string? How is it stored?


A string in C is a one-dimensional array of characters terminated by a null character
(\0). It is stored in contiguous memory bytes, with the last byte reserved for \0 to mark
the end of the string.

4. What are string handling library functions?

These are predefined functions in <string.h> used to manipulate strings.

• strlen(): Finds length.


• strcpy(): Copies one string to another.
• strcat(): Concatenates (joins) two strings.
• strcmp(): Compares two strings.

5. Define a pointer.

A pointer is a variable that stores the memory address of another variable. It allows
direct manipulation of memory. It is declared using an asterisk (e.g., int *ptr;).

6. What is pointer arithmetic?

Pointer arithmetic allows performing operations like addition or subtraction on pointers.

• Adding 1 to a pointer (ptr++) moves it to the next memory location based on the
data type size (e.g., for int, it jumps 4 bytes).

7. What are arrays of pointers?

An array of pointers is an array where each element is a pointer to a variable.

• Example: int *arr[3]; creates an array that can hold 3 integer addresses. It is often
used for storing an array of strings.

8. Define a structure.

A structure (struct) is a user-defined data type that allows grouping variables of


different data types under a single name.

• Example: A Student structure can hold name (char array), roll_no (int), and
marks (float).

9. Define a union.
A union (union) is similar to a structure, but all its members share the same memory
location. Only one member can hold a value at any given time. The size of the union is
equal to the size of its largest member.

10. Difference between structure and union.

• Memory: Structure allocates memory for all members (Sum of sizes). Union
allocates memory for only the largest member.
• Access: In a structure, all members can be accessed simultaneously. In a union,
only one member is active at a time.

11. What is a structure pointer?

A pointer that points to the address of a structure variable.

• Syntax: struct Student *ptr;


• To access members using a pointer, use the arrow operator (->) instead of the
dot operator (.).

12. What is a function pointer?

A function pointer is a pointer that points to the address of a function (the start of its
code in memory). It is used to pass functions as arguments to other functions
(callbacks).

• Syntax: int (*ptr)(int, int);

13. What is meant by passing arrays to a function?

When an array is passed to a function, only the base address (address of the first
element) is passed. Therefore, arrays are always passed by reference, and changes
made inside the function affect the original array.

PART B: Long Answer Questions (8–12 Marks)


1. Explain 1D, 2D, and multidimensional arrays with memory representation.

• 1D Array: Stored linearly. Address of arr[i] = Base Address + (i * size_of_type).


• 2D Array: Stored in memory as a single continuous block, typically in Row-
Major Order (row by row).
o Address calculation involves row and column indices.
o Useful for matrices and tables.
• Memory Representation: Even though we visualize 2D arrays as grids,
computer memory is linear (1D). The compiler maps the 2D indices to linear
addresses.

2. Explain string functions (strlen, strcpy, strcmp, strcat, etc.).

• strlen(s): Returns the count of characters excluding \0.


• strcpy(dest, src): Copies the content of src to dest.
• strcat(dest, src): Appends src to the end of dest.
• strcmp(s1, s2): Compares strings character by character (ASCII value). Returns
0 if equal, <0 if s1 is smaller, >0 if s1 is larger.
• strrev(s): Reverses the string.

3. Explain pointer operations and pointer arithmetic with examples.

Pointer arithmetic depends on the data type the pointer points to.

• Increment (ptr++): Moves to the next element. If ptr is int* (4 bytes) at address
1000, ptr++ becomes 1004.
• Decrement (ptr--): Moves to the previous element.
• Addition (ptr + n): Skips n elements forward.
• Subtraction (ptr1 - ptr2): Returns the number of elements between two
pointers.
• Note: You cannot add two pointers or multiply pointers.

4. Explain arrays and pointers relationship.

Arrays and pointers are closely related.

• The name of an array (e.g., arr) acts as a constant pointer to the first element
(&arr[0]).
• arr[i] is internally converted by the compiler to *(arr + i).
• This is why array indexing starts at 0 and why arrays are passed by reference.

5. Explain array of pointers with examples.

An array of pointers stores addresses.


• Usage: Commonly used to create "Ragged Arrays" or arrays of strings where
string lengths vary.

C
char *names[] = {"Amit", "Rohan", "Suresh"};

Here, names[0] points to "Amit", names[1] points to "Rohan". This saves memory
compared to a 2D char array where all rows must be the same size.

6. Explain function pointers with syntax and usage.

• Definition: Holds the address of executable code.


• Syntax: return_type (*pointer_name)(parameter_types);

C
void display() { printf("Hello"); }
int main() {
void (*ptr)() = display; // Pointer points to function
ptr(); // Calls the function
}

• Usage: Implementing callback functions (like in qsort()) and menu-driven


systems.

7. Explain structures with syntax, memory allocation, and examples.

• Syntax:

C
struct Book {
char title[20]; // 20 bytes
int price; // 4 bytes
};

• Memory: Contiguous block. Total size is usually the sum of members (plus
padding for alignment). In the example above, size ≈ 24 bytes.
• Usage: Used to model real-world entities (Employee, Car, Student).
8. Explain unions with examples and memory allocation.

• Syntax:

C
union Data {
int i; // 4 bytes
float f; // 4 bytes
char str[20]; // 20 bytes
};

• Memory: The compiler allocates memory only for the largest member (str[20]).
Total size = 20 bytes.
• Behavior: If you store a value in i, then store a value in str, the value in i gets
corrupted/overwritten because they share the same space.

9. Structures vs unions—explain with memory diagram.

• Structure: Like a house with separate rooms for every person (member).
Everyone exists at the same time. High memory usage.
• Union: Like a house with one room. Only one person (member) can be inside at
a time. Low memory usage.

10. Explain how structures and arrays combine (array of structures).

An array of structures is used to store multiple records.

• Example: Storing data for 50 students.

C
struct Student class_data[50];

• Accessing data: class_data[0].roll_no, class_data[1].name, etc.

11. Explain pointer to structure and accessing structure members using → operator.

When using a pointer to a structure, the dot operator (.) cannot be used directly
because of operator precedence.
• Instead of (*ptr).member, C provides the arrow operator: ptr->member.
• This is crucial for Linked Lists and Trees.

12. Explain passing structure to function (by value and by reference).

• By Value: The entire structure is copied. Slow for large structures.


o void printFunc(struct Student s);
• By Reference: Only the address is passed. Fast and efficient.
o void printFunc(struct Student *s);
o Inside the function, access members using s->member.

Here is the final section, UNIT IV, along with the Bonus High-Probability Questions
list to complete your question bank.

UNIT IV — Dynamic Memory Allocation & File Handling


PART A: Short Answer Questions (2–5 Marks)
1. What is dynamic memory allocation?

Dynamic Memory Allocation (DMA) is the process of allocating memory manually


during runtime (while the program is executing), rather than at compile time. It allows
the program to use exactly as much memory as needed. It uses the Heap segment of
memory.

2. Difference between malloc() and calloc().

• malloc() (Memory Allocation): Allocates a single large block of memory. It does


not clear the memory, so it contains garbage values initially.
• calloc() (Contiguous Allocation): Allocates multiple blocks of memory (usually
for arrays). It initializes all bytes to zero.

3. What is the use of realloc()?

realloc() (Re-allocation) is used to change the size of a previously allocated memory


block. It can increase or decrease the size without losing the existing data (if growing,
new space is uninitialized).

4. What is free()?
free() is used to deallocate (release) the memory previously allocated by malloc, calloc,
or realloc. This is essential to prevent memory leaks, where unused memory remains
occupied.

5. What is a file?

A file is a container in secondary storage (like a hard disk) used to store data
permanently. It is a sequence of bytes. In C, files are treated as a "stream" of bytes.

6. What is the difference between text and binary files?

• Text Files: Store data as ASCII characters. easy for humans to read. Newline
characters may be translated (e.g., \n to \r\n).
• Binary Files: Store data in the same format as it appears in memory (raw bytes).
More efficient for storage and faster for the computer to read, but not human-
readable.

7. What are file pointers?

A file pointer is a pointer to a structure of type FILE. It holds information about the file
being used, such as the current position, buffer status, and end-of-file indicator.

• Syntax: FILE *fp;

8. Explain fopen(), fclose().

• fopen(): Opens a file and returns a file pointer. If it fails (e.g., file not found), it
returns NULL.
• fclose(): Closes the file, releases the memory buffer, and saves any pending data
to the disk.

9. What are r, w, a modes of file handling?

• "r": Read mode. Opens an existing file. Returns NULL if file doesn't exist.
• "w": Write mode. Creates a new file. If file exists, it overwrites (erases) it.
• "a": Append mode. Opens file to add data at the end. Preserves existing content.

PART B: Long Answer Questions (8–12 Marks)


1. Explain all dynamic memory allocation functions: malloc, calloc, realloc, free.
These functions are defined in <stdlib.h>.

• malloc:
o Syntax: ptr = (cast_type*) malloc(byte_size);
o Example: int *p = (int*)malloc(5 * sizeof(int));
• calloc:
o Syntax: ptr = (cast_type*) calloc(n, element_size);
o Example: int *p = (int*)calloc(5, sizeof(int));
• realloc:
o Syntax: ptr = realloc(ptr, new_size);
• free:
o Syntax: free(ptr);
o Note: After freeing, ptr becomes a dangling pointer, so it is good practice to
set ptr = NULL.

2. Explain memory allocation on heap vs stack.

• Stack Memory:
o Used for Static/Automatic allocation (local variables, function calls).
o Managed automatically by the compiler/OS.
o Allocation happens when a function is called; deallocation happens when it
returns.
o Fast access but limited size (Stack Overflow risk).
• Heap Memory:
o Used for Dynamic allocation (pointer variables).
o Managed manually by the programmer.
o Persists until explicitly freed or program ends.
o Slower access but flexible size (Memory Leak risk if not freed).

3. Discuss file operations: opening, reading, writing, and closing a file.

File handling involves four major steps:

1. Declaration: Define a file pointer (FILE *fp).


2. Opening: Use fopen() to link the file pointer to a physical file.
3. Operations: Use functions like fprintf or fscanf to perform I/O.
a. Check: Always check if fp == NULL to ensure the file opened successfully.
4. Closing: Use fclose(fp) to save changes and free resources.
4. Explain all file I/O functions: getc, putc, getchar, putchar, fprintf, fscanf, fwrite,
fread.

• Character I/O:
o fgetc(fp): Reads one character from file.
o fputc(ch, fp): Writes one character to file.
• String I/O:
o fgets(str, n, fp): Reads a line/string.
o fputs(str, fp): Writes a string.
• Formatted I/O:
o fscanf(fp, "format", vars): Reads formatted data (like scanf but from file).
o fprintf(fp, "format", vars): Writes formatted data (like printf but to file).
• Block/Binary I/O:
o fread(&ptr, size, n, fp): Reads entire blocks/structures (binary safe).
o fwrite(&ptr, size, n, fp): Writes blocks/structures.

5. Explain file pointer and its role in file handling.

The FILE structure (defined in <stdio.h>) acts as a bridge between the program and
the operating system's file system.

• It tracks the current position (where the next read/write will happen).
• It manages the buffer (temporary storage to reduce disk access).
• When you open a file, the OS creates this structure and returns its address. All
subsequent functions need this pointer to know which file to operate on.

6. Explain the steps to read and write a file in C with a program.

• Writing Program:

C
FILE *fp = fopen("[Link]", "w");
if(fp != NULL) {
fprintf(fp, "Hello World\n");
fclose(fp);
}
• Reading Program:

C
char buffer[100];
FILE *fp = fopen("[Link]", "r");
if(fp != NULL) {
while(fscanf(fp, "%s", buffer) != EOF) {
printf("%s ", buffer);
}
fclose(fp);
}

7. Explain how to update and append data to a file.

• Append: Open with "a" mode. Any data written is added to the end. The
previous content remains safe.
• Update: Open with "r+" (read/write existing), "w+" (read/write new), or "a+"
(read/append).
o To modify specific data in the middle of a file, you usually need fseek() to
move the file pointer to the specific byte location, then write the new data.

BONUS: VERY HIGH PROBABILITY FINAL EXAM QUESTIONS


10 Marks (Detailed Explanation Required)

1. Explain pointer arithmetic with examples. (Focus on incrementing pointers


based on data type size).
2. Explain structures and unions with memory diagrams. (Focus on the shared
memory aspect of unions).
3. Explain recursion and write a recursive program for factorial or Fibonacci.
(Include the stack diagram logic).
4. Explain dynamic memory allocation in C and write programs using
malloc/calloc. (Focus on the syntax and free()).
5. Explain different decision control structures with examples. (Cover if-else
ladder and switch case).

5 Marks (Concise Answers)

1. Difference between while and do-while. (Entry vs Exit control).


2. Difference between structure and union. (Memory allocation difference).
3. Explain break and continue. (Loop control flow).
4. Explain array of pointers. (Storing multiple strings).
5. What is a file pointer? (The FILE structure and its use).

You might also like