0% found this document useful (0 votes)
29 views19 pages

C Functions and File Handling Guide

The document provides a comprehensive overview of functions and file handling in C programming, detailing how to define, declare, and call functions, as well as explaining parameters and their types. It also covers different types of functions based on definitions, parameters, and return values, alongside parameter passing techniques such as call by value and call by reference. Additionally, the document discusses the scope of variables, local and global variables, the return statement, and storage classes in C.

Uploaded by

abrarhabib75
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)
29 views19 pages

C Functions and File Handling Guide

The document provides a comprehensive overview of functions and file handling in C programming, detailing how to define, declare, and call functions, as well as explaining parameters and their types. It also covers different types of functions based on definitions, parameters, and return values, alongside parameter passing techniques such as call by value and call by reference. Additionally, the document discusses the scope of variables, local and global variables, the return statement, and storage classes in C.

Uploaded by

abrarhabib75
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

66

Unit V

Func ons & File Handling

Q 1. Define a func on. How to define and call a func on in C.


 A func on is a block of statements which perform specific task.
Every func on in C has the following:
1. Func on Declara on (Func on Prototype)
2. Func on Defini on
3. Func on Call
1. Func on Declara on (Func on Prototype):
 The func on declara on tells the compiler about func on name, the data type of the return value and
parameters. The func on declara on is also called a func on prototype.
 The func on declara on is performed before the main func on or inside the main func on or any other
func on.
Syntax:
Return_Type func on_Name(parameters_List);
Example:
void add( int , int );
2. Func on Defini on:
The func on defini on is also known as the body of the func on.
Syntax
Return_Type func on_Name(parameters_List)
{
Actual code...
}
In the above syntax,
Return_Type specifies the value return by a func on
func on_Name is a user-defined name used to iden fy the func on uniquely
parameters_List is the data values that are sent to the func on defini on
Example:
void add(int a, int b)
{
prin (“Addi on of a and b = %d”, a+b);
}
In this example,
The func on name is add, it is taking two integer variables as parameters and it is not returning any value.
67

3. Func on Call:
 The func on call tells the compiler when to execute the func on defini on. When a func on call is executed,
the execu on control jumps to the func on defini on where the actual code gets executed and returns to
the same func ons call once the execu on completes.
 The func on call is performed inside the main func on or any other func on or inside the func on itself.
Syntax
func onName(parameters);
Example:
add(15, 20);
Q 2. define parameter. What are its types.
 Parameters are the data values that are passed from calling func on to called func on.
 Parameters are also called as arguments.
 In C, there are two types of parameters and they are as follows...
o Actual Parameter
o Formal Parameters
 The actual parameters are the parameters that are specified in calling func on.
 The formal parameters are the parameters that are declared at called func on.
 When a func on gets executed, the copy of actual parameter values are copied into formal parameters.

Q 3. Write the differences between actual parameters and formal parameters.


68

Q 4. What are the different types of func ons? Explain.


Bases on func on defini on, func ons are divided into two types:
1. Pre-Defined Func ons
2. User Defined Func ons
1. Pre-Defined Func ons:
 The func on whose defini on is defined by the developers of language is called as system defined func on.
 The pre-defined func ons are also called as Library Func ons or Standard Func ons or system Func ons.
 In C, all the system defined func ons are defined inside the header files like stdio.h, conio.h, math.h, string.h,
stdlib,h etc.,
 For example, the fun ons prin () and scanf() are defined in the header file called stdio.h
2. User Defined Func ons:
 The func on whose defini on is defined by the user is called as user defined func on.
Example Program:

#include<stdio.h>
int addition(int,int) ; // function declaration
int main()
{
int num1, num2,
result ;
printf("Enter any two integer numbers : ");
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("SUM = %d", result);
return 0;
}
int addition(int a, int b) // function definition
{
return a + b ;
}
Output:
Enter any two integer numbers : 23 54
SUM = 77
In the above example addi on() is user defined func on.
Q 5. Explain different types of func ons based on parameters and return values?
Based on parameters and return types, func ons are classified into 4 types:
1. Func on without parameters and without return values
2. Func on with parameters and without return values
3. Func on without parameters and with return values
4. Func on with parameters and with return values
69

