0% found this document useful (0 votes)
8 views25 pages

C Functions and File Handling Basics

Uploaded by

svnsarma
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)
8 views25 pages

C Functions and File Handling Basics

Uploaded by

svnsarma
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

UNIT-5 : FUNCTIONS & FILE HANDLING

Definition: A function is a block of code/group of statements/self-contained block of statements/basic


building blocks in a program that performs a particular task. It is also known as procedure or subroutine or
module, in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity
and code reusability.

Advantage of functions

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and
again.

2) Code optimization

It makes the code optimized we don't need to write much code.

3) Easily to debug the program.

Example: Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not.
Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.
----------------------------------------------------------------------------------------------------------------------------- --
**Types of Functions
There are two types of functions in C programming:

1. Library Functions: These are already declared and defined. Ex : scanf(), printf(), gets(), puts(), ceil(),
floor() etc.
System defined functions are declared in header files and implemented in .dll files. (DLL stands for
Dynamic Link Library).
To use system defined functions the respective header file must be included. Ex: we write
#include<stdio.h> to use printf() and scanf() functions.

2. User-defined functions: These are created by the C programmer, so that he/she can use it many
times. It reduces complexity of a big program and optimizes the code. Depending upon the complexity
and requirement of the program, you can create as many user-defined functions as you want.

1
ELEMENTS ( Parts / Steps ) OF USER-DEFINED FUNCTIONS:

In order to write an efficient user defined function, the programmer must familiar with the following three
elements.

1 : Function Declaration. (Function Prototype).

2 : Function Call.

3 : Function Definition

1: Function Declaration. (Function Prototype).A function declaration is the process of tells the compiler
about Function Name, No. of parameters , Type of Parameters and Return type.

Syntax

return_type function_name(parameter/argument);

return_type function-name();

Ex : int add(int a,int b);

int add();

Note: At the time of function declaration function must be terminated with ;

2
[Link] Call /Calling a function
When we call any function control goes to function body and execute entire code.

Syntax : function-name();

function-name(parameter/argument);

return value/ variable = function-name(parameter/argument);

Ex : add(); // function without parameter/argument

add(a,b); // function with parameter/argument

c=fun(a,b); // function with parameter/argument and return values

Defining a function.

Defining of function is nothing but write logic or statements inside function body(block) .

Syntax

return_ type function-name(parameter list) // function header.

declaration of variables;

body of function; // Function body

return statement; (expression or value) //optional

}
Ex : int addNumbers(int a,int b) // function definition

int result;

result = a+b;

return result; // return statement

3
The execution of a C program begins from the main () function.

When the compiler encounters functionName(); inside the main function, control of the program jumps to
void functionName()

And, the compiler starts executing the codes inside the user-defined function.

The control of the program jumps to statement next to functionName(); once all the codes inside the
function definition are executed.
Example:

#include <stdio.h>

int addNumbers(int a, int b); // function prototype

4
int main()

int n1,n2,sum;

printf("Enter two numbers: ");

scanf("%d %d",&n1,&n2);

sum = addNumbers(n1, n2); // function call


printf("sum = %d",sum);

return 0;

int addNumbers(int a,int b) // function definition

int result;

result = a+b;

return result; // return statement

o/p : Enter two numbers 7 10


Sum = 17
--------------------------------------------------------------------------------------

PARAMETERS:

Parameters provides the data communication between the calling function and called function.

They are two types of parameters

1 : Actual parameters.

2 : Formal parameters.
1 : Actual Parameters : These are the parameters transferred from the calling function (main program) to
the called function (function).

2 : Formal Parameters :These are the parameters transferred into the calling function (main program) from
the called function(function).

The parameters specified in calling function are said to be Actual Parameters.

5
The parameters declared in called function are said to be Formal Parameters.

The value of actual parameters is always copied into formal parameters.

Ex :

main()

fun1( a , b ); //Calling function

fun1( x, y ) //called function

......

Where

a, b are the Actual Parameters

x, y are the Formal Parameters

---------------------------------------------------------------------------------------------

