Basic Concepts of Functions
1. What is a global variable in C? Why do we need such a variable?
A global variable in C is a variable that is declared outside of all functions, typically at the top of a program. It has global scope, meaning it can be accessed and modified by any function in the program.
We need global variables when:
- Multiple functions need to access the same data
- We want to maintain state information across function calls
- We need to share data between functions without passing parameters
However, excessive use of global variables is discouraged as it can lead to code that is difficult to debug and maintain.
2. Write the syntax of a function declaration. The name of the function is calculateAge(). The function accepts the current year and birth year of a person. The function returns the age of the person.
int calculateAge(int currentYear, int birthYear);
3. Write the code segment for the function definition of the above function calculateAge().
int calculateAge(int currentYear, int birthYear) {
int age = currentYear - birthYear;
return age;
}
4. What are different types of functions in C? Differentiate among them.
In C, functions can be categorized based on:
| Category |
Types |
Description |
| Based on arguments and return values |
Functions with arguments and return value |
Accept parameters and return a value |
|
Functions with arguments but no return value |
Accept parameters but don't return anything (void) |
|
Functions without arguments but with return value |
Don't accept parameters but return a value |
|
Functions without arguments and return value |
Don't accept parameters and don't return anything |
| Based on definition |
Library functions |
Predefined functions in C standard library (e.g., printf(), scanf()) |
|
User-defined functions |
Functions created by the programmer |
| Based on recursion |
Recursive functions |
Functions that call themselves |
|
Non-recursive functions |
Functions that don't call themselves |
5. Differentiate between caller and callee functions. Write a small C program and identify the caller and callee function in it.
Caller function: The function that calls another function.
Callee function: The function that is being called.
#include <stdio.h>
void greet() {
printf("Hello, World!\n");
}
int main() {
greet();
return 0;
}
Function Types & Components
6. When do we call a function user-defined? Is printf() a user-defined function? Justify.
A function is called user-defined when it is created by the programmer rather than being part of the C standard library.
printf() is NOT a user-defined function. It is a library function that is predefined in the C standard library (stdio.h). We don't need to define printf() ourselves; we just include the header file and use it.
7. Can we have two functions with the same name but with different numbers of parameters in a single C program? Write a simple C program to justify your answer.
No, C does not support function overloading like C++. In C, we cannot have two functions with the same name even if they have different numbers or types of parameters.
However, we can achieve similar functionality using variable arguments or different function names:
#include <stdio.h>
int addTwo(int a, int b) {
return a + b;
}
int addThree(int a, int b, int c) {
return a + b + c;
}
int main() {
printf("Sum of two numbers: %d\n", addTwo(5, 10));
printf("Sum of three numbers: %d\n", addThree(5, 10, 15));
return 0;
}
8. What are different components of a function? Show with a complete C program.
The main components of a function in C are:
- Function declaration/prototype: Tells the compiler about the function's name, return type, and parameters
- Function definition: Contains the actual code of the function
- Function call: Invokes the function to execute its code
- Parameters/Arguments: Values passed to the function
- Return type: The data type of the value returned by the function
#include <stdio.h>
int multiply(int a, int b);
int main() {
int x = 5, y = 10, result;
result = multiply(x, y);
printf("Product: %d\n", result);
return 0;
}
int multiply(int a, int b) {
return a * b;
}
9. Define recursive function. Can we use a recursive function to solve all kinds of problems?
A recursive function is a function that calls itself directly or indirectly to solve a problem. It typically has:
- A base case (termination condition) that stops the recursion
- A recursive case that calls the function with modified parameters
While recursive functions can solve many problems, they are not suitable for all kinds of problems because:
- They can cause stack overflow for deep recursion
- They may be less efficient than iterative solutions due to function call overhead
- Some problems are naturally iterative and don't lend themselves to recursive solutions
- Recursive solutions can be harder to understand and debug for some programmers
Recursive functions are best suited for problems that can be broken down into similar subproblems, such as tree traversals, factorial calculation, Fibonacci series, etc.
Practical Programs
12. Write a C program and define a function square() that accepts a number as the parameter and returns the square of that number as output.
#include <stdio.h>
int square(int num) {
return num * num;
}
int main() {
int number, result;
printf("Enter a number: ");
scanf("%d", &number);
result = square(number);
printf("Square of %d is %d\n", number, result);
return 0;
}
13. Write a C program and define a function search() that searches an element in an array and returns the index of the element.
#include <stdio.h>
int search(int arr[], int size, int element) {
for (int i = 0; i < size; i++) {
if (arr[i] == element) {
return i;
}
}
return -1;
}
int main() {
int arr[] = {10, 23, 45, 70, 11, 33};
int size = sizeof(arr) / sizeof(arr[0]);
int element, index;
printf("Enter element to search: ");
scanf("%d", &element);
index = search(arr, size, element);
if (index != -1) {
printf("Element found at index %d\n", index);
} else {
printf("Element not found in the array\n");
}
return 0;
}
14. Write a C program and define a recursive function to find the summation of first N natural numbers.
#include <stdio.h>
int sumNatural(int n) {
if (n == 0) {
return 0;
}
else {
return n + sumNatural(n - 1);
}
}
int main() {
int n, sum;
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n < 0) {
printf("Please enter a positive integer.\n");
} else {
sum = sumNatural(n);
printf("Sum of first %d natural numbers is %d\n", n, sum);
}
return 0;
}
15. Write a C program and define a function add() that accepts three integers. These integers indicate indices of an integer array. The function returns the summation of the elements stored in those indices.
#include <stdio.h>
int add(int arr[], int index1, int index2, int index3) {
return arr[index1] + arr[index2] + arr[index3];
}
int main() {
int arr[] = {7, 8, 8, 0, 0, 9};
int size = sizeof(arr) / sizeof(arr[0]);
int index1, index2, index3, result;
printf("Array elements: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
index1 = 0;
index2 = 2;
index3 = 5;
result = add(arr, index1, index2, index3);
printf("Sum of elements at indices %d, %d, and %d is: %d\n",
index1, index2, index3, result);
printf("Calculation: %d + %d + %d = %d\n",
arr[index1], arr[index2], arr[index3], result);
return 0;
}
Output: Sum of elements at indices 0, 2, and 5 is: 24
Calculation: 7 + 8 + 9 = 24
Code Analysis
10. Consider the below code and list all the syntax errors.
#include<stdio.h>
int fun ( int x )
{
if ( x %2 == 0 )
return 1;
else
return 0;
}
int main ( )
{
int n = 10;
int result = fun ( n )
printf ( "Result = %d" , result ) ;
return 0 ;
}
Syntax Errors:
- Missing semicolon after the function call:
int result = fun(n) should be int result = fun(n);
- Missing space in the include directive:
#include<stdio.h> should be #include <stdio.h>
Corrected Code:
#include <stdio.h>
int fun(int x) {
if (x % 2 == 0)
return 1;
else
return 0;
}
int main() {
int n = 10;
int result = fun(n);
printf("Result = %d", result);
return 0;
}
11. Consider the below code and answer the questions.
#include <stdio.h>
int fun(int x, int y) {
if (x == 0)
return y;
else
return fun(x - 1, x + y);
}
int main() {
int a = 4, b = 3;
int result = fun(a, b);
printf("Result = %d", result);
return 0;
}
Questions:
- What is the output of the program?
The output is: Result = 13
- What does the function fun() do?
The function calculates the sum of the first x natural numbers plus y. It's a recursive function that computes: y + (1 + 2 + 3 + ... + x)
- Trace the execution for fun(4, 3):
- fun(4, 3) → fun(3, 4+3=7)
- fun(3, 7) → fun(2, 3+7=10)
- fun(2, 10) → fun(1, 2+10=12)
- fun(1, 12) → fun(0, 1+12=13)
- fun(0, 13) → return 13
Final result: 13