1. Func on without parameters and without return values:


This type of func ons doesn’t contain parameters and return values.
Example Program
#include<stdio.h>
void addition() ; // function declaration
int main()
{
addition() ; // function call
}
void addition() // function definition
{
int num1, num2;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
printf("Sum = %d", num1+num2 );
}
Output:
Enter any two integer numbers : 20 30
Sum = 50

2. Func on with parameters and without return values:


These types of func ons having the parameters and doesn’t have the return values.

Example Program

#include<stdio.h>
void addition(int, int) ; // function declaration
int main()
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
addition(num1, num2) ; // function call
return 0;
}
void addition(int a, int b) // function definition
{
printf("Sum = %d", a+b ) ;
}
Output:
Enter any two integer numbers : 20 30
Sum = 50
70

3. Func on without parameters and with return values:


These types of func ons doesn’t have any parameters and contains return values.
Example Program

#include<stdio.h>
int addition() ; // function declaration
int main()
{
int result ;
result = addition() ; // function call
printf("Sum = %d", result) ;
return 0;
}
int addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
return (num1+num2) ;
}
Output:
Enter any two integer numbers : 20 30
Sum = 50
4. Func on with parameters and with return values:
These types of func ons contain both parameters and return values.
Example Program

#include<stdio.h>
int main()
{
int num1, num2, result ;
int addition(int, int) ; // function declaration
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("Sum = %d", result) ;
return 0;
}
int addition(int a, int b) // function definition
{
return (a+b) ;
}
Output:
Enter any two integer numbers : 20 30
Sum = 50
71

Q 6. Explain in detail about parameter passing techniques.


(Or)
Explain call by value and call by reference with example.
There are two methods to pass parameters from calling func on to called func on and they are:
1. Call by Value
2. Call by Reference
1. Call by Value
 In call by value parameter passing method, the copy of actual parameter values are copied to formal
parameters and these formal parameters are used in called func on.
 The changes made on the formal parameters does not affect the values of actual parameters.
Example Program
#include<stdio.h>
void swap(int,int) ; // function declaration
int main()
{
int num1, num2 ;
printf("Enter two numbers: ");
scanf("%d%d",&num1,&num2);
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(num1, num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
return 0;
}
void swap(int a, int b) // called function
{
int temp ;
temp = a ;
a = b ;
b = temp ;
}
Output:
Enter two numbers: 10 20
Before swap: num1 = 10, num2 = 20
After swap: num1 = 10, num2 = 20
2. Call by reference:
 In Call by Reference parameter passing method, the memory address of the actual parameters is copied to
formal parameters.
 This address is used to access the memory loca ons of the actual parameters in called func on. In this
method, the formal parameters must be pointer variables.
 Any changes made on the formal parameters effects the values of actual parameters.
72

Example Program

#include<stdio.h>
void swap(int*, int*) ; // function declaration
int main()
{
int num1, num2 ;
printf("Enter two numbers: ");
scanf("%d%d",&num1,&num2);
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
return 0;
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}
Output:
Enter two numbers: 10 20
Before swap: num1 = 10, num2 = 20
After swap: num1 = 20, num2 = 10
Q 7 Explain the Pass arrays to a func on in C
 In C programming, you can pass an en re array to func ons.
 To pass array to a func on, only the name of the array is passed to the func on (similar to one-dimensional
arrays).
Example Program:
// Program to calculate the sum of array elements by passing to a function
#include <stdio.h>
float calculateSum(float num[]);
int main()
{
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
// num array is passed to calculateSum()
result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float num[]) {
float sum = 0.0;
for (int i = 0; i < 6; ++i) {
73

sum += num[i];
}
return sum;
}
Output:
Result = 162.50
Explana on:
To pass an en re array to a func on, only the name of the array is passed as an argument.
result = calculateSum(num);
However, no ce the use of [] in the func on defini on.
float calculateSum(float num[])
{
... ..
}
This informs the compiler that you are passing a one-dimensional array to the func on.
Q 8. Explain Pass Mul dimensional Arrays to a Func on in C.
 To pass mul dimensional arrays to a func on, only the name of the array is passed to the func on (similar to
one-dimensional arrays).
Example Program:
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main() {
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
scanf("%d", &num[i][j]);
}
}
// pass multi-dimensional array to a function
displayNumbers(num);
return 0;
}
void displayNumbers(int num[2][2]) {
printf("Displaying:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
printf("%d\n", num[i][j]);
}
}
}
74

Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5
Explana on:
 Note the parameter int num[2][2] in the func on prototype and func on defini on:
