Unit 4: Functions - Subjective Questions
CAP1008 — C Programming • Practice Questions with Detailed Answers
20 questions
Define a function in C. Explain the general syntax of a function definition with a suitable example.
A function is a self-contained block of code that performs a specific task and can be reused whenever needed. Functions help in modular programming, reducing code duplication and improving readability.
General Syntax of a Function Definition:
return_type function_name(parameter_list)
{
// body of the function
return value;
}- return_type: Data type of the value returned by the function (e.g.,
int,float,void). - function_name: A valid identifier that names the function.
- parameter_list: List of input arguments with their types.
- body: Statements that define the task performed.
Example:
int add(int a, int b)
{
int sum = a + b;
return sum;
}Here, add takes two integers and returns their sum. This function can be called multiple times, e.g., add(5, 3) returns 8.
Distinguish between predefined (library) functions and user-defined functions with examples.
Predefined (Library) Functions and User-Defined Functions differ as follows:
| Basis | Predefined Functions | User-Defined Functions |
|---|---|---|
| Definition | Already defined in C libraries | Defined by the programmer |
| Header file | Require inclusion of header files (e.g., <stdio.h>, <math.h>) |
No special header needed |
| Examples | printf(), scanf(), sqrt(), strlen() |
add(), factorial(), display() |
| Modification | Cannot be modified by the user | Can be modified freely |
| Purpose | Perform common standard tasks | Perform custom tasks specific to a program |
Example of Predefined Function:
#include <math.h>
float r = sqrt(25.0); // returns 5.0Example of User-Defined Function:
int square(int n)
{
return n * n;
}- Predefined functions save development time and are optimized.
- User-defined functions provide flexibility to solve problem-specific requirements.
Explain the scope rules in C. Differentiate between local scope and global scope with examples.
Scope refers to the region of a program where a variable is accessible and valid.
Local Scope:
- Variables declared inside a function or block.
- Accessible only within that function/block.
- Created when the function is called and destroyed when it exits.
Global Scope:
- Variables declared outside all functions, usually at the top.
- Accessible by all functions in the program.
- Exist throughout the program's execution.
Example:
#include <stdio.h>
int g = 10; // global variable
void display()
{
int x = 5; // local variable
printf("Local x = %d, Global g = %d\n", x, g);
}
int main()
{
display();
printf("Global g = %d\n", g);
// printf("%d", x); // ERROR: x not accessible here
return 0;
}Key Differences:
| Local | Global |
|---|---|
| Declared inside function | Declared outside all functions |
| Limited scope | Program-wide scope |
| Short lifetime | Entire program lifetime |
| Higher safety, less coupling | Risk of unintended modification |
What is a pointer? Explain pointer declaration and initialization with examples.
A pointer is a variable that stores the memory address of another variable. Pointers allow direct memory access and efficient manipulation of data.
Pointer Declaration Syntax:
data_type *pointer_name;The * (asterisk) indicates that the variable is a pointer.
Examples of Declaration:
int *p; // pointer to int
float *fp; // pointer to float
char *cp; // pointer to charPointer Initialization:
A pointer is initialized using the address-of operator (&).
int a = 25;
int *p;
p = &a; // p now holds the address of aCombined Declaration and Initialization:
int a = 25;
int *p = &a;Key Points:
&agives the address of variablea.pstores that address.- Uninitialized pointers (wild pointers) should be avoided; initialize to
NULLif no address is assigned:
int *p = NULL;Explain how values are accessed using pointers. Describe the role of the dereference operator with an example.
Values are accessed through pointers using the dereference (indirection) operator *. When applied to a pointer, * gives the value stored at the address the pointer points to.
Two Important Operators:
&(address-of): returns the memory address of a variable.*(dereference): returns the value stored at a memory address.
Example:
#include <stdio.h>
int main()
{
int a = 50;
int *p = &a;
printf("Value of a = %d\n", a); // 50
printf("Address of a = %p\n", &a); // address
printf("Value of p = %p\n", p); // same address
printf("Value pointed by p = %d\n", *p); // 50
*p = 100; // modifying a through pointer
printf("New value of a = %d\n", a); // 100
return 0;
}Explanation:
*preads the value at the address held byp.- Assigning
*p = 100modifies the original variableaindirectly. - This demonstrates that pointers can both read and modify data through addresses.
Distinguish between call by value and call by reference (address) in C with suitable examples.
Call by Value and Call by Reference (Address) are two ways of passing arguments to functions.
Call by Value:
- A copy of the actual argument is passed.
- Changes made inside the function do not affect the original variable.
void swap(int x, int y)
{
int t = x; x = y; y = t;
}
// original values remain unchangedCall by Reference (Address):
- The address of the actual argument is passed using pointers.
- Changes inside the function affect the original variable.
void swap(int *x, int *y)
{
int t = *x; *x = *y; *y = t;
}
// called as swap(&a, &b); values actually swapComparison Table:
| Basis | Call by Value | Call by Reference |
|---|---|---|
| Passed | Copy of value | Address of variable |
| Effect on original | No change | Changes reflected |
| Memory | Uses more (copies) | Efficient |
| Uses pointers | No | Yes |
Conclusion: Call by reference is used when the function needs to modify actual arguments or when passing large data efficiently.
What is recursion? Explain with an example program to calculate the factorial of a number.
Recursion is a programming technique in which a function calls itself directly or indirectly to solve a problem. A recursive function must have:
- A base case (terminating condition) to stop recursion.
- A recursive case that reduces the problem toward the base case.
Factorial Example:
Mathematically, and .
#include <stdio.h>
int factorial(int n)
{
if (n == 0 || n == 1) // base case
return 1;
else
return n * factorial(n - 1); // recursive case
}
int main()
{
int num = 5;
printf("Factorial = %d\n", factorial(num));
return 0;
}Working for factorial(5):
- Each call waits for the next until the base case returns.
Advantages: Simplifies problems like factorial, Fibonacci, and tree traversals.
Disadvantage: Uses more memory (stack) and can be slower than iteration.
Describe the components of a function in C: function declaration (prototype), function definition, and function call.
A function in C works through three main components:
1. Function Declaration (Prototype):
- Informs the compiler about the function's name, return type, and parameters before use.
- Ends with a semicolon.
int add(int, int); // prototype2. Function Definition:
- Contains the actual body/implementation of the function.
int add(int a, int b)
{
return a + b;
}3. Function Call:
- Invokes the function to execute its code.
int result = add(5, 3); // callComplete Example:
#include <stdio.h>
int add(int, int); // declaration
int main()
{
printf("%d", add(5, 3)); // call
return 0;
}
int add(int a, int b) // definition
{
return a + b;
}Summary: The prototype tells what, the definition tells how, and the call tells when to execute the function.
Explain the advantages of using functions in C programming.
Functions offer several important benefits in C programming:
-
Modularity: A large program is divided into smaller, manageable modules, making it easier to develop and understand.
-
Code Reusability: A function written once can be called multiple times, avoiding repetition of code.
-
Easy Debugging and Maintenance: Errors can be isolated to specific functions, simplifying testing and correction.
-
Reduced Program Size: Repeated code is replaced with a single function, reducing overall length.
-
Improved Readability: Well-named functions make the program logic clearer.
-
Abstraction: The user can use a function by knowing what it does without knowing how it works internally.
-
Team Development: Different programmers can work on different functions simultaneously.
Example: Instead of writing addition logic repeatedly, a single add() function can be reused:
int add(int a, int b) { return a + b; }
// used as add(2,3), add(10,20), etc.These advantages make functions a foundation of structured programming.
What are library functions? Explain commonly used library functions from stdio.h, math.h, and string.h.
Library functions are predefined functions provided by the C standard library. They are stored in header files and can be used by including the appropriate header.
1. stdio.h (Standard Input/Output):
printf()— displays output on screen.scanf()— reads input from user.getchar(),putchar()— read/write single characters.
2. math.h (Mathematical Functions):
sqrt(x)— square root of .pow(x, y)— computes .abs(x)— absolute value.sin(x),cos(x)— trigonometric functions.
#include <math.h>
float r = pow(2, 3); // 8.03. string.h (String Handling):
strlen(s)— length of string.strcpy(d, s)— copy string.strcat(d, s)— concatenate strings.strcmp(s1, s2)— compare strings.
#include <string.h>
int len = strlen("Hello"); // 5Advantages: Library functions are reliable, optimized, and save development time.
Write a C program using a user-defined function to check whether a given number is prime. Explain its working.
A prime number is a natural number greater than 1 that is divisible only by 1 and itself.
Program:
#include <stdio.h>
int isPrime(int n)
{
int i;
if (n <= 1)
return 0; // not prime
for (i = 2; i <= n / 2; i++)
{
if (n % i == 0)
return 0; // divisible, not prime
}
return 1; // prime
}
int main()
{
int num = 7;
if (isPrime(num))
printf("%d is Prime\n", num);
else
printf("%d is Not Prime\n", num);
return 0;
}Working:
- The function
isPrime()checks divisibility from to . - If any number divides
nevenly, it returns0(not prime). - If no divisor is found, it returns
1(prime). - For
num = 7, no divisor exists, so output is "7 is Prime".
This demonstrates a user-defined function returning a value used in decision-making.
Explain the concept of passing arguments by address to swap two numbers. Write the complete program.
Passing arguments by address means sending the memory addresses of variables to a function using pointers. This allows the function to modify the original variables. Swapping two numbers is a classic example that requires call by address.
Program:
#include <stdio.h>
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int a = 10, b = 20;
printf("Before swap: a = %d, b = %d\n", a, b);
swap(&a, &b); // passing addresses
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}Working:
&aand&bpass the addresses ofaandb.- Inside
swap(),*xand*yaccess the actual values. - Swapping
*xand*ychanges the original variables.
Output:
Before swap: a = 10, b = 20
After swap: a = 20, b = 10
If call by value were used, the swap would not reflect in main() because only copies would be exchanged.
Compare recursion and iteration. State the advantages and disadvantages of each.
Recursion and iteration are two approaches to perform repetitive tasks.
Recursion: A function calls itself until a base condition is met.
Iteration: A loop (for, while, do-while) repeats a block of code.
Comparison Table:
| Basis | Recursion | Iteration |
|---|---|---|
| Definition | Function calls itself | Uses loops |
| Termination | Base case | Loop condition |
| Memory | Uses stack (more memory) | Uses less memory |
| Speed | Slower (function call overhead) | Faster |
| Code size | Shorter, elegant | Usually longer |
| Risk | Stack overflow if no base case | Infinite loop if condition wrong |
Advantages of Recursion:
- Simplifies complex problems (tree traversal, factorial, Fibonacci).
- Cleaner and more readable for certain problems.
Disadvantages of Recursion:
- Higher memory usage and slower execution.
- Difficult to trace and debug.
Advantages of Iteration:
- Efficient in memory and speed.
Disadvantages of Iteration:
- May be complex for problems that are naturally recursive.
Conclusion: Use recursion for problems with recursive structure; use iteration for performance-critical repetition.
Explain the different categories of functions based on arguments and return values with examples.
C functions can be categorized into four types based on arguments and return values:
1. Function with no arguments and no return value:
void greet()
{
printf("Hello\n");
}2. Function with arguments but no return value:
void display(int n)
{
printf("Number = %d\n", n);
}3. Function with no arguments but a return value:
int getNumber()
{
return 100;
}4. Function with arguments and a return value:
int add(int a, int b)
{
return a + b;
}Summary Table:
| Type | Arguments | Return Value |
|---|---|---|
| 1 | No | No |
| 2 | Yes | No |
| 3 | No | Yes |
| 4 | Yes | Yes |
The fourth type is most commonly used as it allows both input and output through the function.
Write a recursive C program to generate the Fibonacci series up to terms and explain the logic.
The Fibonacci series is a sequence where each term is the sum of the two preceding terms:
Mathematically:
Program:
#include <stdio.h>
int fib(int n)
{
if (n == 0)
return 0; // base case
else if (n == 1)
return 1; // base case
else
return fib(n - 1) + fib(n - 2); // recursive case
}
int main()
{
int n = 7, i;
printf("Fibonacci Series: ");
for (i = 0; i < n; i++)
printf("%d ", fib(i));
return 0;
}Logic:
- The function
fib()returns the value of the term. - Base cases handle and .
- For higher terms, it recursively adds the previous two terms.
Output:
Fibonacci Series: 0 1 1 2 3 5 8
Note: Recursive Fibonacci recomputes values repeatedly, so it is elegant but less efficient than the iterative version.
Explain the relationship between pointers and arrays in C with an example.
In C, arrays and pointers are closely related. The name of an array acts as a constant pointer to its first element.
Key Points:
arris equivalent to&arr[0](address of first element).*(arr + i)is equivalent toarr[i].- A pointer can be used to traverse an array.
Example:
#include <stdio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr; // p points to arr[0]
int i;
for (i = 0; i < 5; i++)
{
printf("%d ", *(p + i)); // same as arr[i]
}
return 0;
}Explanation:
p = arrmakesppoint to the first element.*(p + i)accesses the element using pointer arithmetic.- Adding 1 to a pointer moves it by the size of one element (e.g., 4 bytes for
int).
Output:
10 20 30 40 50
This relationship allows efficient array manipulation using pointers.
What is a NULL pointer and a wild pointer? Explain their significance in C programming.
NULL Pointer:
- A pointer that does not point to any valid memory location.
- It is explicitly assigned the value
NULL(or0).
int *p = NULL;- Used to indicate that the pointer is not currently pointing to any object.
- Helps avoid accidental memory access and is used in error checking.
Wild Pointer:
- A pointer that has been declared but not initialized.
- It contains a garbage address and may point anywhere in memory.
int *p; // wild pointer
*p = 10; // dangerous! undefined behaviorSignificance:
- NULL pointers provide safety; before dereferencing, we can check:
if (p != NULL)
printf("%d", *p);- Wild pointers are dangerous and can cause program crashes or unpredictable behavior. Always initialize pointers.
Comparison:
| Basis | NULL Pointer | Wild Pointer |
|---|---|---|
| Value | NULL/0 |
Garbage address |
| Safety | Safe | Unsafe |
| Initialization | Explicitly set | Not initialized |
Best Practice: Initialize every pointer either with a valid address or NULL.
Explain storage classes in C (auto, register, static, extern) and their effect on scope and lifetime.
Storage classes define the scope, lifetime, and visibility of variables in C.
1. auto (Automatic):
- Default for local variables.
- Scope: within the block. Lifetime: until block ends.
auto int x = 10;2. register:
- Suggests storing the variable in a CPU register for faster access.
- Scope and lifetime like
auto; address (&) cannot be taken.
register int count;3. static:
- Retains its value between function calls.
- Lifetime: entire program. Scope: local to the block/file.
static int c = 0; // keeps value across calls4. extern:
- Declares a global variable defined elsewhere (another file/scope).
- Extends visibility across multiple files.
extern int g;Summary Table:
| Storage Class | Scope | Lifetime | Default Value |
|---|---|---|---|
| auto | Local | Block | Garbage |
| register | Local | Block | Garbage |
| static | Local/File | Whole program | Zero |
| extern | Global | Whole program | Zero |
Storage classes help control memory usage and variable persistence.
Describe how a function returns a value. Write a program using a function that returns the largest of three numbers.
A function returns a value using the return statement. The value returned must match the function's declared return type. When the function is called, the returned value can be assigned to a variable or used in an expression.
Syntax:
return expression;Program to find the largest of three numbers:
#include <stdio.h>
int largest(int a, int b, int c)
{
int max = a;
if (b > max)
max = b;
if (c > max)
max = c;
return max; // returns the largest value
}
int main()
{
int x = 12, y = 45, z = 30;
int result = largest(x, y, z);
printf("Largest number = %d\n", result);
return 0;
}Working:
largest()compares the three numbers and stores the maximum inmax.return maxsends the result back tomain().- The returned value is stored in
resultand displayed.
Output:
Largest number = 45
Note: A function can return only one value at a time using return.
Explain the advantages and disadvantages of using pointers in C programming.
Pointers are powerful features of C that store memory addresses. They have both benefits and drawbacks.
Advantages:
- Efficient memory access: Direct access to memory locations speeds up processing.
- Dynamic memory allocation: Enable functions like
malloc()andfree()to manage memory at runtime. - Call by reference: Allow functions to modify actual arguments.
- Efficient array and string handling: Pointers can traverse arrays faster.
- Data structures: Essential for implementing linked lists, trees, stacks, and queues.
- Reduced execution time: Passing addresses avoids copying large data.
Disadvantages:
- Complexity: Pointers are difficult to understand and use correctly.
- Errors: Uninitialized (wild) pointers can cause crashes.
- Memory leaks: Failure to free dynamically allocated memory wastes resources.
- Segmentation faults: Invalid memory access leads to program termination.
- Debugging difficulty: Pointer-related bugs are hard to trace.
Example of dynamic allocation:
int *p = (int*)malloc(5 * sizeof(int));
// use p ...
free(p);Conclusion: Pointers offer flexibility and efficiency but must be used carefully to avoid errors and memory issues.
Define a function in C. Explain the general syntax of a function definition with a suitable example.
A function is a self-contained block of code that performs a specific task and can be reused whenever needed. Functions help in modular programming, reducing code duplication and improving readability.
General Syntax of a Function Definition:
return_type function_name(parameter_list)
{
// body of the function
return value;
}- return_type: Data type of the value returned by the function (e.g.,
int,float,void). - function_name: A valid identifier that names the function.
- parameter_list: List of input arguments with their types.
- body: Statements that define the task performed.
Example:
int add(int a, int b)
{
int sum = a + b;
return sum;
}Here, add takes two integers and returns their sum. This function can be called multiple times, e.g., add(5, 3) returns 8.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →