C Programming · Unit 7 · 5 hrs
Functions
Exam-focused notes for Functions (C Programming, CSC115): what the TU syllabus asks and how it has actually been tested, with 12 solved past questions from this unit.
Functions in short
This chapter looks at the function as C's unit of reusable code: how library and user-defined functions differ, how a function is declared, defined and called, how arguments and return values move data in and out of it, and how a variable's scope and lifetime decide where and how long it exists.
What this unit covers
- Library Functions
- User defined functions
- Function prototype, Function call, and Function Definition
- Nested and Recursive Function
- Function Arguments and Return Types
- Passing Arrays to Function
- Passing Strings to Function
- Passing Arguments by Value
- Passing Arguments by Address
- Scope visibility and lifetime of a variable
- Local and Global Variable
Passing Arguments by Address
2081 · 10 marks
Differentiate between library function and user defined function.Write a program to swap two values using call by reference concept.[2+8]
Show solved answerHide answer
Difference Between Library Function and User Defined Function + Swap Using Call by Reference
(a) Difference Between Library Function and User Defined Function
As per the course notes, C programs have two types of functions: Library Functions and User Defined Functions.
| S.N. | Library Function | User Defined Function |
|---|---|---|
| 1. | A predefined function stored in a header file or preprocessor directive. | Not predefined; it is defined by the programmer according to need. |
| 2. | Programmer can simply use this function by including the respective header file. | Programmer has to declare, define, and call this function by themselves. |
| 3. | Program is usually short as the programmer does not have to define the function. | Program is usually lengthy as the programmer has to define the function. |
| 4. | Program development time is faster. | Program development time is usually slower. |
| 5. | Program will be simple. | Program will be complex. |
| 6. | Requires a header file to use it (e.g., #include<stdio.h>). | Requires a function prototype to use it. |
Examples:
- Library functions:
printf(),scanf(),sqrt(),strlen()- User defined functions: any function written by the programmer for a specific task
(b) Program to Swap Two Values Using Call by Reference
Concept: Call by Reference
In call by reference, instead of passing the actual values to the function, the addresses (pointers) of the variables are passed. This means any changes made inside the function directly affect the original variables in the calling function.
Program
#include<stdio.h>
#include<conio.h>
/* Function prototype (declaration) */
void swap(int *a, int *b);
int main()
{
int x, y;
printf("Enter first value : ");
scanf("%d", &x);
printf("Enter second value : ");
scanf("%d", &y);
printf("\nBefore Swap: x = %d, y = %d\n", x, y);
/* Passing addresses of x and y - Call by Reference */
swap(&x, &y);
printf("After Swap: x = %d, y = %d\n", x, y);
getch();
return 0;
}
/* Function definition */
void swap(int *a, int *b)
{
int temp;
temp = *a; /* temp stores value at address a */
*a = *b; /* value at address a = value at address b */
*b = temp; /* value at address b = temp */
}
Step-by-Step Explanation
| Step | Statement | What Happens |
|---|---|---|
| 1 | swap(&x, &y) | Addresses of x and y are passed to the function |
| 2 | int *a, int *b | Pointer a holds address of x; pointer b holds address of y |
| 3 | temp = *a | temp gets the value stored at address a (i.e., value of x) |
| 4 | *a = *b | Value at address a (i.e., x) is replaced by value at address b (i.e., y) |
| 5 | *b = temp | Value at address b (i.e., y) is replaced by temp (original x) |
Sample Output
Enter first value : 10
Enter second value : 20
Before Swap: x = 10, y = 20
After Swap: x = 20, y = 10
Key Point
In call by reference, the function works with the actual memory locations of the variables. Therefore, the swap is reflected back in
main(), unlike call by value where only copies are passed and the original values remain unchanged.
Nested and Recursive Function
2081 · 5 marks
Demonstrate the use of recursive function with a suitable example. [5]
2080 · 5 marks
Write a program to calculate the factorial of a given number using recursion. [5]
2079 · 5 marks
Write a program to find the sum of digits of a given integer using recursion. [5]
Local and Global Variable
2081 · 5 marks
Write short notes on: a) Global variable b) Debugging Debugging [2.5+2.5]
2079 · 5 marks
Write short notes on: a. Local, Global, and Static variables b. Conditional Operator [5]
User defined functions
2080 · 10 marks
Define structure and nested structure. Write a program to find out whether the $n^{th}$ term of the Fibonacci series is a prime number or not. Read the value of $n$ from the user and display the result in the main function. Use separate user-defined function to (i) generate $n^{th}$ term and (ii) to check whether that number is prime or not.[3+7]
Show solved answerHide answer
Structure, Nested Structure, and Fibonacci Prime Program
(a) Definitions
Structure
A structure is a user-defined data type in C that allows grouping of variables of different data types under a single name. Each variable inside a structure is called a member or field.
Syntax:
struct structure_name {
data_type member1;
data_type member2;
...
};
Example:
struct Student {
int roll;
char name[20];
float marks;
};
Nested Structure
A nested structure is a structure that contains another structure as its member. That is, one structure is defined or declared inside another structure.
Syntax:
struct Inner {
data_type member1;
};
struct Outer {
data_type member;
struct Inner obj; /* nested structure member */
};
Example:
struct Date {
int day;
int month;
int year;
};
struct Student {
int roll;
char name[20];
struct Date dob; /* nested structure */
};
Here, struct Date is nested inside struct Student. The member dob is accessed as s.dob.day, s.dob.month, etc.
(b) Program
Problem Analysis
- Read
nfrom the user inmain(). - Call function
fibonacci(n)to find the nth term of the Fibonacci series. - Call function
isPrime(num)to check whether that term is prime or not. - Display the result in
main().
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, ... The 1st term = 0, 2nd term = 1, 3rd term = 1, and so on.
Complete Program
#include <stdio.h>
#include <conio.h>
/* Function to generate the nth term of Fibonacci series */
int fibonacci(int n)
{
int first = 0, second = 1, next, i;
if (n == 1)
return 0;
if (n == 2)
return 1;
for (i = 3; i <= n; i++)
{
next = first + second;
first = second;
second = next;
}
return next;
}
/* Function to check whether a number is prime or not */
/* Returns 1 if prime, 0 if not prime */
int isPrime(int num)
{
int i;
if (num <= 1)
return 0; /* 0 and 1 are not prime */
for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
return 0; /* divisible, so not prime */
}
return 1; /* prime */
}
/* Main function */
void main()
{
int n, term, result;
clrscr();
printf("Enter the value of n: ");
scanf("%d", &n);
/* Generate nth Fibonacci term */
term = fibonacci(n);
printf("\nThe %dth term of Fibonacci series is: %d\n", n, term);
/* Check if the term is prime */
result = isPrime(term);
if (result == 1)
printf("%d is a PRIME number.\n", term);
else
printf("%d is NOT a prime number.\n", term);
getch();
}
Sample Output
Enter the value of n: 7
The 7th term of Fibonacci series is: 8
8 is NOT a prime number.
Enter the value of n: 5
The 5th term of Fibonacci series is: 3
3 is a PRIME number.
Fibonacci Series Reference Table
| n | Fibonacci Term |
|---|---|
| 1 | 0 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 3 |
| 6 | 5 |
| 7 | 8 |
| 8 | 13 |
Key Points
| Function | Purpose | Return Type |
|---|---|---|
fibonacci(n) | Returns the nth Fibonacci term | int |
isPrime(num) | Returns 1 if prime, 0 if not | int |
main() | Reads input, calls both functions, displays result | void |
2080 · 5 marks
Write a program to compute the sum of first 10 even numbers using function. [5]
2078 · 5 marks
Write a program using your own function to find sum of two numbers. [5]
2077 · 5 marks
Write a program to find product of two integers using your own function. [5]
2074 · 5 marks
What is function? Discuss the benefits of using function. [1.5+3.5]
Show solved answerHide answer
Function in C Programming
What is a Function? [1.5 marks]
A function is a self-contained, named block of code that performs a specific task. It is written once and can be called (invoked) multiple times from anywhere in the program.
General Syntax:
return_type function_name(parameter_list)
{
// body of the function
return value;
}
Example:
int add(int a, int b)
{
return a + b;
}
A C program must have at least one function: int main(), which is the starting point of every C program.
Benefits of Using Functions [3.5 marks]
1. Reusability
A function is written once and can be called multiple times from different parts of the program. This avoids writing the same code repeatedly.
int square(int n) { return n * n; }
// Can be called as: square(3), square(5), square(10) ...
2. Modularity / Divide and Conquer
A large, complex program can be broken down into smaller, manageable, and independent modules (functions). Each function handles one specific task, making the overall program easier to design and understand.
3. Readability and Clarity
Programs written using functions are easier to read and understand. The main() function becomes shorter and cleaner because the detailed logic is moved into separate named functions.
4. Easy Debugging and Testing
Since each function performs a specific task, errors can be located and fixed more easily. Functions can be unit tested individually (tested separately) before being combined into the full program.
5. Reduced Program Length (Avoids Code Duplication)
Without functions, the same logic would need to be written multiple times. Functions reduce the total size of the program by replacing repeated code with a single function call.
6. Easy Maintenance
If a change is needed in a particular task, only the corresponding function needs to be modified. There is no need to search and change the same logic at multiple places throughout the program.
7. Abstraction
The user of a function does not need to know how it works internally. They only need to know what input to provide and what output to expect. This hides complexity and promotes abstraction.
Summary Table
| Benefit | Description |
|---|---|
| Reusability | Write once, use many times |
| Modularity | Breaks program into smaller parts |
| Readability | Makes code cleaner and easier to follow |
| Easy Debugging | Errors are isolated within individual functions |
| Reduced Code | Eliminates repetition |
| Easy Maintenance | Changes are made in one place only |
| Abstraction | Hides internal complexity from the caller |
Function Arguments and Return Types
2079 · 10 marks
Why do we need a break and continue statement? Define formal argument and actual argument in function with examples. Identify and list the errors in the following code.
int main() {
int a, b, c
scanf("%d%d%d, &a, &b, &c);
sum(a, b, c);
return -1;
}
void sum(int x, int y, int z) {
int sum;
sum = a + b + c;
return sum;
}
[10]
Make Unit 7 stick
Practice CSC115 with flashcards & quizzes