// func on prototype
void displayNumbers(int num[2][2]);
 This signifies that the func on takes a two-dimensional array as an argument. We can also pass arrays with
more than 2 dimensions as a func on argument.
 When passing two-dimensional arrays, it is not mandatory to specify the number of rows in the array.
However, the number of columns should always be specified.
For example,
void displayNumbers(int num[][2])
{
// code
}
Q 9. Explain the Scope of Variables in C?
 The availability of a variable in a program or func on is referred to as the scope of variable in C language.
 A variable, for example, may be accessed only within a single func on/block of code (your apartment key) or
throughout the whole C program (the shared access key).
 We can associate the room keys with the local variables in C language because they only work in that single
room. The term global variables refers to variables (keys) that are accessible to the whole program
(apartment complex).
Q 10. Define local and global variables.
Local Variable:
 Local variable is declared inside a func on.
 Local variables are created when the func on has started execu on and is lost when the func on terminates.
 If a value of local variable is updated, it will effect within that func on only.
Example:
#include <stdio.h>
int main()
{
int x = 30;
75

printf("\nValue of x is %d\n", x);


{
int x = 20;
printf("\n\tValue of x is %d\n", x);
{
int x = 10;
printf("\n\t\tValue of x is %d\n\n", x);
}
}
return 0;
}
Output:
Value of x is 30
Value of x is 20
Value of x is 10
Global Variable:
 Global variable is declared outside the func on.
 Global variable is created as execu on starts and is lost when the program ends.
 If a value of global variable updated, it will effect on en re program.
Example:
#include <stdio.h>
int x=300;
int main()
{
printf("\nValue of x is %d\n", x);
{
int x = 20;
printf("\n\tValue of x is %d\n", x);
{
printf("\n\t\tValue of x is %d\n\n", x);
}
}
return 0;
}
Output:
Value of x is 300
Value of x is 20
Value of x is 20
Q 11. Write short note on return statement.
 return statement will return a value to the calling func on and control is transfers from called to calling
func on.
Syntax:
return <value>;
Example:
return 0;
76

Q 12. Define storage class. What are the storage classes in C. Explain with example?
 Storage classes are used to define storage loca on (whether RAM or Register), scope, life me and the default
value of a variable.
 In C language, there are FOUR storage classes and they are as follows:
1. auto storage class
2. sta c storage class
3. register storage class
4. extern storage class
1. auto storage class:
 The default storage class of all local variables (variables declared inside block or func on) is auto storage
class.
 Variable of auto storage class has the following proper es:
77

2. sta c storage class:

 The sta c storage class is used to create variables that hold value beyond its scope un l the end of the
program.
 The sta c variable allows to ini alize only once and can be modified any number of mes.
 Variable of sta c storage class has the following proper es:
78

3. register storage class:

 The register storage class is used to specify the memory of the variable that has to be allocated in CPU
Registers.
 The register variables enable faster accessibility compared to other storage class variables.
 As the number of registers inside the CPU is very less we can use very less number of register variables.
 Variable of register storage class has the following proper es:
79

4. extern storage class:

 The default storage class of all global varibles (variables declared outside func on) is external storage class.
 Variable of external storage class has the following proper es:
80

Q 13 . Describe file handling in C language?

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

