7 Functions

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.

Functions: notes

Library Functions

A library function is a ready-made function supplied with the C compiler; its source code is not given to the programmer, only its precompiled object code, which the linker adds to the program wherever it is called. Different groups of library functions are collected into separate header files: printf() and scanf() come from stdio.h, strlen() and strupr() from string.h, and pow() and sqrt() from math.h. To use a library function correctly, the programmer only needs to know its name and purpose, the number and type of arguments it takes, the type of value it returns, and which header file declares it. A programmer may even define a function with the same name as a library function; the programmer's own definition then takes precedence over the library one.

User Defined Functions

A user defined function is written by the programmer to carry out one specific, well-defined task of the program. Breaking a program into functions gives several advantages: it increases reusability, since the same code is not rewritten in several places; it lets different parts of a large program be developed independently; it makes development faster and debugging easier, since a fault can be isolated to one function; it reduces overall complexity; and it makes recursion possible, since only a function can call itself. Using a user defined function correctly requires three related pieces: its definition, its declaration (or prototype), and the call that invokes it.

Function Prototype, Function Call, and Function Definition

The function definition contains the complete code of the function: a header line followed by a body in braces.

return_type func_name(type1 arg1, type2 arg2, ...) {
    /* local declarations and statements */
    return expression;   /* omitted if return_type is void */
}

return_type is the type of value the function sends back (assumed int if omitted, or void if the function returns nothing), and the parameters listed in parentheses are the function's formal arguments. The function declaration, or prototype, tells the compiler the function's name, the number and type of its arguments, and its return type, before the function is actually defined or called, for example int sum(int, int);; it is only needed when the call appears before the definition in the file. The function call invokes the function by writing its name followed by the actual argument list, sum(a, b);, at which point control passes to the called function and returns to the statement following the call once the function finishes, either by reaching its closing brace or by executing a return statement.

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 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 FunctionUser 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

StepStatementWhat Happens
1swap(&x, &y)Addresses of x and y are passed to the function
2int *a, int *bPointer a holds address of x; pointer b holds address of y
3temp = *atemp gets the value stored at address a (i.e., value of x)
4*a = *bValue at address a (i.e., x) is replaced by value at address b (i.e., y)
5*b = tempValue 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.

Open this answer on its own page →

Nested and Recursive Function

2081 · 5 marks

Demonstrate the use of recursive function with a suitable example. [5]

A recursive function is a function that calls itself during its own execution. Each recursive call works on a smaller version of the problem until a base condition (terminating condition) is reached, which stops further recursion. --- Component Description ------ Base Case The condition that stop...

Open this answer on its own page →

2080 · 5 marks

Write a program to calculate the factorial of a given number using recursion. [5]

A recursive function is a function that calls itself. It must have: 1. Base condition (stopping condition) -- when n == 0, return 1 2. Recursive call -- each call must move closer to the base condition $$n! = \begin{cases} 1 & \text{if } n = 0 \ n \times (n-1)! & \text{if } n 0 \end{cases}$$ ---...

Open this answer on its own page →

2079 · 5 marks

Write a program to find the sum of digits of a given integer using recursion. [5]

The sum of digits of a number can be found recursively by: - Base case: If the number is 0, return 0 - Recursive case: Return (number % 10) + sumOfDigits(number / 10) For example, for n = 123: - 123 % 10 = 3, then call sumOfDigits(12) - 12 % 10 = 2, then call sumOfDigits(1) - 1 % 10 = 1, then cal...

Open this answer on its own page →

Local and Global Variable

2081 · 5 marks

Write short notes on: a) Global variable b) Debugging Debugging [2.5+2.5]

--- Definition: Global variables are variables that are defined outside any function in a C program. Since they are declared outside all functions, they are accessible and can be modified by all functions in the program. Key Characteristics: - Declared outside any function (usually at the top of ...

Open this answer on its own page →

2079 · 5 marks

Write short notes on: a. Local, Global, and Static variables b. Conditional Operator [5]

--- Variables that are defined within the body of a function or a block are called local variables. Key characteristics: - Can be used only within the function or block in which they are declared - They are not accessible outside that function/block - The same variable name may be used in differe...

Open this answer on its own page →

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 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 n from the user in main().
  • 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

nFibonacci Term
10
21
31
42
53
65
78
813

Key Points

FunctionPurposeReturn Type
fibonacci(n)Returns the nth Fibonacci termint
isPrime(num)Returns 1 if prime, 0 if notint
main()Reads input, calls both functions, displays resultvoid
Open this answer on its own page →

2080 · 5 marks

Write a program to compute the sum of first 10 even numbers using function. [5]

The first 10 even numbers are: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20. A separate function evenSum() is defined to compute and return their sum, which is then called from main(). --- --- Iteration i sum (before) sum (after) count ------------------------------------------------ 1 2 0 2 1 2 4 2 6 2 3 ...

Open this answer on its own page →

2078 · 5 marks

Write a program using your own function to find sum of two numbers. [5]

A user-defined function is a function created by the programmer to perform a specific task. Here, we define a separate function sum() that takes two numbers as parameters, adds them, and returns the result to main(). --- --- --- Part Description ------ int sum(int a, int b) User-defined function ...

Open this answer on its own page →

2077 · 5 marks

Write a program to find product of two integers using your own function. [5]

A user-defined function is a function created by the programmer to perform a specific task. Here, we create a separate function called product() that takes two integers as parameters and returns their product. --- --- --- Part Description ------ int product(int a, int b) User-defined function tha...

Open this answer on its own page →

2074 · 5 marks

What is function? Discuss the benefits of using function. [1.5+3.5]

Show solved 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

BenefitDescription
ReusabilityWrite once, use many times
ModularityBreaks program into smaller parts
ReadabilityMakes code cleaner and easier to follow
Easy DebuggingErrors are isolated within individual functions
Reduced CodeEliminates repetition
Easy MaintenanceChanges are made in one place only
AbstractionHides internal complexity from the caller
Open this answer on its own page →

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]

--- The break statement is used to immediately exit from a loop (for, while, do-while) or a switch statement before its normal termination condition is reached. Without break, a loop would continue executing even when a desired condition has been met, wasting processing time or producing incorrec...

Open this answer on its own page →