Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Function

The document contains a series of questions and answers related to functions in C programming, categorized into easy, medium, hard, conceptual, programming, output, and descriptive questions. It covers topics such as function syntax, recursion, array manipulation, and the differences between various function types. Additionally, it provides code examples and explanations for each question to aid understanding.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Function

The document contains a series of questions and answers related to functions in C programming, categorized into easy, medium, hard, conceptual, programming, output, and descriptive questions. It covers topics such as function syntax, recursion, array manipulation, and the differences between various function types. Additionally, it provides code examples and explanations for each question to aid understanding.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Easy Questions

1. What is a function in C?
o Answer: A function is a block of code that performs a specific task. It is called
by its name and can take arguments and return a value.
2. What is the syntax for declaring a function in C?
o Answer:

return_type function_name(parameters) {
// Code
}

3. What is the difference between void and int return types in functions?
o Answer: A void function does not return a value, while an int function
returns an integer value.
4. Write a function to calculate the square of a number.
o Code:

int square(int num) {


return num * num;
}

o Output: Call square(4) → Output: 16.


5. What is the default return type of a function in C?
o Answer: int.
6. Write a program to find the sum of two numbers using a function.
o Code:

int add(int a, int b) {


return a + b;
}

int main() {
printf("%d", add(5, 3));
return 0;
}

o Output: 8.

Medium Questions

7. Write a program to find the factorial of a number using recursion.


o Code:

c
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}

int main() {
printf("%d", factorial(5));
return 0;
}

o Output: 120.
8. Explain the concept of pass-by-value in C.
o Answer: In C, function arguments are passed by value. Changes to the
parameter inside the function do not affect the original argument.
9. Write a function to check if a number is even or odd.
o Code:

int isEven(int num) {


return num % 2 == 0;
}

int main() {
printf(isEven(10) ? "Even" : "Odd");
return 0;
}

o Output: Even.
10. How do you declare and call a function with no parameters?
o Answer:

void myFunction() {
printf("Hello");
}

int main() {
myFunction();
return 0;
}

o Output: Hello.
11. Write a program to calculate the GCD of two numbers using a function.
o Code:

int gcd(int a, int b) {


if (b == 0) return a;
return gcd(b, a % b);
}

int main() {
printf("%d", gcd(24, 36));
return 0;
}

o Output: 12.

Hard Questions

12. Write a program to generate the Fibonacci series up to n terms using recursion.
o Code:

int fibonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
for (int i = 0; i < 5; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}

o Output: 0 1 1 2 3.
13. What is the difference between a function declaration and a function definition in C?
o Answer:
 Function Declaration: Tells the compiler about a function's name,
return type, and parameters.
 Function Definition: Contains the actual implementation of the
function.
14. Write a program to reverse a string using a function.
o Code:

void reverse(char str[]) {


int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - 1 - i];
str[len - 1 - i] = temp;
}
}

int main() {
char str[] = "Hello";
reverse(str);
printf("%s", str);
return 0;
}

o Output: olleH.
15. How is memory allocated for function calls in C?
o Answer: Memory for function calls is allocated on the stack. Each call creates
a new stack frame.
16. Write a function to find the maximum of three numbers.
o Code:

int maxOfThree(int a, int b, int c) {


return (a > b && a > c) ? a : (b > c ? b : c);
}

int main() {
printf("%d", maxOfThree(10, 20, 15));
return 0;
}

o Output: 20.

Conceptual Questions

17. What is a recursive function?


o Answer: A recursive function calls itself either directly or indirectly to solve
smaller subproblems.
18. What is the role of the return statement in a function?
o Answer: It is used to return a value from a function to the caller.
19. What are the advantages of using functions in C?
o Answer: Reusability, modularity, readability, and easier debugging.
20. Can a function return multiple values in C?
o Answer: No, but it can return values via pointers or structures.

Programming Questions

21. Write a program to swap two numbers using a function.


22. Write a function to count the number of vowels in a string.
23. Write a program to check if a number is a palindrome using a function.
24. Write a program to sort an array using the bubble sort algorithm via a function.
25. Write a program to calculate the power of a number using recursion.
26. Write a program to find the transpose of a matrix using a function.
27. Write a function to calculate the length of a string without using strlen.
28. Write a function to convert a decimal number to binary.
29. Write a function to check if a number is prime.
30. Write a function to calculate the sum of digits of a number recursively.

Output Questions
31. Predict the output of:

void test() {
printf("Test");
}

