0% found this document useful (0 votes)
7 views22 pages

Unit-5 (Functions & File Handling) - 2-23

Unit 5 covers functions and file handling in C programming, detailing function declaration, definition, and calling, as well as parameter passing methods. It explains the differences between library functions and user-defined functions, and illustrates how to pass arrays and pointers to functions. Additionally, it discusses variable scope and lifetime, emphasizing the importance of understanding global and local scope in C.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views22 pages

Unit-5 (Functions & File Handling) - 2-23

Unit 5 covers functions and file handling in C programming, detailing function declaration, definition, and calling, as well as parameter passing methods. It explains the differences between library functions and user-defined functions, and illustrates how to pass arrays and pointers to functions. Additionally, it discusses variable scope and lifetime, emphasizing the importance of understanding global and local scope in C.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

lOMoAR cPSD| 43161045

UNIT 5
FUNCTIONS & FILE HANDLING
Introduction to Functions, Function declaration and definition, Function call return
types and arguments, modifying parameters inside functions using pointers, array
as parameters, Scope and lifetime of variables, basics of File handling

A function in C is a set of statements that when called perform some specific


task. It is the basic building block of a C program that provides modularity and
code reusability. The programming statements of a function are enclosed within {
} braces, having certain meanings and performing certain operations. They are
also called subroutines or procedures in other languages.

Syntax of Functions in C
The syntax of function can be divided into 3 aspects:
1. Function Declaration
2. Function Definition
3. Function Calls

Function Declarations
In a function declaration, we must provide the function name, its return type, and
the number and type of its parameters. A function declaration tells the compiler
that there is a function with the given name defined somewhere else in the
program.

Syntax

return_type name_of_the_function (parameter_1, parameter_2);

The parameter name is not mandatory while declaring functions. We can also
declare the function without using the name of the data variables.

Example

int sum(int a, int b);


int sum(int , int);
lOMoAR cPSD| 43161045

Note: A function in C must always be declared globally before calling it.

Function Definition
The function definition consists of actual statements which are executed when the
function is called (i.e. when the program control comes to the function).
A C function is generally defined and declared in a single step because the
function definition always starts with the function declaration so we do not need
to declare it explicitly. The below example serves as both a function definition
and a declaration.

return_type function_name (para1_type para1_name, para2_type para2_name)


{
// body of the function
}
lOMoAR cPSD| 43161045

Function Call
A function call is a statement that instructs the compiler to execute the function.
We use the function name and parameters in the function call.
In the below example, the first sum function is called and 10,30 are passed to the
sum function. After the function call sum of a and b is returned and control is also
returned back to the main function of the program.

Note: Function call is neccessary to bring the program control to the function
definition. If not called, the function statements will not be executed.

Example of C Function

// C program to show function


// call and definition
#include <stdio.h>

// Function that takes two parameters


// a and b as inputs and returns
// their sum
int sum(int a, int b)
{
lOMoAR cPSD| 43161045

return a + b;
}

// Driver code
int main()
{
// Calling sum function and
// storing its value in add variable
int add = sum(10, 30);

printf("Sum is: %d", add);


return 0;
}

Output
Sum is: 40

Function Return Type

Function return type tells what type of value is returned after all function is
executed. When we don’t want to return a value, we can use the void data type.
Example:
int func(parameter_1,parameter_2);
The above function will return an integer value after running statements inside
the function.

Function Arguments

Function Arguments (also known as Function Parameters) are the data that is
passed to a function.
Example:
int function_name(int var1, int var2);
Conditions of Return Types and Arguments
In C programming language, functions can be called either with or without
arguments and might return values. They may or might not return values to the
calling functions.
lOMoAR cPSD| 43161045

1. Function with no arguments and no return value


2. Function with no arguments and with return value
3. Function with argument and with no return value
4. Function with arguments and with return value

Types of Functions
There are two types of functions in C:
1. Library Functions
2. User Defined Functions

1. Library Function

A library function is also referred to as a “built-in function”. A compiler


package already exists that contains these functions, each of which has a specific
meaning and is included in the package. Built-in functions have the advantage of
being directly usable without being defined, whereas user-defined functions must
be declared and defined before being used.

For Example:
pow(), sqrt(), strcmp(), strcpy() etc.

Advantages of C library functions


• C Library functions are easy to use and optimized for better performance.
• C library functions save a lot of time i.e, function development time.
• C library functions are convenient as they always work.