***Passing Parameter to Functions /Parameter passing Techniques /


Call by Value and Call by Reference(address)
There are two ways to pass value or data to

Function in C language: call by value and call by reference. Original value is not modified in call by value
but it is modified in call by reference.

6
The called function receives the information from the calling function through the parameters. The variables
used while invoking the calling function are called actual parameters and the variables used in the function
header of the called function are called formal parameters.

C provides two mechanisms to pass parameters to a function.

1 : Pass by value (OR) Call by value.

2 : Pass by reference (OR) Call by Reference.

1 : Pass by value (OR) Call by value :

When a function is called with actual parameters, the values of actual parameters are copied into formal
parameters. If the values of the formal parameters changes in the function, the values of the actual
parameters are not changed. This way of passing parameters is called pass by value or call by value.

Ex :

#include<stdio.h>

#include<conio.h>

void swap(int ,int );

void main()

int i,j;

printf("Enter i and j values:");

scanf("%d%d",&i,&j);

printf("Before swapping:%d%d\n",i,j);

swap(i,j); // call by reference

printf("After swapping:%d%d\n",i,j);

getch();

7
void swap(int a,int b)

int temp;

temp=a;

a=b;

b=temp;

Output

Enter i and j values: 10 20

Before swapping: 10 20

After swapping: 10 20

2: Pass by reference (OR) Call by Reference: In pass by reference, a function is called with
addresses of actual parameters. In the function header, the formal parameters receive the addresses of
actual parameters. Now the formal parameters do not contain values, instead they contain addresses. Any
variable if it contains an address, it is called a pointer variable. Using pointer variables, the values of the
actual parameters can be changed. This way of passing parameters is called call by reference or pass by
reference.

Ex :

#include<stdio.h>

#include<conio.h>

void swap(int *,int *);

void main()

int i,j;

printf("Enter i and j values:");

scanf("%d%d",&i,&j);

printf("Before swapping:%d%d\n",i,j);

8
swap(&i ,&j); // call by reference

printf("After swapping:%d%d\n",i,j);

void swap(int *a,int *b)

int temp;

temp=*a;

*a=*b;

*b=temp;

Output

Enter i and j values: 10 20

Before swapping: 10 20

After swapping: 20 10

-------------------------------------------------------------------------------------------------------------------------------------

9
**Passing Arrays as Function Arguments
If you want to pass a single-dimension array as an argument in a function, you would have to declare a
formal parameter in one of following three ways

Way-1

Formal parameters as a pointer

void myFunction(int *param)

Way-2

Formal parameters as a sized array

void myFunction(int param[10])

Way-3

Formal parameters as an unsized array

void myFunction(int param[])

10
Example

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

sum += num[i];

return sum;

Output

Result = 162.50

To pass an entire array to a function, only the name of the array is passed as an argument.

result = calculateSum(num);

--------------------------------------------------------------------------------------------------------------

11
***Storage Classes (Scope and Life Time of variables )
In C language, each variable has a storage class which is used to define scope and life time of a variable.

Storage: Any variable declared in a program can be stored either in memory or registers. Registers are
small amount of storage in CPU. The data stored in registers has fast access compared to data stored in
memory.

Storage class of a variable gives information about the location of the variable in which it is stored, initial
value of the variable, if storage class is not specified; scope of the variable; life of the variable.

There are four storage classes in C programming.

1 : Automatic Storage class.

2 : Register Storage class.

3 : Static Storage class.

4 : External Storage class.

1: Automatic Storage class: To define a variable as automatic storage class, the keyword „auto‟ is used.
By defining a variable as automatic storage class, it is stored in the memory. The default value of the
variable will be garbage value. Scope of the variable is within the block where it is defined and the life of
the variable is until the control remains within the block.

Syntax : auto data_type variable_name;

auto int a,b;

Example:

void main()

int detail;

or

auto int detail; //Both are same

The variables a and b are declared as integer type and auto. The keyword auto is not mandatory. Because
the default storage class in C is auto.