int main() {
test();
return 0;
}

o Output: Test.
32. Predict the output:

int test() {
return 5;
}

int main() {
printf("%d", test());
return 0;
}

o Output: 5.

Conceptual Questions

1. What is the difference between call by value and call by reference in C?


o Answer:
 Call by Value: A copy of the actual parameter is passed. Changes in
the function do not affect the original variable.
 Call by Reference: The actual memory address of the variable is
passed. Changes in the function affect the original variable.
2. What is a function prototype? Why is it necessary?
o Answer: A function prototype declares the function's name, return type, and
parameters to the compiler before its actual definition. It is necessary to avoid
errors during compilation when functions are used before their definition.
3. What is recursion? List some examples where recursion is useful.
o Answer: Recursion is a process where a function calls itself. Examples
include calculating factorial, generating Fibonacci series, solving Tower of
Hanoi, and performing binary search.
4. What is a static function in C?
o Answer: A static function in C has internal linkage, meaning it can only be
accessed within the file in which it is declared.
5. Explain the difference between return and exit() in C.
o Answer:
 return: Used to return control to the calling function.
 exit(): Terminates the program execution immediately.
6. What is the purpose of the main() function in C?
o Answer: The main() function serves as the entry point for program execution.
Every C program must have a main() function.
7. Can a function be called without its definition in C?
o Answer: Yes, if its prototype is declared before the call.
8. What is the difference between global and local functions?
o Answer:
 Global Function: Accessible throughout the program.
 Local Function: Restricted to the file or block where it is defined.
9. What is a variadic function in C? Provide an example.
o Answer: A function that can accept a variable number of arguments, e.g.,
printf().
10. What is the importance of the return type in a function?
o Answer: It determines the type of value a function will return to its caller.

Descriptive Questions

1. Explain the lifecycle of a function call in C.


o Answer:
1. Call Preparation: The program stores arguments in memory or
registers.
2. Control Transfer: The control is transferred to the function.
3. Execution: The function executes its code.
4. Return Value: The return value is passed to the caller.
5. Control Back to Caller: Execution resumes after the function call.
2. How can you pass an array to a function in C? Provide an example.
o Answer: Arrays are passed by reference by passing the array name, which is a
pointer to its first element. Example:

void printArray(int arr[], int size) {


for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
}

int main() {
int arr[] = {1, 2, 3};
printArray(arr, 3);
return 0;
}

3. Describe the differences between iterative and recursive approaches in solving


problems.
o Answer:
 Iterative: Uses loops to repeat code. It’s usually faster and more
memory-efficient.
 Recursive: Uses function calls. It’s easier to implement for problems
like tree traversal but may use more memory.
4. What are the advantages and disadvantages of using functions in C?
o Answer:
 Advantages: Code reuse, modularity, readability, and easier
debugging.
 Disadvantages: Overhead for function calls and complexity in
debugging recursive functions.

Predict the Output (Hard)


1. c

int fun(int n) {
if (n == 1) return 0;
return 1 + fun(n / 2);
}

int main() {
printf("%d", fun(16));
return 0;
}

o Output: 4 (Counts the number of divisions by 2 until n becomes 1).


2. c

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

int main() {
int x = 10, y = 20;
swap(&x, &y);
printf("%d %d", x, y);
return 0;
}

o Output: 20 10.
3. c

void test(int x) {
printf("%d ", x);
if (x > 1) test(x - 1);
}

int main() {
test(3);
return 0;
}

o Output: 3 2 1.
4. c

int add(int a, int b) {


if (b == 0) return a;
return add(a + 1, b - 1);
}

int main() {
printf("%d", add(3, 2));
return 0;
}

o Output: 5.
5. c

int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}

int main() {
printf("%d", fib(4));
return 0;
}

o Output: 3.

Programming Question Answers

1. Swap Two Numbers Using a Function:

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

2. Count Vowels in a String:

int countVowels(char str[]) {


int count = 0;
for (int i = 0; str[i] != '\0'; i++) {
char c = tolower(str[i]);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
count++;
}
return count;
}

3. Check Palindrome:

int isPalindrome(char str[]) {


int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
if (str[i] != str[len - 1 - i]) return 0;
}
return 1;
}

4. Bubble Sort:

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

5. Power of a Number:

int power(int base, int exp) {


if (exp == 0) return 1;
return base * power(base, exp - 1);
}
4o

You said:

Give some function to array type questions too.


ChatGPT said:

ChatGPT

