Unit3 - Subjective Questions
CSE101 • Practice Questions with Detailed Answers
Define a user-defined function in C. Explain the general syntax and the components of a function definition.
A user-defined function is a block of code written by the programmer to perform a specific task, which can be reused throughout the program. It divides a large program into smaller, manageable modules.
General Syntax
c
return_type function_name(parameter_list) {
// Local variable declarations
// Executable statements
return value;
}
Components of a Function Definition
- Return Type: Specifies the data type of the value the function returns to the caller (e.g.,
int,float,void). - Function Name: A unique identifier used to call the function.
- Parameter List: A list of variables (with types) that accept values passed from the calling function. It is enclosed in parentheses.
- Function Body: The block of code enclosed in braces
{ }that defines the logic/task. - Return Statement: Used to terminate the function and pass the result back to the calling environment (optional for
voidfunctions).
What is a Function Prototype? Why is it necessary in C programming?
A Function Prototype is a declaration statement that tells the compiler about a function's name, its return type, and the number and data types of its parameters before the function is actually defined or called.
Syntax
return_type function_name(type1 arg1, type2 arg2, ...);
Why is it necessary?
- Compiler Validation: It allows the compiler to check if the function is being called correctly (correct number and type of arguments).
- Type Conversion: It enables the compiler to perform implicit type conversion if the arguments passed do not exactly match the parameters but are compatible.
- Top-Down Approach: It allows functions to be defined anywhere in the code (even after the
mainfunction) while still being callable frommain.
Differentiate between Call by Value and Call by Reference with appropriate examples.
Call by Value vs Call by Reference
| Feature | Call by Value | Call by Reference |
|---|---|---|
| Mechanism | A copy of the actual argument's value is passed to the formal parameter. | The address (memory location) of the actual argument is passed to the formal parameter. |
| Effect on Original | Changes made inside the function do not affect the original variables. | Changes made inside the function directly affect the original variables. |
| Memory | Separate memory is allocated for formal parameters. | Formal parameters share the same memory address as actual arguments. |
| Syntax (C) | func(x); |
func(&x); |
Examples
1. Call by Value:
c
void modify(int x) {
x = 100; // Changes copy only
}
// In main, if a=10, modify(a) leaves a as 10.
2. Call by Reference:
c
void modify(int x) {
x = 100; // Changes value at address
}
// In main, if a=10, modify(&a) changes a to 100.
Write a C program to swap two numbers using a user-defined function and the Call by Reference method.
To swap two numbers using call by reference, we must pass the addresses of the variables to the function and use pointers to dereference and swap the values.
Program
c
include <stdio.h>
// Function Declaration
void swap(int a, int b);
int main() {
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
printf("Before Swapping: num1 = %d, num2 = %d
", num1, num2);
// Passing addresses of num1 and num2
swap(&num1, &num2);
printf("After Swapping: num1 = %d, num2 = %d
", num1, num2);
return 0;
}
// Function Definition
void swap(int a, int b) {
int temp;
temp = a; // Store value at address a into temp
a = b; // Copy value at address b to address a
b = temp; // Copy temp to address b
}
Explain the difference between Formal Parameters and Actual Arguments.
Actual Arguments and Formal Parameters refer to data transfer during a function call.
Actual Arguments
- These are the variables or values passed to the function during the function call in the calling function (e.g., inside
main). - Example: In
add(a, b);,aandbare actual arguments.
Formal Parameters
- These are the variables declared in the function definition header that receive values from the actual arguments.
- They act as placeholders or local variables within the called function.
- Example: In
void add(int x, int y) { ... },xandyare formal parameters.
Key Difference: The Actual Arguments provide the input, while the Formal Parameters process that input within the function scope.
List and explain any five mathematical library functions defined in the <math.h> header file.
The <math.h> header file contains standard mathematical functions. Common examples include:
-
sqrt(double x):- Returns the square root of .
- Example:
sqrt(16.0)returns4.0.
-
pow(double base, double exp):- Returns the result of base raised to the power of exp ().
- Example:
pow(2.0, 3.0)returns8.0.
-
ceil(double x):- Returns the smallest integer value greater than or equal to (rounds up).
- Example:
ceil(4.2)returns5.0.
-
floor(double x):- Returns the largest integer value less than or equal to (rounds down).
- Example:
floor(4.9)returns4.0.
-
abs(int x)(found instdlib.husually, butfabsis inmath.h):fabs(double x)returns the absolute value of a floating-point number.- Example:
fabs(-5.5)returns5.5.
What is Recursion? Explain the two essential conditions required for a recursive function to work correctly.
Recursion is a programming technique where a function calls itself directly or indirectly to solve a problem. The problem is solved by breaking it down into smaller instances of the same problem.
Essential Conditions
-
Base Case (Termination Condition):
- There must be at least one condition where the function does not call itself.
- This stops the recursion chain and prevents an infinite loop (stack overflow).
- Example: In factorial calculation,
if (n == 0) return 1;.
-
Recursive Case:
- The part of the function where it calls itself.
- The recursive call must move the problem closer to the base case (e.g., reducing the input size).
- Example:
return n * factorial(n - 1);.
Write a recursive function in C to calculate the Factorial of a number . Show the mathematical logic used.
Mathematical Logic
The factorial of a non-negative integer , denoted by , is defined as:
C Program Segment
c
include <stdio.h>
long int factorial(int n) {
// Base Case
if (n == 0) {
return 1;
}
// Recursive Case
else {
return n * factorial(n - 1);
}
}
int main() {
int n = 5;
printf("Factorial of %d is %ld", n, factorial(n));
return 0;
}
Execution Trace for n=3:
factorial(3)calls3 * factorial(2)factorial(2)calls2 * factorial(1)factorial(1)calls1 * factorial(0)factorial(0)returns1- Unwinding: .
Compare Recursion and Iteration (Loops).
Recursion vs Iteration
| Aspect | Recursion | Iteration |
|---|---|---|
| Definition | A function calls itself to solve a problem. | A block of code is repeated using loops (for, while, do-while). |
| Termination | Uses a Base Case to stop. | Uses a loop continuation/termination condition. |
| Memory Usage | High: Uses a stack frame for every recursive call (can lead to Stack Overflow). | Low: Only one set of variables is typically maintained. |
| Speed | Generally slower due to overhead of function calls (push/pop stack). | Generally faster (CPU cycles are used only for operations, not call overhead). |
| Code Size | Code is often shorter and cleaner for problems like tree traversals or Towers of Hanoi. | Code can become complex for recursive-natured data structures. |
| Risk | Infinite recursion leads to system crash (Stack Overflow). | Infinite loops run forever but usually consume CPU, not memory (unless allocating memory inside loop). |
Write a recursive C function to generate the term of the Fibonacci series.
The Fibonacci sequence is defined as:
With base cases: .
C Function
c
int fibonacci(int n) {
// Base Cases
if (n == 0) {
return 0;
}
else if (n == 1) {
return 1;
}
// Recursive Step
else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
Note: While this demonstrates recursion, it is inefficient for large due to repeated calculations of the same sub-problems.
Explain the concept of Scope in C. Differentiate between Global Scope and Local Scope.
Scope determines the region of the program where a variable is visible and can be accessed.
Local Scope
- Definition: Variables defined inside a function or a block
{ }. - Visibility: Accessible only within that specific function or block.
- Lifetime: Created when control enters the block and destroyed when control exits.
Global Scope
- Definition: Variables defined outside of all functions (usually at the top of the program).
- Visibility: Accessible by all functions in the program (after the declaration point).
- Lifetime: Exists for the entire duration of the program execution.
Example:
c
int globalVar = 10; // Global Scope
void func() {
int localVar = 5; // Local Scope
// Can access globalVar here
}
// Cannot access localVar here
What are Storage Classes in C? List the four storage classes available.
Storage Classes in C define the following attributes of a variable:
- Scope: Where the variable is available.
- Visibility: Who can see the variable.
- Lifetime: How long the variable stays in memory.
- Storage Place: Where the variable is stored (Stack, CPU Register, Data Segment).
- Default Initial Value: What the value is if not initialized.
List of Storage Classes:
auto(Automatic)register(Register)static(Static)extern(External)
Explain the auto storage class with respect to scope, lifetime, and default value.
The auto (automatic) storage class is the default for all local variables.
- Keyword:
auto(optional, rarely written). - Storage Location: Stack memory.
- Scope: Local. Only within the function or block
{ }where it is defined. - Lifetime: Exists only while the control is within the block. It is destroyed upon exit.
- Default Initial Value: Garbage value (unpredictable) if not manually initialized.
Example:
c
void function() {
auto int x; // same as int x;
// x has garbage value here
}
Discuss the extern storage class. How is it used to share variables between multiple files?
The extern (external) storage class is used to declare a global variable or function that is defined in another file or another part of the same file.
- Keyword:
extern. - Storage Location: Data segment (RAM).
- Scope: Global. Visible to all functions in the program.
- Lifetime: Throughout the program execution.
- Default Initial Value: Zero.
Usage across files
It tells the compiler, "The variable is not defined here, but it exists somewhere else."
File1.c
c
int count = 10; // Definition
File2.c
c
extern int count; // Declaration referring to File1
void printCount() {
printf("%d", count); // Prints 10
}
Explain the static storage class. How does a static local variable differ from a standard local variable?
The static storage class preserves the value of a variable even after the variable's scope has been exited.
- Keyword:
static. - Storage Location: Data segment.
- Default Value: Zero.
Static Local Variable vs Standard Local (auto) Variable
- Lifetime:
auto: Created on entry, destroyed on exit.static: Created once (first call), persists between function calls until the program ends.
- Initialization:
auto: Re-initialized every time the function is called.static: Initialized only once.
Example:
c
void counter() {
static int count = 0;
count++;
printf("%d ", count);
}
// Calling counter() 3 times prints: 1 2 3
// If 'count' was 'auto', it would print: 1 1 1
What is the purpose of the register storage class? What are its limitations?
The register storage class is a request to the compiler to store the variable in a CPU Register instead of RAM (memory) for faster access.
- Purpose: Used for frequently accessed variables (e.g., loop counters) to improve execution speed.
- Scope & Lifetime: Same as
auto(Local scope, block lifetime). - Default Value: Garbage value.
Limitations
- No Address Operator (
&): You cannot obtain the address of a register variable (e.g.,&xis illegal) because registers do not have memory addresses. - Hardware Constraints: The number of CPU registers is limited. If no register is available, the compiler treats it as
auto. - Size: Generally, only variables fitting the register size (like
int,char, or pointers) can be stored.
Create a comparative table of the four Storage Classes (Auto, Register, Static, Extern) based on Storage, Initial Value, Scope, and Lifetime.
Comparison of Storage Classes
| Feature | auto |
register |
static |
extern |
|---|---|---|---|---|
| Storage | Stack Memory | CPU Register | Data Segment | Data Segment |
| Default Value | Garbage | Garbage | Zero | Zero |
| Scope | Local (Within block) | Local (Within block) | Local (if defined inside function) | Global (Entire program) |
| Lifetime | End of block | End of block | End of Program | End of Program |
Note: static can also have global scope if defined outside a function (restricted to that specific file), but the table refers to the common usage of internal static variables compared to auto.
Write a recursive function to calculate (Power of a number).
To calculate recursively:
- Base Case: If , return 1.
- Recursive Case: .
C Code
c
include <stdio.h>
double power(double base, int exp) {
if (exp == 0)
return 1;
else
return base * power(base, exp - 1);
}
int main() {
double base = 2.0;
int exp = 3;
printf("%.2lf to the power %d is %.2lf", base, exp, power(base, exp));
return 0;
}
Predict the output of the following code snippet and explain why.
c
include <stdio.h>
void fun() {
static int x = 1;
int y = 1;
x++;
y++;
printf("%d %d\n", x, y);
}
int main() {
fun();
fun();
return 0;
}
Output
2 2
3 2
Explanation
-
Variable
y(auto): It is a standard local variable. Every timefun()is called,yis re-created and initialized to 1. It increments to 2, prints, and is destroyed.- Call 1: .
- Call 2: .
-
Variable
x(static): It is initialized to 1 only once when the program starts. It retains its value between function calls.- Call 1:
xstarts at 1, increments to 2. Prints 2. - Call 2:
xretains the value 2, increments to 3. Prints 3.
- Call 1:
Explain the mechanism of parameter passing in a function. What is a 'Stack Frame' or 'Activation Record'?
When a function is called, the system allocates a block of memory on the Stack known as a Stack Frame or Activation Record.
Contents of a Stack Frame:
- Return Address: Where control should go after the function finishes.
- Parameters: Values passed from the calling function (Actual arguments copied to Formal parameters).
- Local Variables: Variables declared inside the function.
Mechanism:
- Push: When
maincallsfunc, a frame forfuncis pushed onto the stack on top ofmain's frame. - Execution: The CPU executes
funcusing the variables in this top frame. - Pop: When
funcreturns, its frame is popped (removed), releasing memory, and control returns to the address stored in the Return Address field, resumingmain.