12
Note: A variable declared inside a function without any storage class specification, is by default an
automatic variable. Automatic variables can also be called local variables because they are local to a
function.

2: Register Storage class : To define a variable as register storage class, the keyword „register‟ is used. If
CPU cannot store the variables in CPU registers, then the variables are assumed as auto and stored in the
memory. When a variable is declared as register, it is stored in the CPU registers. The default value of the
variable will be garbage value. Scope of the variable within the block where it is defined and the life of the
variables is until the control remains within the block.

Register variable has faster access than normal variable. Frequently used variables are kept in register. Only
few variables can be placed inside register.

NOTE : We can't get the address of register variable

13
Sytax : register data_type variable_name;

Ex: register int i;

3: Static Storage class: When a variable is declared as static, it is stored in the memory. The default value
of the variable will be zero. Scope of the variable is within the block where it is defined and the life of the
variable persists between different function calls. To define a variable as static storage class, the keyword
„static‟ is used. A static variable can be initialized only once, it cannot be reinitialized.

Syntax : static data_type variable_name;

Ex: static int i;

14
4 : External Storage class : When a variable is declared as extern, it is stored in the memory. The default
value is initialized to zero. The scope of the variable is global and the life of the variable is until the program
execution comes to an end. To define a variable as external storage class, the keyword „extern‟ is used. An
extern variable is also called as a global variable.

Global variables remain available throughout the entire program. One important thing to remember about
global variable is that their values can be changed by any function in the program.

Systax : extern data_type variable_name;

extern int i;

Ex:

int number;

void main()

number=10;

15
}

fun1()

number=20;

fun2()

number=30;

Here the global variable number is available to all three functions.

Ex : void fun1();

void fun2();

int e=20;

void main()

fun1();

fun2();

void fun1()

extern int e;

printf(“e number is :%d”,e);

void fun2()

16
printf(“e number is :%d”,e);

}
extern keyword

The extern keyword is used before a variable to inform the compiler that this variable is declared somewhere
else. The extern declaration does not allocate storage for variables.

---------------------------------------------------------------------------------------------------------------------------

17
**Recursion/ Recursive Functions
When function is called within the same function, it is known as recursion in C. The function which calls
the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail
recursion, we generally call the same function with return statement.

Features :

There should be at least one if statement used to terminate recursion.

It does not contain any looping statements.

Advantages :

It is easy to use.

It represents compact programming structures.

Disadvantages :

It is slower than that of looping statements because each time function is called.

Note: while using recursion, programmers need to be careful to define an exit condition from the function,
otherwise it will go into an infinite loop. Recursive functions are very useful to solve many mathematical
problems, such as calculating the factorial of a number, generating Fibonacci series, etc.

18
Example Program on Recursion :

/*C- program to print factorial number using tail recursion */

#include<stdio.h>

#include<conio.h>

int factorial (int n)

if ( n < 0)

return -1; /*Wrong value*/

if (n == 0)

return 1; /*Terminating condition*/

return (n * factorial (n -1));