Here are some function-to-array type questions with varying difficulty, including
conceptual, descriptive, and coding questions with answers:

Conceptual Questions

1. How can an array be passed to a function in C?


o Answer: An array can be passed to a function by passing its base address
(array name). The function can then access or modify the array elements.
2. What happens if you try to return an array directly from a function?
o Answer: Arrays cannot be returned directly from a function in C. Instead,
pointers, dynamic memory, or structures can be used to achieve this.
3. Why are array parameters passed by reference in C?
o Answer: Arrays in C decay into pointers when passed to a function. The
function operates on the same memory as the original array, effectively
passing it by reference.
4. What is the difference between passing an array and passing a pointer to a
function?
o Answer:
 When passing an array, the function gets the base address of the array
and can access all its elements.
 When passing a pointer, the function operates directly on the pointer,
which may not necessarily represent an array.
5. Explain how multi-dimensional arrays are passed to a function.
o Answer: Multi-dimensional arrays are passed by specifying all dimensions
except the first in the function prototype. For example:

void func(int arr[][3], int rows);

Descriptive Questions

1. How do you pass a 2D array to a function? Provide an example.


o Answer:
Example:

void printMatrix(int arr[][3], int rows) {


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

int main() {
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
printMatrix(matrix, 2);
return 0;
}

2. How can you modify an array within a function? Provide an example.


o Answer: Arrays can be modified directly by accessing their elements through
the passed pointer. Example:

void modifyArray(int arr[], int size) {


for (int i = 0; i < size; i++) {
arr[i] += 1; // Increment each element
}
}

int main() {
int arr[5] = {1, 2, 3, 4, 5};
modifyArray(arr, 5);
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]); // Output: 2 3 4 5 6
}
return 0;
}

3. What are the limitations of passing arrays to functions?


o Answer:
 The size of the array is not inherently known; it must be passed as an
additional parameter.
 Arrays are always passed by reference, so modifications affect the
original array.
 Only the first dimension can be omitted in multi-dimensional arrays.

Programming Questions with Answers

1. Write a function to calculate the sum of all elements in an array.

int sumArray(int arr[], int size) {


int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}

int main() {
int arr[5] = {1, 2, 3, 4, 5};
printf("Sum: %d", sumArray(arr, 5));
return 0;
}

Output: Sum: 15

2. Write a function to find the largest element in an array.

int maxElement(int arr[], int size) {


int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) max = arr[i];
}
return max;
}

int main() {
int arr[5] = {10, 20, 5, 40, 25};
printf("Max: %d", maxElement(arr, 5));
return 0;
}

Output: Max: 40

3. Write a function to reverse an array.

void reverseArray(int arr[], int size) {


for (int i = 0; i < size / 2; i++) {
int temp = arr[i];
arr[i] = arr[size - 1 - i];
arr[size - 1 - i] = temp;
}
}

int main() {
int arr[5] = {1, 2, 3, 4, 5};
reverseArray(arr, 5);
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]); // Output: 5 4 3 2 1
}
return 0;
}

4. Write a function to count occurrences of a number in an array.

int countOccurrences(int arr[], int size, int num) {


int count = 0;
for (int i = 0; i < size; i++) {
if (arr[i] == num) count++;
}
return count;
}

int main() {
int arr[6] = {1, 2, 3, 2, 5, 2};
printf("Occurrences: %d", countOccurrences(arr, 6, 2));
return 0;
}

Output: Occurrences: 3

5. Write a function to merge two arrays into a single array.

void mergeArrays(int arr1[], int size1, int arr2[], int size2, int
result[]) {
for (int i = 0; i < size1; i++) result[i] = arr1[i];
for (int i = 0; i < size2; i++) result[size1 + i] = arr2[i];
}

int main() {
int arr1[3] = {1, 2, 3};
int arr2[3] = {4, 5, 6};
int result[6];
mergeArrays(arr1, 3, arr2, 3, result);
for (int i = 0; i < 6; i++) {
printf("%d ", result[i]); // Output: 1 2 3 4 5 6
}
return 0;
}

6. Write a function to calculate the average of elements in an array.

double averageArray(int arr[], int size) {


int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return (double)sum / size;
}

int main() {
int arr[4] = {10, 20, 30, 40};
printf("Average: %.2f", averageArray(arr, 4));
return 0;
}

Output: Average: 25.00

7. Write a function to rotate an array to the left by one position.