Example:
// C program to implement
// the above approach
#include <math.h>
lOMoAR cPSD| 43161045

#include <stdio.h>

// Driver code
int main()
{
double Number;
Number = 49;

// Computing the square root with


// the help of predefined C
// library function
double squareRoot = sqrt(Number);

printf("The Square root of %.2lf = %.2lf",


Number, squareRoot);
return 0;
}

Output
The Square root of 49.00 = 7.00

2. User Defined Function

Functions that the programmer creates are known as User-Defined functions


or “tailor-made functions”. User-defined functions can be improved and
modified according to the need of the programmer. Whenever we write a function
that is case-specific and is not defined in any header file, we need to declare and
define our own functions according to the syntax.

Advantages of User-Defined Functions


• Changeable functions can be modified as per need.
• The Code of these functions is reusable in other programs.
• These functions are easy to understand, debug and maintain.

Example:

// C program to show
// user-defined functions
#include <stdio.h>
lOMoAR cPSD| 43161045

int sum(int a, int b)


{
return a + b;
}

// Driver code
int main()
{
int a = 30, b = 40;

// function call
int res = sum(a, b);

printf("Sum is: %d", res);


return 0;
}

Output
Sum is: 70
Passing Parameters to Functions
The data passed when the function is being invoked is known as the Actual
parameters. In the below program, 10 and 30 are known as actual parameters.
Formal Parameters are the variable and the data type as mentioned in the function
declaration. In the below program, a and b are known as formal parameters.
lOMoAR cPSD| 43161045

We can pass arguments to the C function in two ways:


1. Pass by Value
2. Pass by Reference

1. Pass by Value
Parameter passing in this method copies values from actual parameters into
formal function parameters. As a result, any changes made inside the functions do
not reflect in the caller’s parameters.
Example:
// C program to show use
// of call by value
#include <stdio.h>

void swap(int var1, int var2)


{
int temp = var1;
var1 = var2;
var2 = temp;
}

// Driver code
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\n",
var1, var2);
swap(var1, var2);
printf("After swap Value of var1 and var2 is: %d, %d",
var1, var2);
return 0;
}
Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 3, 2
2. Pass by Reference
The caller’s actual parameters and the function’s actual parameters refer to the
same locations, so any changes made inside the function are reflected in the
caller’s actual parameters.
lOMoAR cPSD| 43161045

Example:
// C program to show use of
// call by Reference
#include <stdio.h>

void swap(int *var1, int *var2)


{
int temp = *var1;
*var1 = *var2;
*var2 = temp;
}

// Driver code
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\n",
var1, var2);
swap(&var1, &var2);
printf("After swap Value of var1 and var2 is: %d, %d",
var1, var2);
return 0;
}
Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 2, 3
Passing Pointers to Functions in C

Passing the pointers to the function means the memory location of the variables is
passed to the parameters in the function, and then the operations are performed.
The function definition accepts these addresses using pointers, addresses are
stored using pointers.
Arguments Passing without pointer
When we pass arguments without pointers the changes made by the function
would be done to the local variables of the function.
Below is the C program to pass arguments to function without a pointer:
lOMoAR cPSD| 43161045

// C program to swap two values


// without passing pointer to
// swap function.
#include <stdio.h>

void swap(int a, int b)


{
int temp = a;
a = b;
b = temp;
}

// Driver code
int main()
{
int a = 10, b = 20;
swap(a, b);
printf("Values after swap function are: %d, %d",
a, b);
return 0;
}

Output
Values after swap function are: 10, 20
Arguments Passing with pointers

A pointer to a function is passed in this example. As an argument, a pointer is


passed instead of a variable and its address is passed instead of its value. As a
result, any change made by the function using the pointer is permanently stored at
the address of the passed variable. In C, this is referred to as call by reference.
Below is the C program to pass arguments to function with pointers:
// C program to swap two values
// without passing pointer to
// swap function.
#include <stdio.h>

void swap(int* a, int* b)