Q 14. Define Why do we need File Handling in C?

 The opera ons using the C program are done on a prompt/terminal which is not stored anywhere.
 The output is deleted when the program is closed. But in the so ware industry, most programs are wri en to
store the informa on fetched from the program.
 The use of file handling is exactly what the situa on calls for.
 In order to understand why file handling is important, a few features of using files:

Reusability: The data stored in the file can be accessed, updated, and deleted anywhere and any me providing high
reusability.

Portability: Without losing any data, files can be transferred to another in the computer system. The risk of flawed
coding is minimized with this feature.

Efficient: A large amount of input may be required for some programs. File handling allows you to easily access a part
of a file using few instruc ons which saves a lot of me and reduces the chance of errors.

Storage Capacity: Files allow you to store a large amount of data without having to worry about storing everything
simultaneously in a program.

Q 15. Explain different 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:

1. Text Files
2. Binary Files

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 wri en by any text editor.
 They are generally stored with .txt file extension.
 Text files can also be used to store the source code.
81

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.

Q 16. Explain File Opera ons in C.

The different possible opera ons that we can perform on a file in C such as:

 Crea ng a new file – fopen() with a ributes as “a” or “a+” or “w” or “w+”
 Opening an exis ng file – fopen()
 Reading from file – fscanf() or fgets()
 Wri ng to a file – fprin () or fputs()
 Moving to a specific loca on in a file – fseek(), rewind()
 Closing a file – fclose()
82

Q 17. Define a file pointer in C.

A file pointer is a reference to a par cular posi on in the opened file. It is used in file handling to perform all file
opera ons such as read, write, close, etc. We use the FILE macro to declare the file pointer variable. The FILE macro is
defined inside <stdio.h> header file.

Syntax of File Pointer

FILE* pointer_name;

File Pointer is used in almost all the file opera ons in C.

Q 18. Explain how to open a file and File opening modes in C language.

The fopen() func on 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);

Parameters

file_name: name of the file when present in the same directory as the source file. Otherwise, full path.

Access_mode: Specifies for what opera on the file is being opened.

Return Value

If the file is opened successfully, returns a file pointer to it.

If the file is not opened, then returns NULL.

File opening modes

File opening modes or access modes specify the allowed opera ons on the file to be opened. They are passed as an
argument to the fopen() func on. Some of the commonly used file access modes are listed below:

Opening
Modes Description

Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that
r
points to the first character in it. If the file cannot be opened fopen( ) returns NULL.

rb Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL.

Open for writing in text mode. If the file exists, its contents are overwritten. If the file doesn’t exist, a new
w
file is created. Returns NULL, if unable to open the file.

Open for writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it
wb
will be created.
83

Opening
Modes Description

Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that
a points to the last character in it. It opens only in the append mode. If the file doesn’t exist, a new file is
created. Returns NULL, if unable to open the file.

Open for append in binary mode. Data is added to the end of the file. If the file does not exist, it will be
ab
created.

Searches file. It is opened successfully fopen( ) loads it into memory and sets up a pointer that points to
r+
the first character in it. Returns NULL, if unable to open the file.

rb+ Open for both reading and writing in binary mode. If the file does not exist, fopen( ) returns NULL.

Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created.
w+
Returns NULL, if unable to open the file.

Open for both reading and writing in binary mode. If the file exists, its contents are overwritten. If the file
wb+
does not exist, it will be created.

Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that
a+ points to the last character in it. It opens the file in both reading and append mode. If the file doesn’t exist,
a new file is created. Returns NULL, if unable to open the file.

ab+ Open for both reading and appending in binary mode. If the file does not exist, it will be created.

Q 19. Explain briefly about file handling func ons in C language .

There are many func ons in the C library to open, read, write, search and close the file. A list of file func ons are
given

[Link]. Func on Descrip on

1 fopen() opens new or exis ng file

2 fprin () write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file


84

7 fseek() sets the file pointer to given posi on

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ell() returns current posi on

11 rewind() sets the file pointer to the beginning of the file

You might also like