void rotateLeft(int arr[], int size) {


int first = arr[0];
for (int i = 0; i < size - 1; i++) {
arr[i] = arr[i + 1];
}
arr[size - 1] = first;
}

int main() {
int arr[5] = {1, 2, 3, 4, 5};
rotateLeft(arr, 5);
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]); // Output: 2 3 4 5 1
}
return 0;
}

8. Write a function to find the frequency of each element in an array.

void frequencyArray(int arr[], int size) {


int freq[size];
for (int i = 0; i < size; i++) freq[i] = -1;

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


int count = 1;
if (freq[i] != -1) continue;
for (int j = i + 1; j < size; j++) {
if (arr[i] == arr[j]) {
count++;
freq[j] = 0;
}
}
freq[i] = count;
}

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


if (freq[i] != 0)
printf("Element %d occurs %d times\n", arr[i], freq[i]);
}
}

int main() {
int arr[6] = {1, 2, 2, 3, 3, 3};
frequencyArray(arr, 6);
return 0;
}

Output:

bash

Element 1 occurs 1 times


Element 2 occurs 2 times
Element 3 occurs 3 times

Predict the Output Questions


1. c
Copy code
void func(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] = arr[i] * 2;
}
}

int main() {
int arr[] = {1, 2, 3, 4};
func(arr + 1, 3);
for (int i = 0; i < 4; i++) {
printf("%d ", arr[i]);
}
return 0;
}

Output: 1 4 6 8
Explanation: func operates on arr + 1, doubling elements from index 1 onward.

2. c
Copy code
void swap(int *a, int *b) {
int *temp = a;
a = b;
b = temp;
}

int main() {
int x = 5, y = 10;
swap(&x, &y);
printf("%d %d", x, y);
return 0;
}

Output: 5 10
Explanation: The pointers a and b are swapped, not the values they point to. This has
no effect on the original variables.

3. c
Copy code
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *p = arr;
*(p + 2) = 100;
printf("%d %d", arr[2], *(arr + 2));
return 0;
}

Output: 100 100


Explanation: *(p + 2) modifies the value at index 2 of the array.

4. c
Copy code
int main() {
int a = 5, b = 10;
int *p1 = &a, *p2 = &b;
*p1 += *p2;
*p2 = *p1 - *p2;
printf("%d %d", a, b);
return 0;
}

Output: 15 5
Explanation: *p1 += *p2 makes a = 15. Then *p2 = *p1 - *p2 assigns b = 5.

5. c
Copy code
int fun(int n) {
if (n % 2 == 0)
return n / 2;
else
return 3 * n + 1;
}

int main() {
int x = 6;
for (int i = 0; i < 3; i++) {
x = fun(x);
printf("%d ", x);
}
return 0;
}
Output: 3 10 5
Explanation:

o Iteration 1: fun(6) → 6 / 2 = 3
o Iteration 2: fun(3) → 3 * 3 + 1 = 10
o Iteration 3: fun(10) → 10 / 2 = 5
6. c
Copy code
int main() {
int arr[] = {1, 2, 3, 4, 5};
int *p = arr + 1;
*(p++) = 10;
*(p + 1) = 20;
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}

Output: 1 10 3 20 5
Explanation:

o *(p++) = 10 updates arr[1] to 10 and increments p to point to arr[2].


o *(p + 1) = 20 updates arr[3] to 20.
7. c
Copy code
void modify(int *arr, int size) {
for (int i = 0; i < size; i++) {
*(arr + i) += i;
}
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
modify(arr, 5);
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}

Output: 1 3 5 7 9
Explanation: Each element in the array is incremented by its index.

8. c
Copy code
int main() {
int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
printf("%d %d", arr[1][1], *(*(arr + 2) + 2));
return 0;
}

Output: 5 9
Explanation:

o arr[1][1] accesses the element at row 1, column 1.


o *(*(arr + 2) + 2) accesses the element at row 2, column 2.
9. c
Copy code
int fun(int x) {
return (x & 1) ? x * 2 : x / 2;
}

int main() {
int arr[] = {1, 2, 3, 4};
for (int i = 0; i < 4; i++) {
printf("%d ", fun(arr[i]));
}
return 0;
}

Output: 2 1 6 2
Explanation: The fun function doubles odd numbers and halves even numbers.

10.

c
Copy code
int main() {
char str[] = "Hello";
char *p = str;
*p = 'Y';
printf("%s", str);
return 0;
}

Output: Yello
Explanation: The first character of the string is modified to 'Y'.

You might also like