{
lOMoAR cPSD| 43161045

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

// Driver code
int main()
{
int a = 10, b = 20;
printf("Values before swap function are: %d, %d\n",
a, b);
swap(&a, &b);
printf("Values after swap function are: %d, %d",
a, b);
return 0;
}

Output
Values before swap function are: 10, 20
Values after swap function are: 20, 10
Pass Array to Functions in C

Arrays in C are always passed to the function as pointers pointing to the first
element of the array.
Syntax
In C, we have three ways to pass an array as a parameter to the function. In the
function definition, use the following syntax:
return_type foo ( array_type array_name[size], ...);
Mentioning the size of the array is optional. So the syntax can be written as:
return_type foo ( array_type array_name[], ...);
In both of the above syntax, even though we are defining the argument as array it
will still be passed as a pointer. So we can also write the syntax as:
return_type foo ( array_type* array_name, ...);
lOMoAR cPSD| 43161045

Examples of Passing Array to Function in C

Example 1: Checking Size After Passing Array as Parameter

// C program to pass the array as a function and check its size


#include <stdio.h>
#include <stdlib.h>

// Note that arr[] for fun is just a pointer even if square


// brackets are used. It is same as
// void fun(int *arr) or void fun(int arr[size])
void func(int arr[8])
{
printf("Size of arr[] in func(): %d bytes",
sizeof(arr));
}

// Drive code
int main()
{
lOMoAR cPSD| 43161045

int arr[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };

printf("Size of arr[] in main(): %dbytes\n",


sizeof(arr));

func(arr);

return 0;
}
Output
Size of arr[] in main(): 32bytes
Size of arr[] in func(): 8 bytes
As we can see,
• The size of the arr[] in the main() function (where arr[] is declared) is 32 bytes
which is = sizeof(int) * 8 = 4 * 8 = 32 bytes.
• But in the function where the arr[] is passed as a parameter, the size of arr[] is
shown as 8 bytes (which is the size of a pointer in C).
It is due to the fact that the array decays into a pointer after being passed as a
parameter. One way to deal with this problem is to pass the size of the array as
another parameter to the function. This is demonstrated in the below example.

Example 2: Printing Array from the Function

// C program to illustrate the use of sizeof operator in C


#include <stdio.h>

// function to print array


void printArray(int arr[], int size)
{
printf("Array Elements: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}

// driver code
int main()
{
lOMoAR cPSD| 43161045

int arr[8] = { 12, 4, 5, 3, 7, 8, 11, 45 };

// getting the size of array


int size = sizeof(arr) / sizeof(arr[0]);

printArray(arr, size);

return 0;
}
Output
Array Elements: 12 4 5 3 7 8 11 45
This size parameter may not be needed only in the case of ‘\0’ terminated
character arrays as size can be determined by checking the end of the string
character. The below example demonstrates the following.
Example 3: Printing Array of Characters (String) using Function
// C Program to print the string using a function
#include <stdio.h>

// function to print the string


void printString(char* str)
{
printf("Array of Characters: ");

int i = 0;
while (str[i] != '\0') {
printf("%c ", str[i]);
i++;
}
}

// Driver program
int main()
{
char arr[] = "String";

printString(arr);

return 0;
}
lOMoAR cPSD| 43161045

Output
Array of Characters: S t r i n g

Scope rules in C

The scope of a variable in C is the block or the region in the program where a
variable is declared, defined, and used. Outside this region, we cannot access the
variable and it is treated as an undeclared identifier.
• The scope is the area under which a variable is visible.
• The scope of an identifier is the part of the program where the identifier may
directly be accessible.
• We can only refer to a variable in its scope.
• In C, all identifiers are lexically(or statically) scoped.
// C program to illustrate the scope of a variable
#include <stdio.h>

int main()
{
// Scope of this variable is within main() function
// only.
int var = 34;

printf("%d", var);
return 0;
}

// function where we try to access the var defined in main()


void func() { printf("%d", var); }

Output
solution.c: In function 'func':
solution.[Link] error: 'var' undeclared (first use in this function)
void func() { printf("%d", var); }
Here, we tried to access variable names var As we can see that if we try to refer
to the variable outside its scope, we get the above error.
lOMoAR cPSD| 43161045

Types of Scope Rules in C

C scope rules can be covered under the following two categories:


1. Global Scope
2. Local Scope
Let’s discuss each scope rule with examples.
1. Global Scope in C
The global scope refers to the region outside any block or function.
• The variables declared in the global scope are called global variables.
• Global variables are visible in every part of the program.
• Global is also called File Scope as the scope of an identifier starts at the
beginning of the file and ends at the end of the file.
Example
// C program to illustrate the global scope
#include <stdio.h>

// variable declared in global scope


int global = 5;

// global variable accessed from


// within a function
void display()
{
printf("%d\n", global);
}

// main function
int main()
{
printf("Before change within main: ");
display();

// changing value of global


// variable from main function
printf("After change within main: ");
global = 10;
display();
}
lOMoAR cPSD| 43161045

Output
Before change within main: 5
After change within main: 10
2. Local Scope in C
The local scope refers to the region inside a block or a function. It is the space
enclosed between the { } braces.
• The variables declared within the local scope are called local variables.
• Local variables are visible in the block they are declared in and other blocks
nested inside that block.
• Local scope is also called Block scope.
• Local variables have internal linkage.

Example

// C program to illustrate the local scope


#include <stdio.h>

// Driver Code
int main()
{
{
int x = 10, y = 20;
{
// The outer block contains
// declaration of x and
// y, so following statement
// is valid and prints
// 10 and 20
printf("x = %d, y = %d\n", x, y);
{
// y is declared again,
// so outer block y is
// not accessible in this block
int y = 40;

// Changes the outer block


// variable x to 11
x++;
lOMoAR cPSD| 43161045

// Changes this block's


// variable y to 41
y++;

printf("x = %d, y = %d\n", x, y);


}

// This statement accesses


// only outer block's
// variables
printf("x = %d, y = %d\n", x, y);
}
}
return 0;
}
Output
x = 10, y = 20
x = 11, y = 41
x = 11, y = 20
Basics of File Handling in C

File handing in C is the process in which we create, open, read, write, and close
operations on a file. C language provides different functions such as fopen(),
fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many
different C file operations in our program.

Types of Files in C
A file can be classified into two types based on the way the file stores the data.
They are as follows:
• Text Files
• Binary Files
lOMoAR cPSD| 43161045

1. Text Files
A text file contains data in the form of ASCII characters and is generally used
to store a stream of characters.
• Each line in a text file ends with a new line character (‘\n’).
• It can be read or written by any text editor.
• They are generally stored with .txt file extension.
• Text files can also be used to store the source code.

2. Binary Files
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII
characters. They contain data that is stored in a similar manner to how it is stored
in the main memory.
• The binary files can be created only from within a program and their contents
can only be read by a program.
• More secure as they are not easily readable.
• They are generally stored with .bin file extension.

C File Operations
C file operations refer to the different possible operations that we can perform on
a file in C such as:
1. Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
2. Opening an existing file – fopen()
3. Reading from file – fscanf() or fgets()
4. Writing to a file – fprintf() or fputs()
5. Moving to a specific location in a file – fseek(), rewind()
6. Closing a file – fclose()

Functions for C File Operations


lOMoAR cPSD| 43161045

Open a File in C
For opening a file in C, the fopen() function is used with the filename or file path
along with the required access modes.

Syntax of fopen()

FILE* fopen(const char *file_name, const char *access_mode);

Reading From a File


The file read operation in C can be performed using functions fscanf() or fgets().
Both the functions performed the same operations as that of scanf and gets but
lOMoAR cPSD| 43161045

with an additional parameter, the file pointer. There are also other functions we
can use to read from a file. Such functions are listed below:
Function Description

Use formatted string and variable arguments list to take input from a
fscanf()
file.

fgets() Input the whole line from the file.

fgetc() Reads a single character from the file.

fgetw() Reads a number from a file.

fread() Reads the specified bytes of data from a binary file.

Write to a File
The file write operations can be performed by the functions fprintf() and fputs()
with similarities to read operations. C programming also provides some other
functions that can be used to write data to a file such as:
Function Description

Similar to printf(), this function use formatted string and varible


fprintf()
arguments list to print output to the file.

fputs() Prints the whole line in the file and a newline at the end.

fputc() Prints a single character into the file.

fputw() Prints a number to the file.

fwrite() This functions write the specified amount of bytes to the binary file.

Read and Write in a Binary File


Till now, we have only discussed text file operations. The operations on a binary
file are similar to text file operations with little difference.
lOMoAR cPSD| 43161045

Opening a Binary File


To open a file in binary mode, we use the rb, rb+, ab, ab+, wb, and wb+ access
mode in the fopen() function. We also use the .bin file extension in the binary
filename.
Example
fptr = fopen("[Link]", "rb");

Write to a Binary File


We use fwrite() function to write data to a binary file. The data is written to the
binary file in the from of bits (0’s and 1’s).
Syntax of fwrite()
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *file_pointer);

Parameters:
• ptr: pointer to the block of memory to be written.
• size: size of each element to be written (in bytes).
• nmemb: number of elements.
• file_pointer: FILE pointer to the output file stream.
Return Value:
• Number of objects written.

You might also like