void main()
{

int fact=0;

clrscr();

fact=factorial(5);

printf("\n factorial of 5 is %d",fact);

getch();

Output

factorial of 5 is 120

The following shows how the recursion function “factorial(n) “ works

19
**********************

20
Introduction to Programming -Unit-5

File Handling

Files/File management/File Handling/File operations in C.

File : A File is collection of related data stored in permanent memory.

File operations : The following are the basic file operations.

1. Creating and Naming a file


2. Opening a file
3. Writing data to a file
4. Reading data from a file
5. Closing a file

1. Creating and Naming a File: To perform File operations , first we should declare “
File Pointer “ which represents starting address of file .
Example : FILE *fptr;
Here , FILE is defined data type.
After that, we give name to file which contain two parts which are Name of file and Extension- of
file.
Example: student . txt

2. Opening a file: To perform I/O operations on a file, the file must be opened. For opening a file,
we use system defined function “fopen( )” as follows :

Example :

fptr = fopen( “student . txt ”, ”w”);

Different modes in opening file or fopen():


‘w’ means file opened for “writing” mode(purpose) only.
,‘r’ used for open file for “reading” purpose only.

‘a’ used for open file for “appending” (adding data) purpose.

3. Writing to a file : To write(save) data to the file , we use following functions :

- fputs( ) : It writes strings to the file through file pointer

Ex : char name[30] =”Raju”;


fputs(name, fptr) ;

1
Introduction to Programming -Unit-5

- fprintf( ) : It writes list of different values to files through the file pointer.
Ex : int rollno=7;
Float marks =97.3;
fprintf ( fptr, “%d %f”, rollno, marks) ;

4. Reading a file : To read data from the file , we use following functions:

- fgets( ) : It reads string from file through file pointer.


Ex : char name[10];

fgets(name,10,fptr) ;

- fscanf( ) : It reads list of values from files through the file pointer.

Ex : fscanf( fptr, “ %d %f ”, & rno, & marks) ;

5. Closing a file : After performing required operations on files, the already opened files must be
closed. For this , we use “ fclose( ) “ function as follows :
Example : fclose(fptr);
……………………………………………………………………………………………………………………………………………………

/*Write C- program to read and write student data using File handling functions */

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

struct Student
{
int roll;
char name[50];
float marks;
};

int main()
{
struct Student s;
FILE *fp;
int n, i;

/*Writing data to file*/


fp = fopen("[Link]", "w");
2
Introduction to Programming -Unit-5

if (fp == NULL)
{
printf("Error opening file!\n");
exit(1);
}

printf("Enter number of students: ");


scanf("%d", &n);

for (i = 0; i < n; i++)


{
printf("\nEnter details of student %d:\n", i + 1);
printf("Roll Number: ");
scanf("%d", &[Link]);
printf("Name: ");
scanf("%s", [Link]);
printf("Marks: ");
scanf("%f", &[Link]);

fprintf(fp, "%d %s %.2f\n", [Link], [Link], [Link]);


}

fclose(fp);
printf("\n Data written to file successfully.\n");

/* Reading data from file */

fp = fopen("[Link]", "r");

if (fp == NULL)
{
printf("Error opening file!\n");
exit(1);
}

printf("\n Student Details from File:\n");


printf("---------------------------------\n");

while (fscanf(fp, "%d %s %f", &[Link], [Link], &[Link]) != EOF)


{
printf("Roll: %d \t Name: %s \t Marks: %.2f \n", [Link], [Link], [Link]);
}

3
Introduction to Programming -Unit-5

fclose(fp);
return 0;
}

Output :
Enter number of students: 3

Enter details of student 1:


Roll Number: 101
Name: Ravi
Marks: 85.5

Enter details of student 2:


Roll Number: 102
Name: Sita
Marks: 90.0

Enter details of student 3:


Roll Number: 103
Name: Arjun
Marks: 78.5

Data written to file successfully.

Student Details from File:


---------------------------------
Roll: 101 Name: Ravi Marks: 85.50
Roll: 102 Name: Sita Marks: 90.00
Roll: 103 Name: Arjun Marks: 78.50

****************************************************************

**Header File :

A header file is a file with the extension .h that provides declarations and definitions needed for a C program to
use standard or user-defined functions.

Examples :

[Link].h For standard input and output functions like printf(), scanf(), fopen(), fprintf(), etc.
[Link].h For mathematical functions like sqrt(), pow(), sin(), cos(), etc.
-------------------------------------------------------------------------

4
Introduction to Programming -Unit-5

** Simple C- program to write(save) data into file

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

int main()
{
FILE *fp;
char name[50];
int age;

// Open file in write mode

fp = fopen("[Link]", "w");

printf("Enter your name: ");


scanf("%s", name);

printf("Enter your age: ");


scanf("%d", &age);

// Write data into file

fprintf( fp, " %s %d", name, age);

fclose(fp); // Close the file

printf(“\n Data written successfully to '[Link]'\n");

return 0;
}
Output:
Enter your name: Raju
Enter your age: 20
Data written successfully to '[Link]'

You might also like