0% found this document useful (0 votes)
2 views

Unit V

The document provides an 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 the differences between actual and formal parameters, types of functions, parameter passing techniques, and the scope of variables. Additionally, it discusses storage classes in C and introduces file handling operations such as creating, opening, reading, writing, and closing files.

Uploaded by

loknath4007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit V

The document provides an 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 the differences between actual and formal parameters, types of functions, parameter passing techniques, and the scope of variables. Additionally, it discusses storage classes in C and introduces file handling operations such as creating, opening, reading, writing, and closing files.

Uploaded by

loknath4007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

66

Unit V

Functions & File Handling

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


➢ A function is a block of statements which perform specific task.
Every function in C has the following:
1. Function Declaration (Function Prototype)
2. Function Definition
3. Function Call
1. Function Declaration (Function Prototype):
➢ The function declaration tells the compiler about function name, the data type of the return value and
parameters. The function declaration is also called a function prototype.
➢ The function declaration is performed before the main function or inside the main function or any other
function.
Syntax:
Return_Type function_Name(parameters_List);
Example:
void add( int , int );
2. Function Definition:
The function definition is also known as the body of the function.
Syntax
Return_Type function_Name(parameters_List)
{
Actual code...
}
In the above syntax,
Return_Type specifies the value return by a function
function_Name is a user-defined name used to identify the function uniquely
parameters_List is the data values that are sent to the function definition
Example:
void add(int a, int b)
{
printf(“Addition of a and b = %d”, a+b);
}
In this example,
The function name is add, it is taking two integer variables as parameters and it is not returning any value.
67

3. Function Call:
➢ The function call tells the compiler when to execute the function definition. When a function call is executed,
the execution control jumps to the function definition where the actual code gets executed and returns to
the same functions call once the execution completes.
➢ The function call is performed inside the main function or any other function or inside the function itself.
Syntax
functionName(parameters);
Example:
add(15, 20);
Q 2. define parameter. What are its types.
➢ Parameters are the data values that are passed from calling function to called function.
➢ 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 function.
➢ The formal parameters are the parameters that are declared at called function.
➢ When a function 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 functions? Explain.


Bases on function definition, functions are divided into two types:
1. Pre-Defined Functions
2. User Defined Functions
1. Pre-Defined Functions:
➢ The function whose definition is defined by the developers of language is called as system defined function.
➢ The pre-defined functions are also called as Library Functions or Standard Functions or system Functions.
➢ In C, all the system defined functions are defined inside the header files like stdio.h, conio.h, math.h, string.h,
stdlib,h etc.,
➢ For example, the funtions printf() and scanf() are defined in the header file called stdio.h
2. User Defined Functions:
➢ The function whose definition is defined by the user is called as user defined function.
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 addition() is user defined function.
Q 5. Explain different types of functions based on parameters and return values?
Based on parameters and return types, functions are classified into 4 types:
1. Function without parameters and without return values
2. Function with parameters and without return values
3. Function without parameters and with return values
4. Function with parameters and with return values
69

1. Function without parameters and without return values:


This type of functions 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. Function with parameters and without return values:


These types of functions 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. Function without parameters and with return values:


These types of functions 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. Function with parameters and with return values:
These types of functions 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 function to called function 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 function.
➢ 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 locations of the actual parameters in called function. 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 function in C
➢ In C programming, you can pass an entire array to functions.
➢ To pass array to a function, only the name of the array is passed to the function (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
Explanation:
To pass an entire array to a function, only the name of the array is passed as an argument.
result = calculateSum(num);
However, notice the use of [] in the function definition.
float calculateSum(float num[])
{
... ..
}
This informs the compiler that you are passing a one-dimensional array to the function.
Q 8. Explain Pass Multidimensional Arrays to a Function in C.
➢ To pass multidimensional arrays to a function, only the name of the array is passed to the function (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
Explanation:
➢ Note the parameter int num[2][2] in the function prototype and function definition:
// function prototype
void displayNumbers(int num[2][2]);
➢ This signifies that the function takes a two-dimensional array as an argument. We can also pass arrays with
more than 2 dimensions as a function 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 function is referred to as the scope of variable in C language.
➢ A variable, for example, may be accessed only within a single function/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 function.
➢ Local variables are created when the function has started execution and is lost when the function terminates.
➢ If a value of local variable is updated, it will effect within that function 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 function.
➢ Global variable is created as execution starts and is lost when the program ends.
➢ If a value of global variable updated, it will effect on entire 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 function and control is transfers from called to calling
function.
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 location (whether RAM or Register), scope, lifetime 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. static 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 function) is auto storage
class.
➔ Variable of auto storage class has the following properties:
77

2. static storage class:

➔ The static storage class is used to create variables that hold value beyond its scope until the end of the
program.
➔ The static variable allows to initialize only once and can be modified any number of times.
➔ Variable of static storage class has the following properties:
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 properties:
79

4. extern storage class:

➔ The default storage class of all global varibles (variables declared outside function) is external storage class.
➔ Variable of external storage class has the following properties:
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 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.

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

➔ The operations 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 software industry, most programs are written to
store the information fetched from the program.
➔ The use of file handling is exactly what the situation 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 anytime 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 instructions which saves a lot of time 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 written 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 Operations in C.

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

➔ Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
➔ Opening an existing file – fopen()
➔ Reading from file – fscanf() or fgets()
➔ Writing to a file – fprintf() or fputs()
➔ Moving to a specific location 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 particular position in the opened file. It is used in file handling to perform all file
operations 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 operations in C.

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

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);

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 operation 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 operations on the file to be opened. They are passed as an
argument to the fopen() function. 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 functions in C language .

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

S.No. Function Description

1 fopen() opens new or existing file

2 fprintf() 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 position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

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

You might also like